babylon.2.1-alpha.debug.js 1.4 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };var BABYLON;
  7. (function (BABYLON) {
  8. var Color3 = (function () {
  9. function Color3(r, g, b) {
  10. if (r === void 0) { r = 0; }
  11. if (g === void 0) { g = 0; }
  12. if (b === void 0) { b = 0; }
  13. this.r = r;
  14. this.g = g;
  15. this.b = b;
  16. }
  17. Color3.prototype.toString = function () {
  18. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  19. };
  20. // Operators
  21. Color3.prototype.toArray = function (array, index) {
  22. if (index === undefined) {
  23. index = 0;
  24. }
  25. array[index] = this.r;
  26. array[index + 1] = this.g;
  27. array[index + 2] = this.b;
  28. return this;
  29. };
  30. Color3.prototype.toColor4 = function (alpha) {
  31. if (alpha === void 0) { alpha = 1; }
  32. return new Color4(this.r, this.g, this.b, alpha);
  33. };
  34. Color3.prototype.asArray = function () {
  35. var result = [];
  36. this.toArray(result, 0);
  37. return result;
  38. };
  39. Color3.prototype.toLuminance = function () {
  40. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  41. };
  42. Color3.prototype.multiply = function (otherColor) {
  43. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  44. };
  45. Color3.prototype.multiplyToRef = function (otherColor, result) {
  46. result.r = this.r * otherColor.r;
  47. result.g = this.g * otherColor.g;
  48. result.b = this.b * otherColor.b;
  49. return this;
  50. };
  51. Color3.prototype.equals = function (otherColor) {
  52. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  53. };
  54. Color3.prototype.scale = function (scale) {
  55. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  56. };
  57. Color3.prototype.scaleToRef = function (scale, result) {
  58. result.r = this.r * scale;
  59. result.g = this.g * scale;
  60. result.b = this.b * scale;
  61. return this;
  62. };
  63. Color3.prototype.add = function (otherColor) {
  64. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  65. };
  66. Color3.prototype.addToRef = function (otherColor, result) {
  67. result.r = this.r + otherColor.r;
  68. result.g = this.g + otherColor.g;
  69. result.b = this.b + otherColor.b;
  70. return this;
  71. };
  72. Color3.prototype.subtract = function (otherColor) {
  73. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  74. };
  75. Color3.prototype.subtractToRef = function (otherColor, result) {
  76. result.r = this.r - otherColor.r;
  77. result.g = this.g - otherColor.g;
  78. result.b = this.b - otherColor.b;
  79. return this;
  80. };
  81. Color3.prototype.clone = function () {
  82. return new Color3(this.r, this.g, this.b);
  83. };
  84. Color3.prototype.copyFrom = function (source) {
  85. this.r = source.r;
  86. this.g = source.g;
  87. this.b = source.b;
  88. return this;
  89. };
  90. Color3.prototype.copyFromFloats = function (r, g, b) {
  91. this.r = r;
  92. this.g = g;
  93. this.b = b;
  94. return this;
  95. };
  96. // Statics
  97. Color3.FromArray = function (array, offset) {
  98. if (offset === void 0) { offset = 0; }
  99. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  100. };
  101. Color3.FromInts = function (r, g, b) {
  102. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  103. };
  104. Color3.Lerp = function (start, end, amount) {
  105. var r = start.r + ((end.r - start.r) * amount);
  106. var g = start.g + ((end.g - start.g) * amount);
  107. var b = start.b + ((end.b - start.b) * amount);
  108. return new Color3(r, g, b);
  109. };
  110. Color3.Red = function () {
  111. return new Color3(1, 0, 0);
  112. };
  113. Color3.Green = function () {
  114. return new Color3(0, 1, 0);
  115. };
  116. Color3.Blue = function () {
  117. return new Color3(0, 0, 1);
  118. };
  119. Color3.Black = function () {
  120. return new Color3(0, 0, 0);
  121. };
  122. Color3.White = function () {
  123. return new Color3(1, 1, 1);
  124. };
  125. Color3.Purple = function () {
  126. return new Color3(0.5, 0, 0.5);
  127. };
  128. Color3.Magenta = function () {
  129. return new Color3(1, 0, 1);
  130. };
  131. Color3.Yellow = function () {
  132. return new Color3(1, 1, 0);
  133. };
  134. Color3.Gray = function () {
  135. return new Color3(0.5, 0.5, 0.5);
  136. };
  137. return Color3;
  138. })();
  139. BABYLON.Color3 = Color3;
  140. var Color4 = (function () {
  141. function Color4(r, g, b, a) {
  142. this.r = r;
  143. this.g = g;
  144. this.b = b;
  145. this.a = a;
  146. }
  147. // Operators
  148. Color4.prototype.addInPlace = function (right) {
  149. this.r += right.r;
  150. this.g += right.g;
  151. this.b += right.b;
  152. this.a += right.a;
  153. return this;
  154. };
  155. Color4.prototype.asArray = function () {
  156. var result = [];
  157. this.toArray(result, 0);
  158. return result;
  159. };
  160. Color4.prototype.toArray = function (array, index) {
  161. if (index === undefined) {
  162. index = 0;
  163. }
  164. array[index] = this.r;
  165. array[index + 1] = this.g;
  166. array[index + 2] = this.b;
  167. array[index + 3] = this.a;
  168. return this;
  169. };
  170. Color4.prototype.add = function (right) {
  171. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  172. };
  173. Color4.prototype.subtract = function (right) {
  174. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  175. };
  176. Color4.prototype.subtractToRef = function (right, result) {
  177. result.r = this.r - right.r;
  178. result.g = this.g - right.g;
  179. result.b = this.b - right.b;
  180. result.a = this.a - right.a;
  181. return this;
  182. };
  183. Color4.prototype.scale = function (scale) {
  184. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  185. };
  186. Color4.prototype.scaleToRef = function (scale, result) {
  187. result.r = this.r * scale;
  188. result.g = this.g * scale;
  189. result.b = this.b * scale;
  190. result.a = this.a * scale;
  191. return this;
  192. };
  193. Color4.prototype.toString = function () {
  194. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  195. };
  196. Color4.prototype.clone = function () {
  197. return new Color4(this.r, this.g, this.b, this.a);
  198. };
  199. Color4.prototype.copyFrom = function (source) {
  200. this.r = source.r;
  201. this.g = source.g;
  202. this.b = source.b;
  203. this.a = source.a;
  204. return this;
  205. };
  206. // Statics
  207. Color4.Lerp = function (left, right, amount) {
  208. var result = new Color4(0, 0, 0, 0);
  209. Color4.LerpToRef(left, right, amount, result);
  210. return result;
  211. };
  212. Color4.LerpToRef = function (left, right, amount, result) {
  213. result.r = left.r + (right.r - left.r) * amount;
  214. result.g = left.g + (right.g - left.g) * amount;
  215. result.b = left.b + (right.b - left.b) * amount;
  216. result.a = left.a + (right.a - left.a) * amount;
  217. };
  218. Color4.FromArray = function (array, offset) {
  219. if (offset === void 0) { offset = 0; }
  220. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  221. };
  222. Color4.FromInts = function (r, g, b, a) {
  223. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  224. };
  225. return Color4;
  226. })();
  227. BABYLON.Color4 = Color4;
  228. var Vector2 = (function () {
  229. function Vector2(x, y) {
  230. this.x = x;
  231. this.y = y;
  232. }
  233. Vector2.prototype.toString = function () {
  234. return "{X: " + this.x + " Y:" + this.y + "}";
  235. };
  236. // Operators
  237. Vector2.prototype.toArray = function (array, index) {
  238. if (index === void 0) { index = 0; }
  239. array[index] = this.x;
  240. array[index + 1] = this.y;
  241. return this;
  242. };
  243. Vector2.prototype.asArray = function () {
  244. var result = [];
  245. this.toArray(result, 0);
  246. return result;
  247. };
  248. Vector2.prototype.copyFrom = function (source) {
  249. this.x = source.x;
  250. this.y = source.y;
  251. return this;
  252. };
  253. Vector2.prototype.copyFromFloats = function (x, y) {
  254. this.x = x;
  255. this.y = y;
  256. return this;
  257. };
  258. Vector2.prototype.add = function (otherVector) {
  259. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  260. };
  261. Vector2.prototype.addVector3 = function (otherVector) {
  262. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  263. };
  264. Vector2.prototype.subtract = function (otherVector) {
  265. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  266. };
  267. Vector2.prototype.subtractInPlace = function (otherVector) {
  268. this.x -= otherVector.x;
  269. this.y -= otherVector.y;
  270. return this;
  271. };
  272. Vector2.prototype.multiplyInPlace = function (otherVector) {
  273. this.x *= otherVector.x;
  274. this.y *= otherVector.y;
  275. return this;
  276. };
  277. Vector2.prototype.multiply = function (otherVector) {
  278. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  279. };
  280. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  281. result.x = this.x * otherVector.x;
  282. result.y = this.y * otherVector.y;
  283. return this;
  284. };
  285. Vector2.prototype.multiplyByFloats = function (x, y) {
  286. return new Vector2(this.x * x, this.y * y);
  287. };
  288. Vector2.prototype.divide = function (otherVector) {
  289. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  290. };
  291. Vector2.prototype.divideToRef = function (otherVector, result) {
  292. result.x = this.x / otherVector.x;
  293. result.y = this.y / otherVector.y;
  294. return this;
  295. };
  296. Vector2.prototype.negate = function () {
  297. return new Vector2(-this.x, -this.y);
  298. };
  299. Vector2.prototype.scaleInPlace = function (scale) {
  300. this.x *= scale;
  301. this.y *= scale;
  302. return this;
  303. };
  304. Vector2.prototype.scale = function (scale) {
  305. return new Vector2(this.x * scale, this.y * scale);
  306. };
  307. Vector2.prototype.equals = function (otherVector) {
  308. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  309. };
  310. // Properties
  311. Vector2.prototype.length = function () {
  312. return Math.sqrt(this.x * this.x + this.y * this.y);
  313. };
  314. Vector2.prototype.lengthSquared = function () {
  315. return (this.x * this.x + this.y * this.y);
  316. };
  317. // Methods
  318. Vector2.prototype.normalize = function () {
  319. var len = this.length();
  320. if (len === 0)
  321. return this;
  322. var num = 1.0 / len;
  323. this.x *= num;
  324. this.y *= num;
  325. return this;
  326. };
  327. Vector2.prototype.clone = function () {
  328. return new Vector2(this.x, this.y);
  329. };
  330. // Statics
  331. Vector2.Zero = function () {
  332. return new Vector2(0, 0);
  333. };
  334. Vector2.FromArray = function (array, offset) {
  335. if (offset === void 0) { offset = 0; }
  336. return new Vector2(array[offset], array[offset + 1]);
  337. };
  338. Vector2.FromArrayToRef = function (array, offset, result) {
  339. result.x = array[offset];
  340. result.y = array[offset + 1];
  341. };
  342. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  346. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  347. return new Vector2(x, y);
  348. };
  349. Vector2.Clamp = function (value, min, max) {
  350. var x = value.x;
  351. x = (x > max.x) ? max.x : x;
  352. x = (x < min.x) ? min.x : x;
  353. var y = value.y;
  354. y = (y > max.y) ? max.y : y;
  355. y = (y < min.y) ? min.y : y;
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  359. var squared = amount * amount;
  360. var cubed = amount * squared;
  361. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  362. var part2 = (-2.0 * cubed) + (3.0 * squared);
  363. var part3 = (cubed - (2.0 * squared)) + amount;
  364. var part4 = cubed - squared;
  365. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  366. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  367. return new Vector2(x, y);
  368. };
  369. Vector2.Lerp = function (start, end, amount) {
  370. var x = start.x + ((end.x - start.x) * amount);
  371. var y = start.y + ((end.y - start.y) * amount);
  372. return new Vector2(x, y);
  373. };
  374. Vector2.Dot = function (left, right) {
  375. return left.x * right.x + left.y * right.y;
  376. };
  377. Vector2.Normalize = function (vector) {
  378. var newVector = vector.clone();
  379. newVector.normalize();
  380. return newVector;
  381. };
  382. Vector2.Minimize = function (left, right) {
  383. var x = (left.x < right.x) ? left.x : right.x;
  384. var y = (left.y < right.y) ? left.y : right.y;
  385. return new Vector2(x, y);
  386. };
  387. Vector2.Maximize = function (left, right) {
  388. var x = (left.x > right.x) ? left.x : right.x;
  389. var y = (left.y > right.y) ? left.y : right.y;
  390. return new Vector2(x, y);
  391. };
  392. Vector2.Transform = function (vector, transformation) {
  393. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  394. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Distance = function (value1, value2) {
  398. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  399. };
  400. Vector2.DistanceSquared = function (value1, value2) {
  401. var x = value1.x - value2.x;
  402. var y = value1.y - value2.y;
  403. return (x * x) + (y * y);
  404. };
  405. return Vector2;
  406. })();
  407. BABYLON.Vector2 = Vector2;
  408. var Vector3 = (function () {
  409. function Vector3(x, y, z) {
  410. this.x = x;
  411. this.y = y;
  412. this.z = z;
  413. }
  414. Vector3.prototype.toString = function () {
  415. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  416. };
  417. // Operators
  418. Vector3.prototype.asArray = function () {
  419. var result = [];
  420. this.toArray(result, 0);
  421. return result;
  422. };
  423. Vector3.prototype.toArray = function (array, index) {
  424. if (index === void 0) { index = 0; }
  425. array[index] = this.x;
  426. array[index + 1] = this.y;
  427. array[index + 2] = this.z;
  428. return this;
  429. };
  430. Vector3.prototype.toQuaternion = function () {
  431. var result = new Quaternion(0, 0, 0, 1);
  432. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  433. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  434. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  435. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  436. var cosy = Math.cos(this.y * 0.5);
  437. var siny = Math.sin(this.y * 0.5);
  438. result.x = coszMinusx * siny;
  439. result.y = -sinzMinusx * siny;
  440. result.z = sinxPlusz * cosy;
  441. result.w = cosxPlusz * cosy;
  442. return result;
  443. };
  444. Vector3.prototype.addInPlace = function (otherVector) {
  445. this.x += otherVector.x;
  446. this.y += otherVector.y;
  447. this.z += otherVector.z;
  448. return this;
  449. };
  450. Vector3.prototype.add = function (otherVector) {
  451. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  452. };
  453. Vector3.prototype.addToRef = function (otherVector, result) {
  454. result.x = this.x + otherVector.x;
  455. result.y = this.y + otherVector.y;
  456. result.z = this.z + otherVector.z;
  457. return this;
  458. };
  459. Vector3.prototype.subtractInPlace = function (otherVector) {
  460. this.x -= otherVector.x;
  461. this.y -= otherVector.y;
  462. this.z -= otherVector.z;
  463. return this;
  464. };
  465. Vector3.prototype.subtract = function (otherVector) {
  466. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  467. };
  468. Vector3.prototype.subtractToRef = function (otherVector, result) {
  469. result.x = this.x - otherVector.x;
  470. result.y = this.y - otherVector.y;
  471. result.z = this.z - otherVector.z;
  472. return this;
  473. };
  474. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  475. return new Vector3(this.x - x, this.y - y, this.z - z);
  476. };
  477. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  478. result.x = this.x - x;
  479. result.y = this.y - y;
  480. result.z = this.z - z;
  481. return this;
  482. };
  483. Vector3.prototype.negate = function () {
  484. return new Vector3(-this.x, -this.y, -this.z);
  485. };
  486. Vector3.prototype.scaleInPlace = function (scale) {
  487. this.x *= scale;
  488. this.y *= scale;
  489. this.z *= scale;
  490. return this;
  491. };
  492. Vector3.prototype.scale = function (scale) {
  493. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  494. };
  495. Vector3.prototype.scaleToRef = function (scale, result) {
  496. result.x = this.x * scale;
  497. result.y = this.y * scale;
  498. result.z = this.z * scale;
  499. };
  500. Vector3.prototype.equals = function (otherVector) {
  501. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  502. };
  503. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  504. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  505. };
  506. Vector3.prototype.equalsToFloats = function (x, y, z) {
  507. return this.x === x && this.y === y && this.z === z;
  508. };
  509. Vector3.prototype.multiplyInPlace = function (otherVector) {
  510. this.x *= otherVector.x;
  511. this.y *= otherVector.y;
  512. this.z *= otherVector.z;
  513. return this;
  514. };
  515. Vector3.prototype.multiply = function (otherVector) {
  516. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  517. };
  518. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  519. result.x = this.x * otherVector.x;
  520. result.y = this.y * otherVector.y;
  521. result.z = this.z * otherVector.z;
  522. return this;
  523. };
  524. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  525. return new Vector3(this.x * x, this.y * y, this.z * z);
  526. };
  527. Vector3.prototype.divide = function (otherVector) {
  528. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  529. };
  530. Vector3.prototype.divideToRef = function (otherVector, result) {
  531. result.x = this.x / otherVector.x;
  532. result.y = this.y / otherVector.y;
  533. result.z = this.z / otherVector.z;
  534. return this;
  535. };
  536. Vector3.prototype.MinimizeInPlace = function (other) {
  537. if (other.x < this.x)
  538. this.x = other.x;
  539. if (other.y < this.y)
  540. this.y = other.y;
  541. if (other.z < this.z)
  542. this.z = other.z;
  543. return this;
  544. };
  545. Vector3.prototype.MaximizeInPlace = function (other) {
  546. if (other.x > this.x)
  547. this.x = other.x;
  548. if (other.y > this.y)
  549. this.y = other.y;
  550. if (other.z > this.z)
  551. this.z = other.z;
  552. return this;
  553. };
  554. // Properties
  555. Vector3.prototype.length = function () {
  556. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  557. };
  558. Vector3.prototype.lengthSquared = function () {
  559. return (this.x * this.x + this.y * this.y + this.z * this.z);
  560. };
  561. // Methods
  562. Vector3.prototype.normalize = function () {
  563. var len = this.length();
  564. if (len === 0)
  565. return this;
  566. var num = 1.0 / len;
  567. this.x *= num;
  568. this.y *= num;
  569. this.z *= num;
  570. return this;
  571. };
  572. Vector3.prototype.clone = function () {
  573. return new Vector3(this.x, this.y, this.z);
  574. };
  575. Vector3.prototype.copyFrom = function (source) {
  576. this.x = source.x;
  577. this.y = source.y;
  578. this.z = source.z;
  579. return this;
  580. };
  581. Vector3.prototype.copyFromFloats = function (x, y, z) {
  582. this.x = x;
  583. this.y = y;
  584. this.z = z;
  585. return this;
  586. };
  587. // Statics
  588. Vector3.FromArray = function (array, offset) {
  589. if (!offset) {
  590. offset = 0;
  591. }
  592. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  593. };
  594. Vector3.FromArrayToRef = function (array, offset, result) {
  595. result.x = array[offset];
  596. result.y = array[offset + 1];
  597. result.z = array[offset + 2];
  598. };
  599. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  600. result.x = array[offset];
  601. result.y = array[offset + 1];
  602. result.z = array[offset + 2];
  603. };
  604. Vector3.FromFloatsToRef = function (x, y, z, result) {
  605. result.x = x;
  606. result.y = y;
  607. result.z = z;
  608. };
  609. Vector3.Zero = function () {
  610. return new Vector3(0, 0, 0);
  611. };
  612. Vector3.Up = function () {
  613. return new Vector3(0, 1.0, 0);
  614. };
  615. Vector3.TransformCoordinates = function (vector, transformation) {
  616. var result = Vector3.Zero();
  617. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  618. return result;
  619. };
  620. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  621. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  622. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  623. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  624. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  625. result.x = x / w;
  626. result.y = y / w;
  627. result.z = z / w;
  628. };
  629. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  630. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  631. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  632. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  633. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  634. result.x = rx / rw;
  635. result.y = ry / rw;
  636. result.z = rz / rw;
  637. };
  638. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  639. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  640. var m0 = SIMD.float32x4.load(transformation.m, 0);
  641. var m1 = SIMD.float32x4.load(transformation.m, 4);
  642. var m2 = SIMD.float32x4.load(transformation.m, 8);
  643. var m3 = SIMD.float32x4.load(transformation.m, 12);
  644. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  645. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  646. SIMD.float32x4.storeXYZ(result._data, 0, r);
  647. };
  648. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  649. var v0 = SIMD.float32x4.splat(x);
  650. var v1 = SIMD.float32x4.splat(y);
  651. var v2 = SIMD.float32x4.splat(z);
  652. var m0 = SIMD.float32x4.load(transformation.m, 0);
  653. var m1 = SIMD.float32x4.load(transformation.m, 4);
  654. var m2 = SIMD.float32x4.load(transformation.m, 8);
  655. var m3 = SIMD.float32x4.load(transformation.m, 12);
  656. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  657. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  658. SIMD.float32x4.storeXYZ(result._data, 0, r);
  659. };
  660. Vector3.TransformNormal = function (vector, transformation) {
  661. var result = Vector3.Zero();
  662. Vector3.TransformNormalToRef(vector, transformation, result);
  663. return result;
  664. };
  665. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  666. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  667. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  668. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  669. };
  670. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  671. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  672. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  673. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  674. };
  675. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  676. var squared = amount * amount;
  677. var cubed = amount * squared;
  678. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  679. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  680. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  681. return new Vector3(x, y, z);
  682. };
  683. Vector3.Clamp = function (value, min, max) {
  684. var x = value.x;
  685. x = (x > max.x) ? max.x : x;
  686. x = (x < min.x) ? min.x : x;
  687. var y = value.y;
  688. y = (y > max.y) ? max.y : y;
  689. y = (y < min.y) ? min.y : y;
  690. var z = value.z;
  691. z = (z > max.z) ? max.z : z;
  692. z = (z < min.z) ? min.z : z;
  693. return new Vector3(x, y, z);
  694. };
  695. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  696. var squared = amount * amount;
  697. var cubed = amount * squared;
  698. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  699. var part2 = (-2.0 * cubed) + (3.0 * squared);
  700. var part3 = (cubed - (2.0 * squared)) + amount;
  701. var part4 = cubed - squared;
  702. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  703. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  704. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  705. return new Vector3(x, y, z);
  706. };
  707. Vector3.Lerp = function (start, end, amount) {
  708. var x = start.x + ((end.x - start.x) * amount);
  709. var y = start.y + ((end.y - start.y) * amount);
  710. var z = start.z + ((end.z - start.z) * amount);
  711. return new Vector3(x, y, z);
  712. };
  713. Vector3.Dot = function (left, right) {
  714. return (left.x * right.x + left.y * right.y + left.z * right.z);
  715. };
  716. Vector3.Cross = function (left, right) {
  717. var result = Vector3.Zero();
  718. Vector3.CrossToRef(left, right, result);
  719. return result;
  720. };
  721. Vector3.CrossToRef = function (left, right, result) {
  722. result.x = left.y * right.z - left.z * right.y;
  723. result.y = left.z * right.x - left.x * right.z;
  724. result.z = left.x * right.y - left.y * right.x;
  725. };
  726. Vector3.Normalize = function (vector) {
  727. var result = Vector3.Zero();
  728. Vector3.NormalizeToRef(vector, result);
  729. return result;
  730. };
  731. Vector3.NormalizeToRef = function (vector, result) {
  732. result.copyFrom(vector);
  733. result.normalize();
  734. };
  735. Vector3.Project = function (vector, world, transform, viewport) {
  736. var cw = viewport.width;
  737. var ch = viewport.height;
  738. var cx = viewport.x;
  739. var cy = viewport.y;
  740. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  741. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  742. return Vector3.TransformCoordinates(vector, finalMatrix);
  743. };
  744. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  745. var matrix = world.multiply(transform);
  746. matrix.invert();
  747. source.x = source.x / viewportWidth * 2 - 1;
  748. source.y = -(source.y / viewportHeight * 2 - 1);
  749. var vector = Vector3.TransformCoordinates(source, matrix);
  750. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  751. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  752. vector = vector.scale(1.0 / num);
  753. }
  754. return vector;
  755. };
  756. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  757. var matrix = world.multiply(view).multiply(projection);
  758. matrix.invert();
  759. source.x = source.x / viewportWidth * 2 - 1;
  760. source.y = -(source.y / viewportHeight * 2 - 1);
  761. var vector = Vector3.TransformCoordinates(source, matrix);
  762. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  763. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  764. vector = vector.scale(1.0 / num);
  765. }
  766. return vector;
  767. };
  768. Vector3.Minimize = function (left, right) {
  769. var min = left.clone();
  770. min.MinimizeInPlace(right);
  771. return min;
  772. };
  773. Vector3.Maximize = function (left, right) {
  774. var max = left.clone();
  775. max.MaximizeInPlace(right);
  776. return max;
  777. };
  778. Vector3.Distance = function (value1, value2) {
  779. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  780. };
  781. Vector3.DistanceSquared = function (value1, value2) {
  782. var x = value1.x - value2.x;
  783. var y = value1.y - value2.y;
  784. var z = value1.z - value2.z;
  785. return (x * x) + (y * y) + (z * z);
  786. };
  787. Vector3.Center = function (value1, value2) {
  788. var center = value1.add(value2);
  789. center.scaleInPlace(0.5);
  790. return center;
  791. };
  792. return Vector3;
  793. })();
  794. BABYLON.Vector3 = Vector3;
  795. //Vector4 class created for EulerAngle class conversion to Quaternion
  796. var Vector4 = (function () {
  797. function Vector4(x, y, z, w) {
  798. this.x = x;
  799. this.y = y;
  800. this.z = z;
  801. this.w = w;
  802. }
  803. Vector4.prototype.toString = function () {
  804. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  805. };
  806. // Operators
  807. Vector4.prototype.asArray = function () {
  808. var result = [];
  809. this.toArray(result, 0);
  810. return result;
  811. };
  812. Vector4.prototype.toArray = function (array, index) {
  813. if (index === undefined) {
  814. index = 0;
  815. }
  816. array[index] = this.x;
  817. array[index + 1] = this.y;
  818. array[index + 2] = this.z;
  819. array[index + 3] = this.w;
  820. return this;
  821. };
  822. Vector4.prototype.addInPlace = function (otherVector) {
  823. this.x += otherVector.x;
  824. this.y += otherVector.y;
  825. this.z += otherVector.z;
  826. this.w += otherVector.w;
  827. return this;
  828. };
  829. Vector4.prototype.add = function (otherVector) {
  830. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  831. };
  832. Vector4.prototype.addToRef = function (otherVector, result) {
  833. result.x = this.x + otherVector.x;
  834. result.y = this.y + otherVector.y;
  835. result.z = this.z + otherVector.z;
  836. result.w = this.w + otherVector.w;
  837. return this;
  838. };
  839. Vector4.prototype.subtractInPlace = function (otherVector) {
  840. this.x -= otherVector.x;
  841. this.y -= otherVector.y;
  842. this.z -= otherVector.z;
  843. this.w -= otherVector.w;
  844. return this;
  845. };
  846. Vector4.prototype.subtract = function (otherVector) {
  847. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  848. };
  849. Vector4.prototype.subtractToRef = function (otherVector, result) {
  850. result.x = this.x - otherVector.x;
  851. result.y = this.y - otherVector.y;
  852. result.z = this.z - otherVector.z;
  853. result.w = this.w - otherVector.w;
  854. return this;
  855. };
  856. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  857. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  858. };
  859. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  860. result.x = this.x - x;
  861. result.y = this.y - y;
  862. result.z = this.z - z;
  863. result.w = this.w - w;
  864. return this;
  865. };
  866. Vector4.prototype.negate = function () {
  867. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  868. };
  869. Vector4.prototype.scaleInPlace = function (scale) {
  870. this.x *= scale;
  871. this.y *= scale;
  872. this.z *= scale;
  873. this.w *= scale;
  874. return this;
  875. };
  876. Vector4.prototype.scale = function (scale) {
  877. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  878. };
  879. Vector4.prototype.scaleToRef = function (scale, result) {
  880. result.x = this.x * scale;
  881. result.y = this.y * scale;
  882. result.z = this.z * scale;
  883. result.w = this.w * scale;
  884. };
  885. Vector4.prototype.equals = function (otherVector) {
  886. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  887. };
  888. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  889. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  890. };
  891. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  892. return this.x === x && this.y === y && this.z === z && this.w === w;
  893. };
  894. Vector4.prototype.multiplyInPlace = function (otherVector) {
  895. this.x *= otherVector.x;
  896. this.y *= otherVector.y;
  897. this.z *= otherVector.z;
  898. this.w *= otherVector.w;
  899. return this;
  900. };
  901. Vector4.prototype.multiply = function (otherVector) {
  902. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  903. };
  904. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  905. result.x = this.x * otherVector.x;
  906. result.y = this.y * otherVector.y;
  907. result.z = this.z * otherVector.z;
  908. result.w = this.w * otherVector.w;
  909. return this;
  910. };
  911. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  912. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  913. };
  914. Vector4.prototype.divide = function (otherVector) {
  915. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  916. };
  917. Vector4.prototype.divideToRef = function (otherVector, result) {
  918. result.x = this.x / otherVector.x;
  919. result.y = this.y / otherVector.y;
  920. result.z = this.z / otherVector.z;
  921. result.w = this.w / otherVector.w;
  922. return this;
  923. };
  924. Vector4.prototype.MinimizeInPlace = function (other) {
  925. if (other.x < this.x)
  926. this.x = other.x;
  927. if (other.y < this.y)
  928. this.y = other.y;
  929. if (other.z < this.z)
  930. this.z = other.z;
  931. if (other.w < this.w)
  932. this.w = other.w;
  933. return this;
  934. };
  935. Vector4.prototype.MaximizeInPlace = function (other) {
  936. if (other.x > this.x)
  937. this.x = other.x;
  938. if (other.y > this.y)
  939. this.y = other.y;
  940. if (other.z > this.z)
  941. this.z = other.z;
  942. if (other.w > this.w)
  943. this.w = other.w;
  944. return this;
  945. };
  946. // Properties
  947. Vector4.prototype.length = function () {
  948. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  949. };
  950. Vector4.prototype.lengthSquared = function () {
  951. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  952. };
  953. // Methods
  954. Vector4.prototype.normalize = function () {
  955. var len = this.length();
  956. if (len === 0)
  957. return this;
  958. var num = 1.0 / len;
  959. this.x *= num;
  960. this.y *= num;
  961. this.z *= num;
  962. this.w *= num;
  963. return this;
  964. };
  965. Vector4.prototype.clone = function () {
  966. return new Vector4(this.x, this.y, this.z, this.w);
  967. };
  968. Vector4.prototype.copyFrom = function (source) {
  969. this.x = source.x;
  970. this.y = source.y;
  971. this.z = source.z;
  972. this.w = source.w;
  973. return this;
  974. };
  975. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  976. this.x = x;
  977. this.y = y;
  978. this.z = z;
  979. this.w = w;
  980. return this;
  981. };
  982. // Statics
  983. Vector4.FromArray = function (array, offset) {
  984. if (!offset) {
  985. offset = 0;
  986. }
  987. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  988. };
  989. Vector4.FromArrayToRef = function (array, offset, result) {
  990. result.x = array[offset];
  991. result.y = array[offset + 1];
  992. result.z = array[offset + 2];
  993. result.w = array[offset + 3];
  994. };
  995. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  996. result.x = array[offset];
  997. result.y = array[offset + 1];
  998. result.z = array[offset + 2];
  999. result.w = array[offset + 3];
  1000. };
  1001. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1002. result.x = x;
  1003. result.y = y;
  1004. result.z = z;
  1005. result.w = w;
  1006. };
  1007. Vector4.Zero = function () {
  1008. return new Vector4(0, 0, 0, 0);
  1009. };
  1010. Vector4.Normalize = function (vector) {
  1011. var result = Vector4.Zero();
  1012. Vector4.NormalizeToRef(vector, result);
  1013. return result;
  1014. };
  1015. Vector4.NormalizeToRef = function (vector, result) {
  1016. result.copyFrom(vector);
  1017. result.normalize();
  1018. };
  1019. Vector4.Minimize = function (left, right) {
  1020. var min = left.clone();
  1021. min.MinimizeInPlace(right);
  1022. return min;
  1023. };
  1024. Vector4.Maximize = function (left, right) {
  1025. var max = left.clone();
  1026. max.MaximizeInPlace(right);
  1027. return max;
  1028. };
  1029. Vector4.Distance = function (value1, value2) {
  1030. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1031. };
  1032. Vector4.DistanceSquared = function (value1, value2) {
  1033. var x = value1.x - value2.x;
  1034. var y = value1.y - value2.y;
  1035. var z = value1.z - value2.z;
  1036. var w = value1.w - value2.w;
  1037. return (x * x) + (y * y) + (z * z) + (w * w);
  1038. };
  1039. Vector4.Center = function (value1, value2) {
  1040. var center = value1.add(value2);
  1041. center.scaleInPlace(0.5);
  1042. return center;
  1043. };
  1044. return Vector4;
  1045. })();
  1046. BABYLON.Vector4 = Vector4;
  1047. var Quaternion = (function () {
  1048. function Quaternion(x, y, z, w) {
  1049. if (x === void 0) { x = 0; }
  1050. if (y === void 0) { y = 0; }
  1051. if (z === void 0) { z = 0; }
  1052. if (w === void 0) { w = 1; }
  1053. this.x = x;
  1054. this.y = y;
  1055. this.z = z;
  1056. this.w = w;
  1057. }
  1058. Quaternion.prototype.toString = function () {
  1059. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1060. };
  1061. Quaternion.prototype.asArray = function () {
  1062. return [this.x, this.y, this.z, this.w];
  1063. };
  1064. Quaternion.prototype.equals = function (otherQuaternion) {
  1065. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1066. };
  1067. Quaternion.prototype.clone = function () {
  1068. return new Quaternion(this.x, this.y, this.z, this.w);
  1069. };
  1070. Quaternion.prototype.copyFrom = function (other) {
  1071. this.x = other.x;
  1072. this.y = other.y;
  1073. this.z = other.z;
  1074. this.w = other.w;
  1075. return this;
  1076. };
  1077. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1078. this.x = x;
  1079. this.y = y;
  1080. this.z = z;
  1081. this.w = w;
  1082. return this;
  1083. };
  1084. Quaternion.prototype.add = function (other) {
  1085. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1086. };
  1087. Quaternion.prototype.subtract = function (other) {
  1088. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1089. };
  1090. Quaternion.prototype.scale = function (value) {
  1091. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1092. };
  1093. Quaternion.prototype.multiply = function (q1) {
  1094. var result = new Quaternion(0, 0, 0, 1.0);
  1095. this.multiplyToRef(q1, result);
  1096. return result;
  1097. };
  1098. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1099. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1100. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1101. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1102. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1103. return this;
  1104. };
  1105. Quaternion.prototype.length = function () {
  1106. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1107. };
  1108. Quaternion.prototype.normalize = function () {
  1109. var length = 1.0 / this.length();
  1110. this.x *= length;
  1111. this.y *= length;
  1112. this.z *= length;
  1113. this.w *= length;
  1114. return this;
  1115. };
  1116. Quaternion.prototype.toEulerAngles = function () {
  1117. var result = Vector3.Zero();
  1118. this.toEulerAnglesToRef(result);
  1119. return result;
  1120. };
  1121. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1122. //result is an EulerAngles in the in the z-x-z convention
  1123. var qx = this.x;
  1124. var qy = this.y;
  1125. var qz = this.z;
  1126. var qw = this.w;
  1127. var qxy = qx * qy;
  1128. var qxz = qx * qz;
  1129. var qwy = qw * qy;
  1130. var qwz = qw * qz;
  1131. var qwx = qw * qx;
  1132. var qyz = qy * qz;
  1133. var sqx = qx * qx;
  1134. var sqy = qy * qy;
  1135. var determinant = sqx + sqy;
  1136. if (determinant !== 0.000 && determinant !== 1.000) {
  1137. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1138. result.y = Math.acos(1 - 2 * determinant);
  1139. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1140. }
  1141. else {
  1142. if (determinant === 0.0) {
  1143. result.x = 0.0;
  1144. result.y = 0.0;
  1145. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1146. }
  1147. else {
  1148. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1149. result.y = Math.PI;
  1150. result.z = 0.0;
  1151. }
  1152. }
  1153. return this;
  1154. };
  1155. Quaternion.prototype.toRotationMatrix = function (result) {
  1156. var xx = this.x * this.x;
  1157. var yy = this.y * this.y;
  1158. var zz = this.z * this.z;
  1159. var xy = this.x * this.y;
  1160. var zw = this.z * this.w;
  1161. var zx = this.z * this.x;
  1162. var yw = this.y * this.w;
  1163. var yz = this.y * this.z;
  1164. var xw = this.x * this.w;
  1165. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1166. result.m[1] = 2.0 * (xy + zw);
  1167. result.m[2] = 2.0 * (zx - yw);
  1168. result.m[3] = 0;
  1169. result.m[4] = 2.0 * (xy - zw);
  1170. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1171. result.m[6] = 2.0 * (yz + xw);
  1172. result.m[7] = 0;
  1173. result.m[8] = 2.0 * (zx + yw);
  1174. result.m[9] = 2.0 * (yz - xw);
  1175. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1176. result.m[11] = 0;
  1177. result.m[12] = 0;
  1178. result.m[13] = 0;
  1179. result.m[14] = 0;
  1180. result.m[15] = 1.0;
  1181. return this;
  1182. };
  1183. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1184. Quaternion.FromRotationMatrixToRef(matrix, this);
  1185. return this;
  1186. };
  1187. // Statics
  1188. Quaternion.FromRotationMatrix = function (matrix) {
  1189. var result = new Quaternion();
  1190. Quaternion.FromRotationMatrixToRef(matrix, result);
  1191. return result;
  1192. };
  1193. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1194. var data = matrix.m;
  1195. var m11 = data[0], m12 = data[4], m13 = data[8];
  1196. var m21 = data[1], m22 = data[5], m23 = data[9];
  1197. var m31 = data[2], m32 = data[6], m33 = data[10];
  1198. var trace = m11 + m22 + m33;
  1199. var s;
  1200. if (trace > 0) {
  1201. s = 0.5 / Math.sqrt(trace + 1.0);
  1202. result.w = 0.25 / s;
  1203. result.x = (m32 - m23) * s;
  1204. result.y = (m13 - m31) * s;
  1205. result.z = (m21 - m12) * s;
  1206. }
  1207. else if (m11 > m22 && m11 > m33) {
  1208. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1209. result.w = (m32 - m23) / s;
  1210. result.x = 0.25 * s;
  1211. result.y = (m12 + m21) / s;
  1212. result.z = (m13 + m31) / s;
  1213. }
  1214. else if (m22 > m33) {
  1215. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1216. result.w = (m13 - m31) / s;
  1217. result.x = (m12 + m21) / s;
  1218. result.y = 0.25 * s;
  1219. result.z = (m23 + m32) / s;
  1220. }
  1221. else {
  1222. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1223. result.w = (m21 - m12) / s;
  1224. result.x = (m13 + m31) / s;
  1225. result.y = (m23 + m32) / s;
  1226. result.z = 0.25 * s;
  1227. }
  1228. };
  1229. Quaternion.Inverse = function (q) {
  1230. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1231. };
  1232. Quaternion.Identity = function () {
  1233. return new Quaternion(0, 0, 0, 1);
  1234. };
  1235. Quaternion.RotationAxis = function (axis, angle) {
  1236. var result = new Quaternion();
  1237. var sin = Math.sin(angle / 2);
  1238. result.w = Math.cos(angle / 2);
  1239. result.x = axis.x * sin;
  1240. result.y = axis.y * sin;
  1241. result.z = axis.z * sin;
  1242. return result;
  1243. };
  1244. Quaternion.FromArray = function (array, offset) {
  1245. if (!offset) {
  1246. offset = 0;
  1247. }
  1248. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1249. };
  1250. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1251. var result = new Quaternion();
  1252. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1253. return result;
  1254. };
  1255. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1256. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1257. var halfRoll = roll * 0.5;
  1258. var halfPitch = pitch * 0.5;
  1259. var halfYaw = yaw * 0.5;
  1260. var sinRoll = Math.sin(halfRoll);
  1261. var cosRoll = Math.cos(halfRoll);
  1262. var sinPitch = Math.sin(halfPitch);
  1263. var cosPitch = Math.cos(halfPitch);
  1264. var sinYaw = Math.sin(halfYaw);
  1265. var cosYaw = Math.cos(halfYaw);
  1266. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1267. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1268. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1269. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1270. };
  1271. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1272. var result = new Quaternion();
  1273. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1274. return result;
  1275. };
  1276. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1277. // Produces a quaternion from Euler angles in the z-x-z orientation
  1278. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1279. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1280. var halfBeta = beta * 0.5;
  1281. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1282. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1283. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1284. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1285. };
  1286. Quaternion.Slerp = function (left, right, amount) {
  1287. var num2;
  1288. var num3;
  1289. var num = amount;
  1290. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1291. var flag = false;
  1292. if (num4 < 0) {
  1293. flag = true;
  1294. num4 = -num4;
  1295. }
  1296. if (num4 > 0.999999) {
  1297. num3 = 1 - num;
  1298. num2 = flag ? -num : num;
  1299. }
  1300. else {
  1301. var num5 = Math.acos(num4);
  1302. var num6 = (1.0 / Math.sin(num5));
  1303. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1304. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1305. }
  1306. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1307. };
  1308. return Quaternion;
  1309. })();
  1310. BABYLON.Quaternion = Quaternion;
  1311. var Matrix = (function () {
  1312. function Matrix() {
  1313. this.m = new Float32Array(16);
  1314. }
  1315. // Properties
  1316. Matrix.prototype.isIdentity = function () {
  1317. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1318. return false;
  1319. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 || this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 || this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 || this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1320. return false;
  1321. return true;
  1322. };
  1323. Matrix.prototype.determinant = function () {
  1324. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1325. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1326. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1327. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1328. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1329. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1330. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1331. };
  1332. // Methods
  1333. Matrix.prototype.toArray = function () {
  1334. return this.m;
  1335. };
  1336. Matrix.prototype.asArray = function () {
  1337. return this.toArray();
  1338. };
  1339. Matrix.prototype.invert = function () {
  1340. this.invertToRef(this);
  1341. return this;
  1342. };
  1343. Matrix.prototype.invertToRef = function (other) {
  1344. var l1 = this.m[0];
  1345. var l2 = this.m[1];
  1346. var l3 = this.m[2];
  1347. var l4 = this.m[3];
  1348. var l5 = this.m[4];
  1349. var l6 = this.m[5];
  1350. var l7 = this.m[6];
  1351. var l8 = this.m[7];
  1352. var l9 = this.m[8];
  1353. var l10 = this.m[9];
  1354. var l11 = this.m[10];
  1355. var l12 = this.m[11];
  1356. var l13 = this.m[12];
  1357. var l14 = this.m[13];
  1358. var l15 = this.m[14];
  1359. var l16 = this.m[15];
  1360. var l17 = (l11 * l16) - (l12 * l15);
  1361. var l18 = (l10 * l16) - (l12 * l14);
  1362. var l19 = (l10 * l15) - (l11 * l14);
  1363. var l20 = (l9 * l16) - (l12 * l13);
  1364. var l21 = (l9 * l15) - (l11 * l13);
  1365. var l22 = (l9 * l14) - (l10 * l13);
  1366. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1367. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1368. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1369. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1370. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1371. var l28 = (l7 * l16) - (l8 * l15);
  1372. var l29 = (l6 * l16) - (l8 * l14);
  1373. var l30 = (l6 * l15) - (l7 * l14);
  1374. var l31 = (l5 * l16) - (l8 * l13);
  1375. var l32 = (l5 * l15) - (l7 * l13);
  1376. var l33 = (l5 * l14) - (l6 * l13);
  1377. var l34 = (l7 * l12) - (l8 * l11);
  1378. var l35 = (l6 * l12) - (l8 * l10);
  1379. var l36 = (l6 * l11) - (l7 * l10);
  1380. var l37 = (l5 * l12) - (l8 * l9);
  1381. var l38 = (l5 * l11) - (l7 * l9);
  1382. var l39 = (l5 * l10) - (l6 * l9);
  1383. other.m[0] = l23 * l27;
  1384. other.m[4] = l24 * l27;
  1385. other.m[8] = l25 * l27;
  1386. other.m[12] = l26 * l27;
  1387. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1388. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1389. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1390. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1391. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1392. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1393. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1394. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1395. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1396. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1397. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1398. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1399. return this;
  1400. };
  1401. Matrix.prototype.invertToRefSIMD = function (other) {
  1402. var src = this.m;
  1403. var dest = other.m;
  1404. var row0, row1, row2, row3;
  1405. var tmp1;
  1406. var minor0, minor1, minor2, minor3;
  1407. var det;
  1408. // Load the 4 rows
  1409. var src0 = SIMD.float32x4.load(src, 0);
  1410. var src1 = SIMD.float32x4.load(src, 4);
  1411. var src2 = SIMD.float32x4.load(src, 8);
  1412. var src3 = SIMD.float32x4.load(src, 12);
  1413. // Transpose the source matrix. Sort of. Not a true transpose operation
  1414. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1415. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1416. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1417. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1418. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1419. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1420. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1421. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1422. // This is a true transposition, but it will lead to an incorrect result
  1423. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1424. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1425. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1426. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1427. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1428. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1429. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1430. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1431. // ----
  1432. tmp1 = SIMD.float32x4.mul(row2, row3);
  1433. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1434. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1435. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1436. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1437. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1438. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1439. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1440. // ----
  1441. tmp1 = SIMD.float32x4.mul(row1, row2);
  1442. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1443. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1444. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1445. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1446. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1447. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1448. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1449. // ----
  1450. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1451. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1452. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1453. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1454. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1455. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1456. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1457. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1458. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1459. // ----
  1460. tmp1 = SIMD.float32x4.mul(row0, row1);
  1461. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1462. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1463. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1464. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1465. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1466. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1467. // ----
  1468. tmp1 = SIMD.float32x4.mul(row0, row3);
  1469. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1470. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1471. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1472. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1473. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1474. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1475. // ----
  1476. tmp1 = SIMD.float32x4.mul(row0, row2);
  1477. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1478. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1479. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1480. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1481. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1482. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1483. // Compute determinant
  1484. det = SIMD.float32x4.mul(row0, minor0);
  1485. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1486. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1487. tmp1 = SIMD.float32x4.reciprocal(det);
  1488. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1489. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1490. // These shuffles aren't necessary if the faulty transposition is done
  1491. // up at the top of this function.
  1492. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1493. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1494. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1495. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1496. // Compute final values by multiplying with 1/det
  1497. minor0 = SIMD.float32x4.mul(det, minor0);
  1498. minor1 = SIMD.float32x4.mul(det, minor1);
  1499. minor2 = SIMD.float32x4.mul(det, minor2);
  1500. minor3 = SIMD.float32x4.mul(det, minor3);
  1501. SIMD.float32x4.store(dest, 0, minor0);
  1502. SIMD.float32x4.store(dest, 4, minor1);
  1503. SIMD.float32x4.store(dest, 8, minor2);
  1504. SIMD.float32x4.store(dest, 12, minor3);
  1505. return this;
  1506. };
  1507. Matrix.prototype.setTranslation = function (vector3) {
  1508. this.m[12] = vector3.x;
  1509. this.m[13] = vector3.y;
  1510. this.m[14] = vector3.z;
  1511. return this;
  1512. };
  1513. Matrix.prototype.multiply = function (other) {
  1514. var result = new Matrix();
  1515. this.multiplyToRef(other, result);
  1516. return result;
  1517. };
  1518. Matrix.prototype.copyFrom = function (other) {
  1519. for (var index = 0; index < 16; index++) {
  1520. this.m[index] = other.m[index];
  1521. }
  1522. return this;
  1523. };
  1524. Matrix.prototype.copyToArray = function (array, offset) {
  1525. if (offset === void 0) { offset = 0; }
  1526. for (var index = 0; index < 16; index++) {
  1527. array[offset + index] = this.m[index];
  1528. }
  1529. return this;
  1530. };
  1531. Matrix.prototype.multiplyToRef = function (other, result) {
  1532. this.multiplyToArray(other, result.m, 0);
  1533. return this;
  1534. };
  1535. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1536. var tm0 = this.m[0];
  1537. var tm1 = this.m[1];
  1538. var tm2 = this.m[2];
  1539. var tm3 = this.m[3];
  1540. var tm4 = this.m[4];
  1541. var tm5 = this.m[5];
  1542. var tm6 = this.m[6];
  1543. var tm7 = this.m[7];
  1544. var tm8 = this.m[8];
  1545. var tm9 = this.m[9];
  1546. var tm10 = this.m[10];
  1547. var tm11 = this.m[11];
  1548. var tm12 = this.m[12];
  1549. var tm13 = this.m[13];
  1550. var tm14 = this.m[14];
  1551. var tm15 = this.m[15];
  1552. var om0 = other.m[0];
  1553. var om1 = other.m[1];
  1554. var om2 = other.m[2];
  1555. var om3 = other.m[3];
  1556. var om4 = other.m[4];
  1557. var om5 = other.m[5];
  1558. var om6 = other.m[6];
  1559. var om7 = other.m[7];
  1560. var om8 = other.m[8];
  1561. var om9 = other.m[9];
  1562. var om10 = other.m[10];
  1563. var om11 = other.m[11];
  1564. var om12 = other.m[12];
  1565. var om13 = other.m[13];
  1566. var om14 = other.m[14];
  1567. var om15 = other.m[15];
  1568. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1569. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1570. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1571. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1572. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1573. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1574. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1575. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1576. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1577. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1578. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1579. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1580. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1581. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1582. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1583. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1584. return this;
  1585. };
  1586. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1587. if (offset === void 0) { offset = 0; }
  1588. var tm = this.m;
  1589. var om = other.m;
  1590. var om0 = SIMD.float32x4.load(om, 0);
  1591. var om1 = SIMD.float32x4.load(om, 4);
  1592. var om2 = SIMD.float32x4.load(om, 8);
  1593. var om3 = SIMD.float32x4.load(om, 12);
  1594. var tm0 = SIMD.float32x4.load(tm, 0);
  1595. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  1596. var tm1 = SIMD.float32x4.load(tm, 4);
  1597. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  1598. var tm2 = SIMD.float32x4.load(tm, 8);
  1599. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  1600. var tm3 = SIMD.float32x4.load(tm, 12);
  1601. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  1602. };
  1603. Matrix.prototype.equals = function (value) {
  1604. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1605. };
  1606. Matrix.prototype.clone = function () {
  1607. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1608. };
  1609. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1610. translation.x = this.m[12];
  1611. translation.y = this.m[13];
  1612. translation.z = this.m[14];
  1613. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1614. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1615. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1616. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1617. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1618. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1619. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1620. rotation.x = 0;
  1621. rotation.y = 0;
  1622. rotation.z = 0;
  1623. rotation.w = 1;
  1624. return false;
  1625. }
  1626. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1627. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1628. return true;
  1629. };
  1630. // Statics
  1631. Matrix.FromArray = function (array, offset) {
  1632. var result = new Matrix();
  1633. if (!offset) {
  1634. offset = 0;
  1635. }
  1636. Matrix.FromArrayToRef(array, offset, result);
  1637. return result;
  1638. };
  1639. Matrix.FromArrayToRef = function (array, offset, result) {
  1640. for (var index = 0; index < 16; index++) {
  1641. result.m[index] = array[index + offset];
  1642. }
  1643. };
  1644. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1645. result.m[0] = initialM11;
  1646. result.m[1] = initialM12;
  1647. result.m[2] = initialM13;
  1648. result.m[3] = initialM14;
  1649. result.m[4] = initialM21;
  1650. result.m[5] = initialM22;
  1651. result.m[6] = initialM23;
  1652. result.m[7] = initialM24;
  1653. result.m[8] = initialM31;
  1654. result.m[9] = initialM32;
  1655. result.m[10] = initialM33;
  1656. result.m[11] = initialM34;
  1657. result.m[12] = initialM41;
  1658. result.m[13] = initialM42;
  1659. result.m[14] = initialM43;
  1660. result.m[15] = initialM44;
  1661. };
  1662. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1663. var result = new Matrix();
  1664. result.m[0] = initialM11;
  1665. result.m[1] = initialM12;
  1666. result.m[2] = initialM13;
  1667. result.m[3] = initialM14;
  1668. result.m[4] = initialM21;
  1669. result.m[5] = initialM22;
  1670. result.m[6] = initialM23;
  1671. result.m[7] = initialM24;
  1672. result.m[8] = initialM31;
  1673. result.m[9] = initialM32;
  1674. result.m[10] = initialM33;
  1675. result.m[11] = initialM34;
  1676. result.m[12] = initialM41;
  1677. result.m[13] = initialM42;
  1678. result.m[14] = initialM43;
  1679. result.m[15] = initialM44;
  1680. return result;
  1681. };
  1682. Matrix.Compose = function (scale, rotation, translation) {
  1683. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1684. var rotationMatrix = Matrix.Identity();
  1685. rotation.toRotationMatrix(rotationMatrix);
  1686. result = result.multiply(rotationMatrix);
  1687. result.setTranslation(translation);
  1688. return result;
  1689. };
  1690. Matrix.Identity = function () {
  1691. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1692. };
  1693. Matrix.IdentityToRef = function (result) {
  1694. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1695. };
  1696. Matrix.Zero = function () {
  1697. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1698. };
  1699. Matrix.RotationX = function (angle) {
  1700. var result = new Matrix();
  1701. Matrix.RotationXToRef(angle, result);
  1702. return result;
  1703. };
  1704. Matrix.Invert = function (source) {
  1705. var result = new Matrix();
  1706. source.invertToRef(result);
  1707. return result;
  1708. };
  1709. Matrix.RotationXToRef = function (angle, result) {
  1710. var s = Math.sin(angle);
  1711. var c = Math.cos(angle);
  1712. result.m[0] = 1.0;
  1713. result.m[15] = 1.0;
  1714. result.m[5] = c;
  1715. result.m[10] = c;
  1716. result.m[9] = -s;
  1717. result.m[6] = s;
  1718. result.m[1] = 0;
  1719. result.m[2] = 0;
  1720. result.m[3] = 0;
  1721. result.m[4] = 0;
  1722. result.m[7] = 0;
  1723. result.m[8] = 0;
  1724. result.m[11] = 0;
  1725. result.m[12] = 0;
  1726. result.m[13] = 0;
  1727. result.m[14] = 0;
  1728. };
  1729. Matrix.RotationY = function (angle) {
  1730. var result = new Matrix();
  1731. Matrix.RotationYToRef(angle, result);
  1732. return result;
  1733. };
  1734. Matrix.RotationYToRef = function (angle, result) {
  1735. var s = Math.sin(angle);
  1736. var c = Math.cos(angle);
  1737. result.m[5] = 1.0;
  1738. result.m[15] = 1.0;
  1739. result.m[0] = c;
  1740. result.m[2] = -s;
  1741. result.m[8] = s;
  1742. result.m[10] = c;
  1743. result.m[1] = 0;
  1744. result.m[3] = 0;
  1745. result.m[4] = 0;
  1746. result.m[6] = 0;
  1747. result.m[7] = 0;
  1748. result.m[9] = 0;
  1749. result.m[11] = 0;
  1750. result.m[12] = 0;
  1751. result.m[13] = 0;
  1752. result.m[14] = 0;
  1753. };
  1754. Matrix.RotationZ = function (angle) {
  1755. var result = new Matrix();
  1756. Matrix.RotationZToRef(angle, result);
  1757. return result;
  1758. };
  1759. Matrix.RotationZToRef = function (angle, result) {
  1760. var s = Math.sin(angle);
  1761. var c = Math.cos(angle);
  1762. result.m[10] = 1.0;
  1763. result.m[15] = 1.0;
  1764. result.m[0] = c;
  1765. result.m[1] = s;
  1766. result.m[4] = -s;
  1767. result.m[5] = c;
  1768. result.m[2] = 0;
  1769. result.m[3] = 0;
  1770. result.m[6] = 0;
  1771. result.m[7] = 0;
  1772. result.m[8] = 0;
  1773. result.m[9] = 0;
  1774. result.m[11] = 0;
  1775. result.m[12] = 0;
  1776. result.m[13] = 0;
  1777. result.m[14] = 0;
  1778. };
  1779. Matrix.RotationAxis = function (axis, angle) {
  1780. var s = Math.sin(-angle);
  1781. var c = Math.cos(-angle);
  1782. var c1 = 1 - c;
  1783. axis.normalize();
  1784. var result = Matrix.Zero();
  1785. result.m[0] = (axis.x * axis.x) * c1 + c;
  1786. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1787. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1788. result.m[3] = 0.0;
  1789. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1790. result.m[5] = (axis.y * axis.y) * c1 + c;
  1791. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1792. result.m[7] = 0.0;
  1793. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1794. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1795. result.m[10] = (axis.z * axis.z) * c1 + c;
  1796. result.m[11] = 0.0;
  1797. result.m[15] = 1.0;
  1798. return result;
  1799. };
  1800. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1801. var result = new Matrix();
  1802. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1803. return result;
  1804. };
  1805. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1806. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1807. this._tempQuaternion.toRotationMatrix(result);
  1808. };
  1809. Matrix.Scaling = function (x, y, z) {
  1810. var result = Matrix.Zero();
  1811. Matrix.ScalingToRef(x, y, z, result);
  1812. return result;
  1813. };
  1814. Matrix.ScalingToRef = function (x, y, z, result) {
  1815. result.m[0] = x;
  1816. result.m[1] = 0;
  1817. result.m[2] = 0;
  1818. result.m[3] = 0;
  1819. result.m[4] = 0;
  1820. result.m[5] = y;
  1821. result.m[6] = 0;
  1822. result.m[7] = 0;
  1823. result.m[8] = 0;
  1824. result.m[9] = 0;
  1825. result.m[10] = z;
  1826. result.m[11] = 0;
  1827. result.m[12] = 0;
  1828. result.m[13] = 0;
  1829. result.m[14] = 0;
  1830. result.m[15] = 1.0;
  1831. };
  1832. Matrix.Translation = function (x, y, z) {
  1833. var result = Matrix.Identity();
  1834. Matrix.TranslationToRef(x, y, z, result);
  1835. return result;
  1836. };
  1837. Matrix.TranslationToRef = function (x, y, z, result) {
  1838. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1839. };
  1840. Matrix.LookAtLH = function (eye, target, up) {
  1841. var result = Matrix.Zero();
  1842. Matrix.LookAtLHToRef(eye, target, up, result);
  1843. return result;
  1844. };
  1845. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1846. // Z axis
  1847. target.subtractToRef(eye, this._zAxis);
  1848. this._zAxis.normalize();
  1849. // X axis
  1850. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1851. this._xAxis.normalize();
  1852. // Y axis
  1853. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1854. this._yAxis.normalize();
  1855. // Eye angles
  1856. var ex = -Vector3.Dot(this._xAxis, eye);
  1857. var ey = -Vector3.Dot(this._yAxis, eye);
  1858. var ez = -Vector3.Dot(this._zAxis, eye);
  1859. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1860. };
  1861. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  1862. var out = result.m;
  1863. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  1864. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  1865. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  1866. // cc.kmVec3Subtract(f, pCenter, pEye);
  1867. var f = SIMD.float32x4.sub(center, eye);
  1868. // cc.kmVec3Normalize(f, f);
  1869. var tmp = SIMD.float32x4.mul(f, f);
  1870. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1871. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrt(tmp));
  1872. // cc.kmVec3Assign(up, pUp);
  1873. // cc.kmVec3Normalize(up, up);
  1874. tmp = SIMD.float32x4.mul(up, up);
  1875. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1876. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrt(tmp));
  1877. // cc.kmVec3Cross(s, f, up);
  1878. var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
  1879. // cc.kmVec3Normalize(s, s);
  1880. tmp = SIMD.float32x4.mul(s, s);
  1881. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1882. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrt(tmp));
  1883. // cc.kmVec3Cross(u, s, f);
  1884. var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
  1885. // cc.kmVec3Normalize(s, s);
  1886. tmp = SIMD.float32x4.mul(s, s);
  1887. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1888. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrt(tmp));
  1889. //cc.kmMat4Identity(pOut);
  1890. //pOut.mat[0] = s.x;
  1891. //pOut.mat[4] = s.y;
  1892. //pOut.mat[8] = s.z;
  1893. //pOut.mat[1] = u.x;
  1894. //pOut.mat[5] = u.y;
  1895. //pOut.mat[9] = u.z;
  1896. //pOut.mat[2] = -f.x;
  1897. //pOut.mat[6] = -f.y;
  1898. //pOut.mat[10] = -f.z;
  1899. var zero = SIMD.float32x4.splat(0.0);
  1900. s = SIMD.float32x4.neg(s);
  1901. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  1902. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  1903. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1904. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  1905. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  1906. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  1907. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1908. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  1909. // cc.kmMat4Translation(translate, -pEye.x, -pEye.y, -pEye.z);
  1910. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  1911. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  1912. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  1913. var b3 = SIMD.float32x4.neg(eye);
  1914. b3 = SIMD.float32x4.withW(b3, 1.0);
  1915. // cc.kmMat4Multiply(pOut, pOut, translate);
  1916. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  1917. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  1918. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  1919. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  1920. };
  1921. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1922. var matrix = Matrix.Zero();
  1923. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1924. return matrix;
  1925. };
  1926. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1927. var hw = 2.0 / width;
  1928. var hh = 2.0 / height;
  1929. var id = 1.0 / (zfar - znear);
  1930. var nid = znear / (znear - zfar);
  1931. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1932. };
  1933. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1934. var matrix = Matrix.Zero();
  1935. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1936. return matrix;
  1937. };
  1938. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1939. result.m[0] = 2.0 / (right - left);
  1940. result.m[1] = result.m[2] = result.m[3] = 0;
  1941. result.m[5] = 2.0 / (top - bottom);
  1942. result.m[4] = result.m[6] = result.m[7] = 0;
  1943. result.m[10] = -1.0 / (znear - zfar);
  1944. result.m[8] = result.m[9] = result.m[11] = 0;
  1945. result.m[12] = (left + right) / (left - right);
  1946. result.m[13] = (top + bottom) / (bottom - top);
  1947. result.m[14] = znear / (znear - zfar);
  1948. result.m[15] = 1.0;
  1949. };
  1950. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1951. var matrix = Matrix.Zero();
  1952. matrix.m[0] = (2.0 * znear) / width;
  1953. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1954. matrix.m[5] = (2.0 * znear) / height;
  1955. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1956. matrix.m[10] = -zfar / (znear - zfar);
  1957. matrix.m[8] = matrix.m[9] = 0.0;
  1958. matrix.m[11] = 1.0;
  1959. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1960. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1961. return matrix;
  1962. };
  1963. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1964. var matrix = Matrix.Zero();
  1965. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1966. return matrix;
  1967. };
  1968. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1969. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1970. var tan = 1.0 / (Math.tan(fov * 0.5));
  1971. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1972. if (v_fixed) {
  1973. result.m[0] = tan / aspect;
  1974. }
  1975. else {
  1976. result.m[0] = tan;
  1977. }
  1978. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1979. if (v_fixed) {
  1980. result.m[5] = tan;
  1981. }
  1982. else {
  1983. result.m[5] = tan * aspect;
  1984. }
  1985. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1986. result.m[8] = result.m[9] = 0.0;
  1987. result.m[10] = -zfar / (znear - zfar);
  1988. result.m[11] = 1.0;
  1989. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1990. result.m[14] = (znear * zfar) / (znear - zfar);
  1991. };
  1992. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1993. var cw = viewport.width;
  1994. var ch = viewport.height;
  1995. var cx = viewport.x;
  1996. var cy = viewport.y;
  1997. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  1998. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1999. };
  2000. Matrix.Transpose = function (matrix) {
  2001. var result = new Matrix();
  2002. result.m[0] = matrix.m[0];
  2003. result.m[1] = matrix.m[4];
  2004. result.m[2] = matrix.m[8];
  2005. result.m[3] = matrix.m[12];
  2006. result.m[4] = matrix.m[1];
  2007. result.m[5] = matrix.m[5];
  2008. result.m[6] = matrix.m[9];
  2009. result.m[7] = matrix.m[13];
  2010. result.m[8] = matrix.m[2];
  2011. result.m[9] = matrix.m[6];
  2012. result.m[10] = matrix.m[10];
  2013. result.m[11] = matrix.m[14];
  2014. result.m[12] = matrix.m[3];
  2015. result.m[13] = matrix.m[7];
  2016. result.m[14] = matrix.m[11];
  2017. result.m[15] = matrix.m[15];
  2018. return result;
  2019. };
  2020. Matrix.Reflection = function (plane) {
  2021. var matrix = new Matrix();
  2022. Matrix.ReflectionToRef(plane, matrix);
  2023. return matrix;
  2024. };
  2025. Matrix.ReflectionToRef = function (plane, result) {
  2026. plane.normalize();
  2027. var x = plane.normal.x;
  2028. var y = plane.normal.y;
  2029. var z = plane.normal.z;
  2030. var temp = -2 * x;
  2031. var temp2 = -2 * y;
  2032. var temp3 = -2 * z;
  2033. result.m[0] = (temp * x) + 1;
  2034. result.m[1] = temp2 * x;
  2035. result.m[2] = temp3 * x;
  2036. result.m[3] = 0.0;
  2037. result.m[4] = temp * y;
  2038. result.m[5] = (temp2 * y) + 1;
  2039. result.m[6] = temp3 * y;
  2040. result.m[7] = 0.0;
  2041. result.m[8] = temp * z;
  2042. result.m[9] = temp2 * z;
  2043. result.m[10] = (temp3 * z) + 1;
  2044. result.m[11] = 0.0;
  2045. result.m[12] = temp * plane.d;
  2046. result.m[13] = temp2 * plane.d;
  2047. result.m[14] = temp3 * plane.d;
  2048. result.m[15] = 1.0;
  2049. };
  2050. Matrix._tempQuaternion = new Quaternion();
  2051. Matrix._xAxis = Vector3.Zero();
  2052. Matrix._yAxis = Vector3.Zero();
  2053. Matrix._zAxis = Vector3.Zero();
  2054. return Matrix;
  2055. })();
  2056. BABYLON.Matrix = Matrix;
  2057. var Plane = (function () {
  2058. function Plane(a, b, c, d) {
  2059. this.normal = new Vector3(a, b, c);
  2060. this.d = d;
  2061. }
  2062. Plane.prototype.asArray = function () {
  2063. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2064. };
  2065. // Methods
  2066. Plane.prototype.clone = function () {
  2067. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2068. };
  2069. Plane.prototype.normalize = function () {
  2070. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2071. var magnitude = 0;
  2072. if (norm !== 0) {
  2073. magnitude = 1.0 / norm;
  2074. }
  2075. this.normal.x *= magnitude;
  2076. this.normal.y *= magnitude;
  2077. this.normal.z *= magnitude;
  2078. this.d *= magnitude;
  2079. return this;
  2080. };
  2081. Plane.prototype.transform = function (transformation) {
  2082. var transposedMatrix = Matrix.Transpose(transformation);
  2083. var x = this.normal.x;
  2084. var y = this.normal.y;
  2085. var z = this.normal.z;
  2086. var d = this.d;
  2087. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2088. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2089. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2090. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2091. return new Plane(normalX, normalY, normalZ, finalD);
  2092. };
  2093. Plane.prototype.dotCoordinate = function (point) {
  2094. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2095. };
  2096. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2097. var x1 = point2.x - point1.x;
  2098. var y1 = point2.y - point1.y;
  2099. var z1 = point2.z - point1.z;
  2100. var x2 = point3.x - point1.x;
  2101. var y2 = point3.y - point1.y;
  2102. var z2 = point3.z - point1.z;
  2103. var yz = (y1 * z2) - (z1 * y2);
  2104. var xz = (z1 * x2) - (x1 * z2);
  2105. var xy = (x1 * y2) - (y1 * x2);
  2106. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2107. var invPyth;
  2108. if (pyth !== 0) {
  2109. invPyth = 1.0 / pyth;
  2110. }
  2111. else {
  2112. invPyth = 0;
  2113. }
  2114. this.normal.x = yz * invPyth;
  2115. this.normal.y = xz * invPyth;
  2116. this.normal.z = xy * invPyth;
  2117. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2118. return this;
  2119. };
  2120. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2121. var dot = Vector3.Dot(this.normal, direction);
  2122. return (dot <= epsilon);
  2123. };
  2124. Plane.prototype.signedDistanceTo = function (point) {
  2125. return Vector3.Dot(point, this.normal) + this.d;
  2126. };
  2127. // Statics
  2128. Plane.FromArray = function (array) {
  2129. return new Plane(array[0], array[1], array[2], array[3]);
  2130. };
  2131. Plane.FromPoints = function (point1, point2, point3) {
  2132. var result = new Plane(0, 0, 0, 0);
  2133. result.copyFromPoints(point1, point2, point3);
  2134. return result;
  2135. };
  2136. Plane.FromPositionAndNormal = function (origin, normal) {
  2137. var result = new Plane(0, 0, 0, 0);
  2138. normal.normalize();
  2139. result.normal = normal;
  2140. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2141. return result;
  2142. };
  2143. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2144. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2145. return Vector3.Dot(point, normal) + d;
  2146. };
  2147. return Plane;
  2148. })();
  2149. BABYLON.Plane = Plane;
  2150. var Viewport = (function () {
  2151. function Viewport(x, y, width, height) {
  2152. this.x = x;
  2153. this.y = y;
  2154. this.width = width;
  2155. this.height = height;
  2156. }
  2157. Viewport.prototype.toGlobal = function (engine) {
  2158. var width = engine.getRenderWidth();
  2159. var height = engine.getRenderHeight();
  2160. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2161. };
  2162. return Viewport;
  2163. })();
  2164. BABYLON.Viewport = Viewport;
  2165. var Frustum = (function () {
  2166. function Frustum() {
  2167. }
  2168. Frustum.GetPlanes = function (transform) {
  2169. var frustumPlanes = [];
  2170. for (var index = 0; index < 6; index++) {
  2171. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2172. }
  2173. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2174. return frustumPlanes;
  2175. };
  2176. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2177. // Near
  2178. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2179. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2180. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2181. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2182. frustumPlanes[0].normalize();
  2183. // Far
  2184. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2185. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2186. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2187. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2188. frustumPlanes[1].normalize();
  2189. // Left
  2190. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2191. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2192. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2193. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2194. frustumPlanes[2].normalize();
  2195. // Right
  2196. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2197. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2198. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2199. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2200. frustumPlanes[3].normalize();
  2201. // Top
  2202. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2203. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2204. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2205. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2206. frustumPlanes[4].normalize();
  2207. // Bottom
  2208. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2209. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2210. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2211. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2212. frustumPlanes[5].normalize();
  2213. };
  2214. return Frustum;
  2215. })();
  2216. BABYLON.Frustum = Frustum;
  2217. var Ray = (function () {
  2218. function Ray(origin, direction, length) {
  2219. if (length === void 0) { length = Number.MAX_VALUE; }
  2220. this.origin = origin;
  2221. this.direction = direction;
  2222. this.length = length;
  2223. }
  2224. // Methods
  2225. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2226. var d = 0.0;
  2227. var maxValue = Number.MAX_VALUE;
  2228. if (Math.abs(this.direction.x) < 0.0000001) {
  2229. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2230. return false;
  2231. }
  2232. }
  2233. else {
  2234. var inv = 1.0 / this.direction.x;
  2235. var min = (minimum.x - this.origin.x) * inv;
  2236. var max = (maximum.x - this.origin.x) * inv;
  2237. if (max === -Infinity) {
  2238. max = Infinity;
  2239. }
  2240. if (min > max) {
  2241. var temp = min;
  2242. min = max;
  2243. max = temp;
  2244. }
  2245. d = Math.max(min, d);
  2246. maxValue = Math.min(max, maxValue);
  2247. if (d > maxValue) {
  2248. return false;
  2249. }
  2250. }
  2251. if (Math.abs(this.direction.y) < 0.0000001) {
  2252. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2253. return false;
  2254. }
  2255. }
  2256. else {
  2257. inv = 1.0 / this.direction.y;
  2258. min = (minimum.y - this.origin.y) * inv;
  2259. max = (maximum.y - this.origin.y) * inv;
  2260. if (max === -Infinity) {
  2261. max = Infinity;
  2262. }
  2263. if (min > max) {
  2264. temp = min;
  2265. min = max;
  2266. max = temp;
  2267. }
  2268. d = Math.max(min, d);
  2269. maxValue = Math.min(max, maxValue);
  2270. if (d > maxValue) {
  2271. return false;
  2272. }
  2273. }
  2274. if (Math.abs(this.direction.z) < 0.0000001) {
  2275. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2276. return false;
  2277. }
  2278. }
  2279. else {
  2280. inv = 1.0 / this.direction.z;
  2281. min = (minimum.z - this.origin.z) * inv;
  2282. max = (maximum.z - this.origin.z) * inv;
  2283. if (max === -Infinity) {
  2284. max = Infinity;
  2285. }
  2286. if (min > max) {
  2287. temp = min;
  2288. min = max;
  2289. max = temp;
  2290. }
  2291. d = Math.max(min, d);
  2292. maxValue = Math.min(max, maxValue);
  2293. if (d > maxValue) {
  2294. return false;
  2295. }
  2296. }
  2297. return true;
  2298. };
  2299. Ray.prototype.intersectsBox = function (box) {
  2300. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2301. };
  2302. Ray.prototype.intersectsSphere = function (sphere) {
  2303. var x = sphere.center.x - this.origin.x;
  2304. var y = sphere.center.y - this.origin.y;
  2305. var z = sphere.center.z - this.origin.z;
  2306. var pyth = (x * x) + (y * y) + (z * z);
  2307. var rr = sphere.radius * sphere.radius;
  2308. if (pyth <= rr) {
  2309. return true;
  2310. }
  2311. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2312. if (dot < 0.0) {
  2313. return false;
  2314. }
  2315. var temp = pyth - (dot * dot);
  2316. return temp <= rr;
  2317. };
  2318. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2319. if (!this._edge1) {
  2320. this._edge1 = Vector3.Zero();
  2321. this._edge2 = Vector3.Zero();
  2322. this._pvec = Vector3.Zero();
  2323. this._tvec = Vector3.Zero();
  2324. this._qvec = Vector3.Zero();
  2325. }
  2326. vertex1.subtractToRef(vertex0, this._edge1);
  2327. vertex2.subtractToRef(vertex0, this._edge2);
  2328. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2329. var det = Vector3.Dot(this._edge1, this._pvec);
  2330. if (det === 0) {
  2331. return null;
  2332. }
  2333. var invdet = 1 / det;
  2334. this.origin.subtractToRef(vertex0, this._tvec);
  2335. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2336. if (bu < 0 || bu > 1.0) {
  2337. return null;
  2338. }
  2339. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2340. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2341. if (bv < 0 || bu + bv > 1.0) {
  2342. return null;
  2343. }
  2344. //check if the distance is longer than the predefined length.
  2345. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2346. if (distance > this.length) {
  2347. return null;
  2348. }
  2349. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2350. };
  2351. // Statics
  2352. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2353. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2354. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2355. var direction = end.subtract(start);
  2356. direction.normalize();
  2357. return new Ray(start, direction);
  2358. };
  2359. /**
  2360. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2361. * transformed to the given world matrix.
  2362. * @param origin The origin point
  2363. * @param end The end point
  2364. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2365. */
  2366. Ray.CreateNewFromTo = function (origin, end, world) {
  2367. if (world === void 0) { world = Matrix.Identity(); }
  2368. var direction = end.subtract(origin);
  2369. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2370. direction.normalize();
  2371. return Ray.Transform(new Ray(origin, direction, length), world);
  2372. };
  2373. Ray.Transform = function (ray, matrix) {
  2374. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2375. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2376. return new Ray(newOrigin, newDirection, ray.length);
  2377. };
  2378. return Ray;
  2379. })();
  2380. BABYLON.Ray = Ray;
  2381. (function (Space) {
  2382. Space[Space["LOCAL"] = 0] = "LOCAL";
  2383. Space[Space["WORLD"] = 1] = "WORLD";
  2384. })(BABYLON.Space || (BABYLON.Space = {}));
  2385. var Space = BABYLON.Space;
  2386. var Axis = (function () {
  2387. function Axis() {
  2388. }
  2389. Axis.X = new Vector3(1, 0, 0);
  2390. Axis.Y = new Vector3(0, 1, 0);
  2391. Axis.Z = new Vector3(0, 0, 1);
  2392. return Axis;
  2393. })();
  2394. BABYLON.Axis = Axis;
  2395. ;
  2396. var BezierCurve = (function () {
  2397. function BezierCurve() {
  2398. }
  2399. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2400. // Extract X (which is equal to time here)
  2401. var f0 = 1 - 3 * x2 + 3 * x1;
  2402. var f1 = 3 * x2 - 6 * x1;
  2403. var f2 = 3 * x1;
  2404. var refinedT = t;
  2405. for (var i = 0; i < 5; i++) {
  2406. var refinedT2 = refinedT * refinedT;
  2407. var refinedT3 = refinedT2 * refinedT;
  2408. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2409. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2410. refinedT -= (x - t) * slope;
  2411. refinedT = Math.min(1, Math.max(0, refinedT));
  2412. }
  2413. // Resolve cubic bezier for the given x
  2414. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2415. };
  2416. return BezierCurve;
  2417. })();
  2418. BABYLON.BezierCurve = BezierCurve;
  2419. (function (Orientation) {
  2420. Orientation[Orientation["CW"] = 0] = "CW";
  2421. Orientation[Orientation["CCW"] = 1] = "CCW";
  2422. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2423. var Orientation = BABYLON.Orientation;
  2424. var Angle = (function () {
  2425. function Angle(radians) {
  2426. var _this = this;
  2427. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2428. this.radians = function () { return _this._radians; };
  2429. this._radians = radians;
  2430. if (this._radians < 0)
  2431. this._radians += (2 * Math.PI);
  2432. }
  2433. Angle.BetweenTwoPoints = function (a, b) {
  2434. var delta = b.subtract(a);
  2435. var theta = Math.atan2(delta.y, delta.x);
  2436. return new Angle(theta);
  2437. };
  2438. Angle.FromRadians = function (radians) {
  2439. return new Angle(radians);
  2440. };
  2441. Angle.FromDegrees = function (degrees) {
  2442. return new Angle(degrees * Math.PI / 180);
  2443. };
  2444. return Angle;
  2445. })();
  2446. BABYLON.Angle = Angle;
  2447. var Arc2 = (function () {
  2448. function Arc2(startPoint, midPoint, endPoint) {
  2449. this.startPoint = startPoint;
  2450. this.midPoint = midPoint;
  2451. this.endPoint = endPoint;
  2452. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2453. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2454. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2455. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2456. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2457. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2458. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2459. var a1 = this.startAngle.degrees();
  2460. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2461. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2462. // angles correction
  2463. if (a2 - a1 > +180.0)
  2464. a2 -= 360.0;
  2465. if (a2 - a1 < -180.0)
  2466. a2 += 360.0;
  2467. if (a3 - a2 > +180.0)
  2468. a3 -= 360.0;
  2469. if (a3 - a2 < -180.0)
  2470. a3 += 360.0;
  2471. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2472. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2473. }
  2474. return Arc2;
  2475. })();
  2476. BABYLON.Arc2 = Arc2;
  2477. var PathCursor = (function () {
  2478. function PathCursor(path) {
  2479. this.path = path;
  2480. this._onchange = new Array();
  2481. this.value = 0;
  2482. this.animations = new Array();
  2483. }
  2484. PathCursor.prototype.getPoint = function () {
  2485. var point = this.path.getPointAtLengthPosition(this.value);
  2486. return new Vector3(point.x, 0, point.y);
  2487. };
  2488. PathCursor.prototype.moveAhead = function (step) {
  2489. if (step === void 0) { step = 0.002; }
  2490. this.move(step);
  2491. return this;
  2492. };
  2493. PathCursor.prototype.moveBack = function (step) {
  2494. if (step === void 0) { step = 0.002; }
  2495. this.move(-step);
  2496. return this;
  2497. };
  2498. PathCursor.prototype.move = function (step) {
  2499. if (Math.abs(step) > 1) {
  2500. throw "step size should be less than 1.";
  2501. }
  2502. this.value += step;
  2503. this.ensureLimits();
  2504. this.raiseOnChange();
  2505. return this;
  2506. };
  2507. PathCursor.prototype.ensureLimits = function () {
  2508. while (this.value > 1) {
  2509. this.value -= 1;
  2510. }
  2511. while (this.value < 0) {
  2512. this.value += 1;
  2513. }
  2514. return this;
  2515. };
  2516. // used by animation engine
  2517. PathCursor.prototype.markAsDirty = function (propertyName) {
  2518. this.ensureLimits();
  2519. this.raiseOnChange();
  2520. return this;
  2521. };
  2522. PathCursor.prototype.raiseOnChange = function () {
  2523. var _this = this;
  2524. this._onchange.forEach(function (f) { return f(_this); });
  2525. return this;
  2526. };
  2527. PathCursor.prototype.onchange = function (f) {
  2528. this._onchange.push(f);
  2529. return this;
  2530. };
  2531. return PathCursor;
  2532. })();
  2533. BABYLON.PathCursor = PathCursor;
  2534. var Path2 = (function () {
  2535. function Path2(x, y) {
  2536. this._points = new Array();
  2537. this._length = 0;
  2538. this.closed = false;
  2539. this._points.push(new Vector2(x, y));
  2540. }
  2541. Path2.prototype.addLineTo = function (x, y) {
  2542. if (closed) {
  2543. BABYLON.Tools.Error("cannot add lines to closed paths");
  2544. return this;
  2545. }
  2546. var newPoint = new Vector2(x, y);
  2547. var previousPoint = this._points[this._points.length - 1];
  2548. this._points.push(newPoint);
  2549. this._length += newPoint.subtract(previousPoint).length();
  2550. return this;
  2551. };
  2552. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2553. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2554. if (closed) {
  2555. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2556. return this;
  2557. }
  2558. var startPoint = this._points[this._points.length - 1];
  2559. var midPoint = new Vector2(midX, midY);
  2560. var endPoint = new Vector2(endX, endY);
  2561. var arc = new Arc2(startPoint, midPoint, endPoint);
  2562. var increment = arc.angle.radians() / numberOfSegments;
  2563. if (arc.orientation === 0 /* CW */)
  2564. increment *= -1;
  2565. var currentAngle = arc.startAngle.radians() + increment;
  2566. for (var i = 0; i < numberOfSegments; i++) {
  2567. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2568. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2569. this.addLineTo(x, y);
  2570. currentAngle += increment;
  2571. }
  2572. return this;
  2573. };
  2574. Path2.prototype.close = function () {
  2575. this.closed = true;
  2576. return this;
  2577. };
  2578. Path2.prototype.length = function () {
  2579. var result = this._length;
  2580. if (!this.closed) {
  2581. var lastPoint = this._points[this._points.length - 1];
  2582. var firstPoint = this._points[0];
  2583. result += (firstPoint.subtract(lastPoint).length());
  2584. }
  2585. return result;
  2586. };
  2587. Path2.prototype.getPoints = function () {
  2588. return this._points;
  2589. };
  2590. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2591. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2592. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2593. return Vector2.Zero();
  2594. }
  2595. var lengthPosition = normalizedLengthPosition * this.length();
  2596. var previousOffset = 0;
  2597. for (var i = 0; i < this._points.length; i++) {
  2598. var j = (i + 1) % this._points.length;
  2599. var a = this._points[i];
  2600. var b = this._points[j];
  2601. var bToA = b.subtract(a);
  2602. var nextOffset = (bToA.length() + previousOffset);
  2603. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2604. var dir = bToA.normalize();
  2605. var localOffset = lengthPosition - previousOffset;
  2606. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2607. }
  2608. previousOffset = nextOffset;
  2609. }
  2610. BABYLON.Tools.Error("internal error");
  2611. return Vector2.Zero();
  2612. };
  2613. Path2.StartingAt = function (x, y) {
  2614. return new Path2(x, y);
  2615. };
  2616. return Path2;
  2617. })();
  2618. BABYLON.Path2 = Path2;
  2619. var Path3D = (function () {
  2620. function Path3D(path) {
  2621. this.path = path;
  2622. this._curve = new Array();
  2623. this._distances = new Array();
  2624. this._tangents = new Array();
  2625. this._normals = new Array();
  2626. this._binormals = new Array();
  2627. this._curve = path.slice(); // copy array
  2628. var l = this._curve.length;
  2629. // first and last tangents
  2630. this._tangents[0] = this._curve[1].subtract(this._curve[0]);
  2631. this._tangents[0].normalize();
  2632. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2633. this._tangents[l - 1].normalize();
  2634. // normals and binormals at first point : arbitrary vector with _normalVector()
  2635. var tg0 = this._tangents[0];
  2636. var pp0 = this._normalVector(this._curve[0], tg0);
  2637. this._normals[0] = pp0;
  2638. this._normals[0].normalize();
  2639. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2640. this._normals[0].normalize();
  2641. this._distances[0] = 0;
  2642. // normals and binormals : next points
  2643. var prev; // previous vector (segment)
  2644. var cur; // current vector (segment)
  2645. var curTang; // current tangent
  2646. var prevNorm; // previous normal
  2647. var prevBinor; // previous binormal
  2648. for (var i = 1; i < l; i++) {
  2649. // tangents
  2650. prev = this._curve[i].subtract(this._curve[i - 1]);
  2651. if (i < l - 1) {
  2652. cur = this._curve[i + 1].subtract(this._curve[i]);
  2653. this._tangents[i] = prev.add(cur);
  2654. this._tangents[i].normalize();
  2655. }
  2656. this._distances[i] = this._distances[i - 1] + prev.length();
  2657. // normals and binormals
  2658. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2659. curTang = this._tangents[i];
  2660. prevNorm = this._normals[i - 1];
  2661. prevBinor = this._binormals[i - 1];
  2662. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2663. this._normals[i].normalize();
  2664. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2665. this._binormals[i].normalize();
  2666. }
  2667. }
  2668. Path3D.prototype.getCurve = function () {
  2669. return this._curve;
  2670. };
  2671. Path3D.prototype.getTangents = function () {
  2672. return this._tangents;
  2673. };
  2674. Path3D.prototype.getNormals = function () {
  2675. return this._normals;
  2676. };
  2677. Path3D.prototype.getBinormals = function () {
  2678. return this._binormals;
  2679. };
  2680. Path3D.prototype.getDistances = function () {
  2681. return this._distances;
  2682. };
  2683. // private function normalVector(v0, vt) :
  2684. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2685. Path3D.prototype._normalVector = function (v0, vt) {
  2686. var point;
  2687. if (vt.x !== 1) {
  2688. point = new Vector3(1, 0, 0);
  2689. }
  2690. else if (vt.y !== 1) {
  2691. point = new Vector3(0, 1, 0);
  2692. }
  2693. else if (vt.z !== 1) {
  2694. point = new Vector3(0, 0, 1);
  2695. }
  2696. var normal0 = Vector3.Cross(vt, point);
  2697. normal0.normalize();
  2698. return normal0;
  2699. };
  2700. return Path3D;
  2701. })();
  2702. BABYLON.Path3D = Path3D;
  2703. var Curve3 = (function () {
  2704. function Curve3(points) {
  2705. this._points = points;
  2706. }
  2707. // QuadraticBezier(origin_V3, control_V3, destination_V3 )
  2708. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2709. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2710. var bez = new Array();
  2711. var step = 1 / nbPoints;
  2712. var equation = function (t, val0, val1, val2) {
  2713. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2714. return res;
  2715. };
  2716. for (var i = 0; i <= 1; i += step) {
  2717. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x), equation(i, v0.y, v1.y, v2.y), equation(i, v0.z, v1.z, v2.z)));
  2718. }
  2719. return new Curve3(bez);
  2720. };
  2721. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3)
  2722. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2723. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2724. var bez = new Array();
  2725. var step = 1 / nbPoints;
  2726. var equation = function (t, val0, val1, val2, val3) {
  2727. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2728. return res;
  2729. };
  2730. for (var i = 0; i <= 1; i += step) {
  2731. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x, v3.x), equation(i, v0.y, v1.y, v2.y, v3.y), equation(i, v0.z, v1.z, v2.z, v3.z)));
  2732. }
  2733. return new Curve3(bez);
  2734. };
  2735. Curve3.prototype.getPoints = function () {
  2736. return this._points;
  2737. };
  2738. return Curve3;
  2739. })();
  2740. BABYLON.Curve3 = Curve3;
  2741. // SIMD
  2742. if (window.SIMD !== undefined) {
  2743. // Replace functions
  2744. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2745. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2746. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2747. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2748. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2749. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2750. get: function () {
  2751. return this._data[0];
  2752. },
  2753. set: function (value) {
  2754. if (!this._data) {
  2755. this._data = new Float32Array(3);
  2756. }
  2757. this._data[0] = value;
  2758. }
  2759. });
  2760. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2761. get: function () {
  2762. return this._data[1];
  2763. },
  2764. set: function (value) {
  2765. this._data[1] = value;
  2766. }
  2767. });
  2768. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  2769. get: function () {
  2770. return this._data[2];
  2771. },
  2772. set: function (value) {
  2773. this._data[2] = value;
  2774. }
  2775. });
  2776. }
  2777. })(BABYLON || (BABYLON = {}));
  2778. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2779. (function (BABYLON) {
  2780. // Screenshots
  2781. var screenshotCanvas;
  2782. var cloneValue = function (source, destinationObject) {
  2783. if (!source)
  2784. return null;
  2785. if (source instanceof BABYLON.Mesh) {
  2786. return null;
  2787. }
  2788. if (source instanceof BABYLON.SubMesh) {
  2789. return source.clone(destinationObject);
  2790. }
  2791. else if (source.clone) {
  2792. return source.clone();
  2793. }
  2794. return null;
  2795. };
  2796. var Tools = (function () {
  2797. function Tools() {
  2798. }
  2799. Tools.GetFilename = function (path) {
  2800. var index = path.lastIndexOf("/");
  2801. if (index < 0)
  2802. return path;
  2803. return path.substring(index + 1);
  2804. };
  2805. Tools.GetDOMTextContent = function (element) {
  2806. var result = "";
  2807. var child = element.firstChild;
  2808. while (child) {
  2809. if (child.nodeType === 3) {
  2810. result += child.textContent;
  2811. }
  2812. child = child.nextSibling;
  2813. }
  2814. return result;
  2815. };
  2816. Tools.ToDegrees = function (angle) {
  2817. return angle * 180 / Math.PI;
  2818. };
  2819. Tools.ToRadians = function (angle) {
  2820. return angle * Math.PI / 180;
  2821. };
  2822. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2823. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2824. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2825. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2826. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2827. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2828. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2829. }
  2830. return {
  2831. minimum: minimum,
  2832. maximum: maximum
  2833. };
  2834. };
  2835. Tools.ExtractMinAndMax = function (positions, start, count) {
  2836. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2837. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2838. for (var index = start; index < start + count; index++) {
  2839. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2840. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2841. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2842. }
  2843. return {
  2844. minimum: minimum,
  2845. maximum: maximum
  2846. };
  2847. };
  2848. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2849. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2850. return undefined;
  2851. return Array.isArray(obj) ? obj : [obj];
  2852. };
  2853. // Misc.
  2854. Tools.GetPointerPrefix = function () {
  2855. var eventPrefix = "pointer";
  2856. // Check if hand.js is referenced or if the browser natively supports pointer events
  2857. if (!navigator.pointerEnabled) {
  2858. eventPrefix = "mouse";
  2859. }
  2860. return eventPrefix;
  2861. };
  2862. Tools.QueueNewFrame = function (func) {
  2863. if (window.requestAnimationFrame)
  2864. window.requestAnimationFrame(func);
  2865. else if (window.msRequestAnimationFrame)
  2866. window.msRequestAnimationFrame(func);
  2867. else if (window.webkitRequestAnimationFrame)
  2868. window.webkitRequestAnimationFrame(func);
  2869. else if (window.mozRequestAnimationFrame)
  2870. window.mozRequestAnimationFrame(func);
  2871. else if (window.oRequestAnimationFrame)
  2872. window.oRequestAnimationFrame(func);
  2873. else {
  2874. window.setTimeout(func, 16);
  2875. }
  2876. };
  2877. Tools.RequestFullscreen = function (element) {
  2878. if (element.requestFullscreen)
  2879. element.requestFullscreen();
  2880. else if (element.msRequestFullscreen)
  2881. element.msRequestFullscreen();
  2882. else if (element.webkitRequestFullscreen)
  2883. element.webkitRequestFullscreen();
  2884. else if (element.mozRequestFullScreen)
  2885. element.mozRequestFullScreen();
  2886. };
  2887. Tools.ExitFullscreen = function () {
  2888. if (document.exitFullscreen) {
  2889. document.exitFullscreen();
  2890. }
  2891. else if (document.mozCancelFullScreen) {
  2892. document.mozCancelFullScreen();
  2893. }
  2894. else if (document.webkitCancelFullScreen) {
  2895. document.webkitCancelFullScreen();
  2896. }
  2897. else if (document.msCancelFullScreen) {
  2898. document.msCancelFullScreen();
  2899. }
  2900. };
  2901. // External files
  2902. Tools.CleanUrl = function (url) {
  2903. url = url.replace(/#/mg, "%23");
  2904. return url;
  2905. };
  2906. Tools.LoadImage = function (url, onload, onerror, database) {
  2907. url = Tools.CleanUrl(url);
  2908. var img = new Image();
  2909. if (url.substr(0, 5) !== "data:")
  2910. img.crossOrigin = 'anonymous';
  2911. img.onload = function () {
  2912. onload(img);
  2913. };
  2914. img.onerror = function (err) {
  2915. onerror(img, err);
  2916. };
  2917. var noIndexedDB = function () {
  2918. img.src = url;
  2919. };
  2920. var loadFromIndexedDB = function () {
  2921. database.loadImageFromDB(url, img);
  2922. };
  2923. //ANY database to do!
  2924. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2925. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2926. }
  2927. else {
  2928. if (url.indexOf("file:") === -1) {
  2929. noIndexedDB();
  2930. }
  2931. else {
  2932. try {
  2933. var textureName = url.substring(5);
  2934. var blobURL;
  2935. try {
  2936. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2937. }
  2938. catch (ex) {
  2939. // Chrome doesn't support oneTimeOnly parameter
  2940. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2941. }
  2942. img.src = blobURL;
  2943. }
  2944. catch (e) {
  2945. Tools.Log("Error while trying to load texture: " + textureName);
  2946. img.src = null;
  2947. }
  2948. }
  2949. }
  2950. return img;
  2951. };
  2952. //ANY
  2953. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2954. url = Tools.CleanUrl(url);
  2955. var noIndexedDB = function () {
  2956. var request = new XMLHttpRequest();
  2957. var loadUrl = Tools.BaseUrl + url;
  2958. request.open('GET', loadUrl, true);
  2959. if (useArrayBuffer) {
  2960. request.responseType = "arraybuffer";
  2961. }
  2962. request.onprogress = progressCallBack;
  2963. request.onreadystatechange = function () {
  2964. if (request.readyState === 4) {
  2965. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2966. callback(!useArrayBuffer ? request.responseText : request.response);
  2967. }
  2968. else {
  2969. if (onError) {
  2970. onError();
  2971. }
  2972. else {
  2973. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2974. }
  2975. }
  2976. }
  2977. };
  2978. request.send(null);
  2979. };
  2980. var loadFromIndexedDB = function () {
  2981. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2982. };
  2983. if (url.indexOf("file:") !== -1) {
  2984. var fileName = url.substring(5);
  2985. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2986. }
  2987. else {
  2988. // Caching all files
  2989. if (database && database.enableSceneOffline) {
  2990. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2991. }
  2992. else {
  2993. noIndexedDB();
  2994. }
  2995. }
  2996. };
  2997. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2998. var reader = new FileReader();
  2999. reader.onload = function (e) {
  3000. //target doesn't have result from ts 1.3
  3001. callback(e.target['result']);
  3002. };
  3003. reader.onprogress = progressCallback;
  3004. reader.readAsDataURL(fileToLoad);
  3005. };
  3006. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  3007. var reader = new FileReader();
  3008. reader.onerror = function (e) {
  3009. Tools.Log("Error while reading file: " + fileToLoad.name);
  3010. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  3011. };
  3012. reader.onload = function (e) {
  3013. //target doesn't have result from ts 1.3
  3014. callback(e.target['result']);
  3015. };
  3016. reader.onprogress = progressCallBack;
  3017. if (!useArrayBuffer) {
  3018. // Asynchronous read
  3019. reader.readAsText(fileToLoad);
  3020. }
  3021. else {
  3022. reader.readAsArrayBuffer(fileToLoad);
  3023. }
  3024. };
  3025. // Misc.
  3026. Tools.Clamp = function (value, min, max) {
  3027. if (min === void 0) { min = 0; }
  3028. if (max === void 0) { max = 1; }
  3029. return Math.min(max, Math.max(min, value));
  3030. };
  3031. // Returns -1 when value is a negative number and
  3032. // +1 when value is a positive number.
  3033. Tools.Sign = function (value) {
  3034. value = +value; // convert to a number
  3035. if (value === 0 || isNaN(value))
  3036. return value;
  3037. return value > 0 ? 1 : -1;
  3038. };
  3039. Tools.Format = function (value, decimals) {
  3040. if (decimals === void 0) { decimals = 2; }
  3041. return value.toFixed(decimals);
  3042. };
  3043. Tools.CheckExtends = function (v, min, max) {
  3044. if (v.x < min.x)
  3045. min.x = v.x;
  3046. if (v.y < min.y)
  3047. min.y = v.y;
  3048. if (v.z < min.z)
  3049. min.z = v.z;
  3050. if (v.x > max.x)
  3051. max.x = v.x;
  3052. if (v.y > max.y)
  3053. max.y = v.y;
  3054. if (v.z > max.z)
  3055. max.z = v.z;
  3056. };
  3057. Tools.WithinEpsilon = function (a, b, epsilon) {
  3058. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  3059. var num = a - b;
  3060. return -epsilon <= num && num <= epsilon;
  3061. };
  3062. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  3063. for (var prop in source) {
  3064. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  3065. continue;
  3066. }
  3067. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  3068. continue;
  3069. }
  3070. var sourceValue = source[prop];
  3071. var typeOfSourceValue = typeof sourceValue;
  3072. if (typeOfSourceValue === "function") {
  3073. continue;
  3074. }
  3075. if (typeOfSourceValue === "object") {
  3076. if (sourceValue instanceof Array) {
  3077. destination[prop] = [];
  3078. if (sourceValue.length > 0) {
  3079. if (typeof sourceValue[0] == "object") {
  3080. for (var index = 0; index < sourceValue.length; index++) {
  3081. var clonedValue = cloneValue(sourceValue[index], destination);
  3082. if (destination[prop].indexOf(clonedValue) === -1) {
  3083. destination[prop].push(clonedValue);
  3084. }
  3085. }
  3086. }
  3087. else {
  3088. destination[prop] = sourceValue.slice(0);
  3089. }
  3090. }
  3091. }
  3092. else {
  3093. destination[prop] = cloneValue(sourceValue, destination);
  3094. }
  3095. }
  3096. else {
  3097. destination[prop] = sourceValue;
  3098. }
  3099. }
  3100. };
  3101. Tools.IsEmpty = function (obj) {
  3102. for (var i in obj) {
  3103. return false;
  3104. }
  3105. return true;
  3106. };
  3107. Tools.RegisterTopRootEvents = function (events) {
  3108. for (var index = 0; index < events.length; index++) {
  3109. var event = events[index];
  3110. window.addEventListener(event.name, event.handler, false);
  3111. try {
  3112. if (window.parent) {
  3113. window.parent.addEventListener(event.name, event.handler, false);
  3114. }
  3115. }
  3116. catch (e) {
  3117. }
  3118. }
  3119. };
  3120. Tools.UnregisterTopRootEvents = function (events) {
  3121. for (var index = 0; index < events.length; index++) {
  3122. var event = events[index];
  3123. window.removeEventListener(event.name, event.handler);
  3124. try {
  3125. if (window.parent) {
  3126. window.parent.removeEventListener(event.name, event.handler);
  3127. }
  3128. }
  3129. catch (e) {
  3130. }
  3131. }
  3132. };
  3133. Tools.DumpFramebuffer = function (width, height, engine) {
  3134. // Read the contents of the framebuffer
  3135. var numberOfChannelsByLine = width * 4;
  3136. var halfHeight = height / 2;
  3137. //Reading datas from WebGL
  3138. var data = engine.readPixels(0, 0, width, height);
  3139. for (var i = 0; i < halfHeight; i++) {
  3140. for (var j = 0; j < numberOfChannelsByLine; j++) {
  3141. var currentCell = j + i * numberOfChannelsByLine;
  3142. var targetLine = height - i - 1;
  3143. var targetCell = j + targetLine * numberOfChannelsByLine;
  3144. var temp = data[currentCell];
  3145. data[currentCell] = data[targetCell];
  3146. data[targetCell] = temp;
  3147. }
  3148. }
  3149. // Create a 2D canvas to store the result
  3150. if (!screenshotCanvas) {
  3151. screenshotCanvas = document.createElement('canvas');
  3152. }
  3153. screenshotCanvas.width = width;
  3154. screenshotCanvas.height = height;
  3155. var context = screenshotCanvas.getContext('2d');
  3156. // Copy the pixels to a 2D canvas
  3157. var imageData = context.createImageData(width, height);
  3158. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  3159. var castData = imageData.data;
  3160. castData.set(data);
  3161. context.putImageData(imageData, 0, 0);
  3162. var base64Image = screenshotCanvas.toDataURL();
  3163. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  3164. if (("download" in document.createElement("a"))) {
  3165. var a = window.document.createElement("a");
  3166. a.href = base64Image;
  3167. var date = new Date();
  3168. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  3169. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  3170. window.document.body.appendChild(a);
  3171. a.addEventListener("click", function () {
  3172. a.parentElement.removeChild(a);
  3173. });
  3174. a.click();
  3175. }
  3176. else {
  3177. var newWindow = window.open("");
  3178. var img = newWindow.document.createElement("img");
  3179. img.src = base64Image;
  3180. newWindow.document.body.appendChild(img);
  3181. }
  3182. };
  3183. Tools.CreateScreenshot = function (engine, camera, size) {
  3184. var width;
  3185. var height;
  3186. var scene = camera.getScene();
  3187. var previousCamera = null;
  3188. if (scene.activeCamera !== camera) {
  3189. previousCamera = scene.activeCamera;
  3190. scene.activeCamera = camera;
  3191. }
  3192. //If a precision value is specified
  3193. if (size.precision) {
  3194. width = Math.round(engine.getRenderWidth() * size.precision);
  3195. height = Math.round(width / engine.getAspectRatio(camera));
  3196. size = { width: width, height: height };
  3197. }
  3198. else if (size.width && size.height) {
  3199. width = size.width;
  3200. height = size.height;
  3201. }
  3202. else if (size.width && !size.height) {
  3203. width = size.width;
  3204. height = Math.round(width / engine.getAspectRatio(camera));
  3205. size = { width: width, height: height };
  3206. }
  3207. else if (size.height && !size.width) {
  3208. height = size.height;
  3209. width = Math.round(height * engine.getAspectRatio(camera));
  3210. size = { width: width, height: height };
  3211. }
  3212. else if (!isNaN(size)) {
  3213. height = size;
  3214. width = size;
  3215. }
  3216. else {
  3217. Tools.Error("Invalid 'size' parameter !");
  3218. return;
  3219. }
  3220. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  3221. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  3222. texture.renderList = scene.meshes;
  3223. texture.onAfterRender = function () {
  3224. Tools.DumpFramebuffer(width, height, engine);
  3225. };
  3226. scene.incrementRenderId();
  3227. texture.render(true);
  3228. texture.dispose();
  3229. if (previousCamera) {
  3230. scene.activeCamera = previousCamera;
  3231. }
  3232. };
  3233. // XHR response validator for local file scenario
  3234. Tools.ValidateXHRData = function (xhr, dataType) {
  3235. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  3236. if (dataType === void 0) { dataType = 7; }
  3237. try {
  3238. if (dataType & 1) {
  3239. if (xhr.responseText && xhr.responseText.length > 0) {
  3240. return true;
  3241. }
  3242. else if (dataType === 1) {
  3243. return false;
  3244. }
  3245. }
  3246. if (dataType & 2) {
  3247. // Check header width and height since there is no "TGA" magic number
  3248. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  3249. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  3250. return true;
  3251. }
  3252. else if (dataType === 2) {
  3253. return false;
  3254. }
  3255. }
  3256. if (dataType & 4) {
  3257. // Check for the "DDS" magic number
  3258. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  3259. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  3260. return true;
  3261. }
  3262. else {
  3263. return false;
  3264. }
  3265. }
  3266. }
  3267. catch (e) {
  3268. }
  3269. return false;
  3270. };
  3271. Object.defineProperty(Tools, "NoneLogLevel", {
  3272. get: function () {
  3273. return Tools._NoneLogLevel;
  3274. },
  3275. enumerable: true,
  3276. configurable: true
  3277. });
  3278. Object.defineProperty(Tools, "MessageLogLevel", {
  3279. get: function () {
  3280. return Tools._MessageLogLevel;
  3281. },
  3282. enumerable: true,
  3283. configurable: true
  3284. });
  3285. Object.defineProperty(Tools, "WarningLogLevel", {
  3286. get: function () {
  3287. return Tools._WarningLogLevel;
  3288. },
  3289. enumerable: true,
  3290. configurable: true
  3291. });
  3292. Object.defineProperty(Tools, "ErrorLogLevel", {
  3293. get: function () {
  3294. return Tools._ErrorLogLevel;
  3295. },
  3296. enumerable: true,
  3297. configurable: true
  3298. });
  3299. Object.defineProperty(Tools, "AllLogLevel", {
  3300. get: function () {
  3301. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3302. },
  3303. enumerable: true,
  3304. configurable: true
  3305. });
  3306. Tools._AddLogEntry = function (entry) {
  3307. Tools._LogCache = entry + Tools._LogCache;
  3308. if (Tools.OnNewCacheEntry) {
  3309. Tools.OnNewCacheEntry(entry);
  3310. }
  3311. };
  3312. Tools._FormatMessage = function (message) {
  3313. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3314. var date = new Date();
  3315. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3316. };
  3317. Tools._LogDisabled = function (message) {
  3318. // nothing to do
  3319. };
  3320. Tools._LogEnabled = function (message) {
  3321. var formattedMessage = Tools._FormatMessage(message);
  3322. console.log("BJS - " + formattedMessage);
  3323. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3324. Tools._AddLogEntry(entry);
  3325. };
  3326. Tools._WarnDisabled = function (message) {
  3327. // nothing to do
  3328. };
  3329. Tools._WarnEnabled = function (message) {
  3330. var formattedMessage = Tools._FormatMessage(message);
  3331. console.warn("BJS - " + formattedMessage);
  3332. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3333. Tools._AddLogEntry(entry);
  3334. };
  3335. Tools._ErrorDisabled = function (message) {
  3336. // nothing to do
  3337. };
  3338. Tools._ErrorEnabled = function (message) {
  3339. var formattedMessage = Tools._FormatMessage(message);
  3340. console.error("BJS - " + formattedMessage);
  3341. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3342. Tools._AddLogEntry(entry);
  3343. };
  3344. Object.defineProperty(Tools, "LogCache", {
  3345. get: function () {
  3346. return Tools._LogCache;
  3347. },
  3348. enumerable: true,
  3349. configurable: true
  3350. });
  3351. Object.defineProperty(Tools, "LogLevels", {
  3352. set: function (level) {
  3353. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3354. Tools.Log = Tools._LogEnabled;
  3355. }
  3356. else {
  3357. Tools.Log = Tools._LogDisabled;
  3358. }
  3359. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3360. Tools.Warn = Tools._WarnEnabled;
  3361. }
  3362. else {
  3363. Tools.Warn = Tools._WarnDisabled;
  3364. }
  3365. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3366. Tools.Error = Tools._ErrorEnabled;
  3367. }
  3368. else {
  3369. Tools.Error = Tools._ErrorDisabled;
  3370. }
  3371. },
  3372. enumerable: true,
  3373. configurable: true
  3374. });
  3375. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3376. get: function () {
  3377. return Tools._PerformanceNoneLogLevel;
  3378. },
  3379. enumerable: true,
  3380. configurable: true
  3381. });
  3382. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3383. get: function () {
  3384. return Tools._PerformanceUserMarkLogLevel;
  3385. },
  3386. enumerable: true,
  3387. configurable: true
  3388. });
  3389. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3390. get: function () {
  3391. return Tools._PerformanceConsoleLogLevel;
  3392. },
  3393. enumerable: true,
  3394. configurable: true
  3395. });
  3396. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3397. set: function (level) {
  3398. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3399. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3400. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3401. return;
  3402. }
  3403. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3404. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3405. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3406. return;
  3407. }
  3408. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3409. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3410. },
  3411. enumerable: true,
  3412. configurable: true
  3413. });
  3414. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3415. };
  3416. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3417. };
  3418. Tools._StartUserMark = function (counterName, condition) {
  3419. if (condition === void 0) { condition = true; }
  3420. if (!condition || !Tools._performance.mark) {
  3421. return;
  3422. }
  3423. Tools._performance.mark(counterName + "-Begin");
  3424. };
  3425. Tools._EndUserMark = function (counterName, condition) {
  3426. if (condition === void 0) { condition = true; }
  3427. if (!condition || !Tools._performance.mark) {
  3428. return;
  3429. }
  3430. Tools._performance.mark(counterName + "-End");
  3431. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3432. };
  3433. Tools._StartPerformanceConsole = function (counterName, condition) {
  3434. if (condition === void 0) { condition = true; }
  3435. if (!condition) {
  3436. return;
  3437. }
  3438. Tools._StartUserMark(counterName, condition);
  3439. if (console.time) {
  3440. console.time(counterName);
  3441. }
  3442. };
  3443. Tools._EndPerformanceConsole = function (counterName, condition) {
  3444. if (condition === void 0) { condition = true; }
  3445. if (!condition) {
  3446. return;
  3447. }
  3448. Tools._EndUserMark(counterName, condition);
  3449. if (console.time) {
  3450. console.timeEnd(counterName);
  3451. }
  3452. };
  3453. Object.defineProperty(Tools, "Now", {
  3454. get: function () {
  3455. if (window.performance && window.performance.now) {
  3456. return window.performance.now();
  3457. }
  3458. return new Date().getTime();
  3459. },
  3460. enumerable: true,
  3461. configurable: true
  3462. });
  3463. // Deprecated
  3464. Tools.GetFps = function () {
  3465. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3466. return 0;
  3467. };
  3468. Tools.BaseUrl = "";
  3469. Tools.GetExponantOfTwo = function (value, max) {
  3470. var count = 1;
  3471. do {
  3472. count *= 2;
  3473. } while (count < value);
  3474. if (count > max)
  3475. count = max;
  3476. return count;
  3477. };
  3478. // Logs
  3479. Tools._NoneLogLevel = 0;
  3480. Tools._MessageLogLevel = 1;
  3481. Tools._WarningLogLevel = 2;
  3482. Tools._ErrorLogLevel = 4;
  3483. Tools._LogCache = "";
  3484. Tools.Log = Tools._LogEnabled;
  3485. Tools.Warn = Tools._WarnEnabled;
  3486. Tools.Error = Tools._ErrorEnabled;
  3487. // Performances
  3488. Tools._PerformanceNoneLogLevel = 0;
  3489. Tools._PerformanceUserMarkLogLevel = 1;
  3490. Tools._PerformanceConsoleLogLevel = 2;
  3491. Tools._performance = window.performance;
  3492. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3493. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3494. return Tools;
  3495. })();
  3496. BABYLON.Tools = Tools;
  3497. /**
  3498. * An implementation of a loop for asynchronous functions.
  3499. */
  3500. var AsyncLoop = (function () {
  3501. /**
  3502. * Constroctor.
  3503. * @param iterations the number of iterations.
  3504. * @param _fn the function to run each iteration
  3505. * @param _successCallback the callback that will be called upon succesful execution
  3506. * @param offset starting offset.
  3507. */
  3508. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3509. if (offset === void 0) { offset = 0; }
  3510. this.iterations = iterations;
  3511. this._fn = _fn;
  3512. this._successCallback = _successCallback;
  3513. this.index = offset - 1;
  3514. this._done = false;
  3515. }
  3516. /**
  3517. * Execute the next iteration. Must be called after the last iteration was finished.
  3518. */
  3519. AsyncLoop.prototype.executeNext = function () {
  3520. if (!this._done) {
  3521. if (this.index + 1 < this.iterations) {
  3522. ++this.index;
  3523. this._fn(this);
  3524. }
  3525. else {
  3526. this.breakLoop();
  3527. }
  3528. }
  3529. };
  3530. /**
  3531. * Break the loop and run the success callback.
  3532. */
  3533. AsyncLoop.prototype.breakLoop = function () {
  3534. this._done = true;
  3535. this._successCallback();
  3536. };
  3537. /**
  3538. * Helper function
  3539. */
  3540. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3541. if (offset === void 0) { offset = 0; }
  3542. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3543. loop.executeNext();
  3544. return loop;
  3545. };
  3546. /**
  3547. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3548. * @param iterations total number of iterations
  3549. * @param syncedIterations number of synchronous iterations in each async iteration.
  3550. * @param fn the function to call each iteration.
  3551. * @param callback a success call back that will be called when iterating stops.
  3552. * @param breakFunction a break condition (optional)
  3553. * @param timeout timeout settings for the setTimeout function. default - 0.
  3554. * @constructor
  3555. */
  3556. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3557. if (timeout === void 0) { timeout = 0; }
  3558. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3559. if (breakFunction && breakFunction())
  3560. loop.breakLoop();
  3561. else {
  3562. setTimeout(function () {
  3563. for (var i = 0; i < syncedIterations; ++i) {
  3564. var iteration = (loop.index * syncedIterations) + i;
  3565. if (iteration >= iterations)
  3566. break;
  3567. fn(iteration);
  3568. if (breakFunction && breakFunction()) {
  3569. loop.breakLoop();
  3570. break;
  3571. }
  3572. }
  3573. loop.executeNext();
  3574. }, timeout);
  3575. }
  3576. }, callback);
  3577. };
  3578. return AsyncLoop;
  3579. })();
  3580. BABYLON.AsyncLoop = AsyncLoop;
  3581. })(BABYLON || (BABYLON = {}));
  3582. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3583. (function (BABYLON) {
  3584. var _DepthCullingState = (function () {
  3585. function _DepthCullingState() {
  3586. this._isDepthTestDirty = false;
  3587. this._isDepthMaskDirty = false;
  3588. this._isDepthFuncDirty = false;
  3589. this._isCullFaceDirty = false;
  3590. this._isCullDirty = false;
  3591. }
  3592. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3593. get: function () {
  3594. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3595. },
  3596. enumerable: true,
  3597. configurable: true
  3598. });
  3599. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3600. get: function () {
  3601. return this._cullFace;
  3602. },
  3603. set: function (value) {
  3604. if (this._cullFace === value) {
  3605. return;
  3606. }
  3607. this._cullFace = value;
  3608. this._isCullFaceDirty = true;
  3609. },
  3610. enumerable: true,
  3611. configurable: true
  3612. });
  3613. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3614. get: function () {
  3615. return this._cull;
  3616. },
  3617. set: function (value) {
  3618. if (this._cull === value) {
  3619. return;
  3620. }
  3621. this._cull = value;
  3622. this._isCullDirty = true;
  3623. },
  3624. enumerable: true,
  3625. configurable: true
  3626. });
  3627. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3628. get: function () {
  3629. return this._depthFunc;
  3630. },
  3631. set: function (value) {
  3632. if (this._depthFunc === value) {
  3633. return;
  3634. }
  3635. this._depthFunc = value;
  3636. this._isDepthFuncDirty = true;
  3637. },
  3638. enumerable: true,
  3639. configurable: true
  3640. });
  3641. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3642. get: function () {
  3643. return this._depthMask;
  3644. },
  3645. set: function (value) {
  3646. if (this._depthMask === value) {
  3647. return;
  3648. }
  3649. this._depthMask = value;
  3650. this._isDepthMaskDirty = true;
  3651. },
  3652. enumerable: true,
  3653. configurable: true
  3654. });
  3655. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3656. get: function () {
  3657. return this._depthTest;
  3658. },
  3659. set: function (value) {
  3660. if (this._depthTest === value) {
  3661. return;
  3662. }
  3663. this._depthTest = value;
  3664. this._isDepthTestDirty = true;
  3665. },
  3666. enumerable: true,
  3667. configurable: true
  3668. });
  3669. _DepthCullingState.prototype.reset = function () {
  3670. this._depthMask = true;
  3671. this._depthTest = true;
  3672. this._depthFunc = null;
  3673. this._cull = null;
  3674. this._cullFace = null;
  3675. this._isDepthTestDirty = true;
  3676. this._isDepthMaskDirty = true;
  3677. this._isDepthFuncDirty = false;
  3678. this._isCullFaceDirty = false;
  3679. this._isCullDirty = false;
  3680. };
  3681. _DepthCullingState.prototype.apply = function (gl) {
  3682. if (!this.isDirty) {
  3683. return;
  3684. }
  3685. // Cull
  3686. if (this._isCullDirty) {
  3687. if (this.cull) {
  3688. gl.enable(gl.CULL_FACE);
  3689. }
  3690. else {
  3691. gl.disable(gl.CULL_FACE);
  3692. }
  3693. this._isCullDirty = false;
  3694. }
  3695. // Cull face
  3696. if (this._isCullFaceDirty) {
  3697. gl.cullFace(this.cullFace);
  3698. this._isCullFaceDirty = false;
  3699. }
  3700. // Depth mask
  3701. if (this._isDepthMaskDirty) {
  3702. gl.depthMask(this.depthMask);
  3703. this._isDepthMaskDirty = false;
  3704. }
  3705. // Depth test
  3706. if (this._isDepthTestDirty) {
  3707. if (this.depthTest) {
  3708. gl.enable(gl.DEPTH_TEST);
  3709. }
  3710. else {
  3711. gl.disable(gl.DEPTH_TEST);
  3712. }
  3713. this._isDepthTestDirty = false;
  3714. }
  3715. // Depth func
  3716. if (this._isDepthFuncDirty) {
  3717. gl.depthFunc(this.depthFunc);
  3718. this._isDepthFuncDirty = false;
  3719. }
  3720. };
  3721. return _DepthCullingState;
  3722. })();
  3723. BABYLON._DepthCullingState = _DepthCullingState;
  3724. var _AlphaState = (function () {
  3725. function _AlphaState() {
  3726. this._isAlphaBlendDirty = false;
  3727. this._isBlendFunctionParametersDirty = false;
  3728. this._alphaBlend = false;
  3729. this._blendFunctionParameters = new Array(4);
  3730. }
  3731. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3732. get: function () {
  3733. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3734. },
  3735. enumerable: true,
  3736. configurable: true
  3737. });
  3738. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3739. get: function () {
  3740. return this._alphaBlend;
  3741. },
  3742. set: function (value) {
  3743. if (this._alphaBlend === value) {
  3744. return;
  3745. }
  3746. this._alphaBlend = value;
  3747. this._isAlphaBlendDirty = true;
  3748. },
  3749. enumerable: true,
  3750. configurable: true
  3751. });
  3752. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3753. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3754. return;
  3755. }
  3756. this._blendFunctionParameters[0] = value0;
  3757. this._blendFunctionParameters[1] = value1;
  3758. this._blendFunctionParameters[2] = value2;
  3759. this._blendFunctionParameters[3] = value3;
  3760. this._isBlendFunctionParametersDirty = true;
  3761. };
  3762. _AlphaState.prototype.reset = function () {
  3763. this._alphaBlend = false;
  3764. this._blendFunctionParameters[0] = null;
  3765. this._blendFunctionParameters[1] = null;
  3766. this._blendFunctionParameters[2] = null;
  3767. this._blendFunctionParameters[3] = null;
  3768. this._isAlphaBlendDirty = true;
  3769. this._isBlendFunctionParametersDirty = false;
  3770. };
  3771. _AlphaState.prototype.apply = function (gl) {
  3772. if (!this.isDirty) {
  3773. return;
  3774. }
  3775. // Alpha blend
  3776. if (this._isAlphaBlendDirty) {
  3777. if (this._alphaBlend) {
  3778. gl.enable(gl.BLEND);
  3779. }
  3780. else {
  3781. gl.disable(gl.BLEND);
  3782. }
  3783. this._isAlphaBlendDirty = false;
  3784. }
  3785. // Alpha function
  3786. if (this._isBlendFunctionParametersDirty) {
  3787. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3788. this._isBlendFunctionParametersDirty = false;
  3789. }
  3790. };
  3791. return _AlphaState;
  3792. })();
  3793. BABYLON._AlphaState = _AlphaState;
  3794. var compileShader = function (gl, source, type, defines) {
  3795. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3796. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3797. gl.compileShader(shader);
  3798. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3799. throw new Error(gl.getShaderInfoLog(shader));
  3800. }
  3801. return shader;
  3802. };
  3803. var getWebGLTextureType = function (gl, type) {
  3804. var textureType = gl.UNSIGNED_BYTE;
  3805. if (type === Engine.TEXTURETYPE_FLOAT)
  3806. textureType = gl.FLOAT;
  3807. return textureType;
  3808. };
  3809. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3810. var magFilter = gl.NEAREST;
  3811. var minFilter = gl.NEAREST;
  3812. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3813. magFilter = gl.LINEAR;
  3814. if (generateMipMaps) {
  3815. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3816. }
  3817. else {
  3818. minFilter = gl.LINEAR;
  3819. }
  3820. }
  3821. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3822. magFilter = gl.LINEAR;
  3823. if (generateMipMaps) {
  3824. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3825. }
  3826. else {
  3827. minFilter = gl.LINEAR;
  3828. }
  3829. }
  3830. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3831. magFilter = gl.NEAREST;
  3832. if (generateMipMaps) {
  3833. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3834. }
  3835. else {
  3836. minFilter = gl.NEAREST;
  3837. }
  3838. }
  3839. return {
  3840. min: minFilter,
  3841. mag: magFilter
  3842. };
  3843. };
  3844. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3845. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3846. var engine = scene.getEngine();
  3847. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3848. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3849. gl.bindTexture(gl.TEXTURE_2D, texture);
  3850. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3851. processFunction(potWidth, potHeight);
  3852. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3853. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3854. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3855. if (!noMipmap && !isCompressed) {
  3856. gl.generateMipmap(gl.TEXTURE_2D);
  3857. }
  3858. gl.bindTexture(gl.TEXTURE_2D, null);
  3859. engine._activeTexturesCache = [];
  3860. texture._baseWidth = width;
  3861. texture._baseHeight = height;
  3862. texture._width = potWidth;
  3863. texture._height = potHeight;
  3864. texture.isReady = true;
  3865. texture.samplingMode = samplingMode;
  3866. scene._removePendingData(texture);
  3867. };
  3868. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3869. var onload = function () {
  3870. loadedImages[index] = img;
  3871. loadedImages._internalCount++;
  3872. scene._removePendingData(img);
  3873. if (loadedImages._internalCount === 6) {
  3874. onfinish(loadedImages);
  3875. }
  3876. };
  3877. var onerror = function () {
  3878. scene._removePendingData(img);
  3879. };
  3880. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3881. scene._addPendingData(img);
  3882. };
  3883. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3884. var loadedImages = [];
  3885. loadedImages._internalCount = 0;
  3886. for (var index = 0; index < 6; index++) {
  3887. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3888. }
  3889. };
  3890. var EngineCapabilities = (function () {
  3891. function EngineCapabilities() {
  3892. }
  3893. return EngineCapabilities;
  3894. })();
  3895. BABYLON.EngineCapabilities = EngineCapabilities;
  3896. /**
  3897. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3898. */
  3899. var Engine = (function () {
  3900. /**
  3901. * @constructor
  3902. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3903. * @param {boolean} [antialias] - enable antialias
  3904. * @param options - further options to be sent to the getContext function
  3905. */
  3906. function Engine(canvas, antialias, options) {
  3907. var _this = this;
  3908. // Public members
  3909. this.isFullscreen = false;
  3910. this.isPointerLock = false;
  3911. this.cullBackFaces = true;
  3912. this.renderEvenInBackground = true;
  3913. this.scenes = new Array();
  3914. this._windowIsBackground = false;
  3915. this._loadingDivBackgroundColor = "black";
  3916. this._drawCalls = 0;
  3917. this._renderingQueueLaunched = false;
  3918. this._activeRenderLoops = [];
  3919. // FPS
  3920. this.fpsRange = 60;
  3921. this.previousFramesDuration = [];
  3922. this.fps = 60;
  3923. this.deltaTime = 0;
  3924. // States
  3925. this._depthCullingState = new _DepthCullingState();
  3926. this._alphaState = new _AlphaState();
  3927. this._alphaMode = Engine.ALPHA_DISABLE;
  3928. // Cache
  3929. this._loadedTexturesCache = new Array();
  3930. this._activeTexturesCache = new Array();
  3931. this._compiledEffects = {};
  3932. this._uintIndicesCurrentlySet = false;
  3933. this._renderingCanvas = canvas;
  3934. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3935. options = options || {};
  3936. options.antialias = antialias;
  3937. try {
  3938. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3939. }
  3940. catch (e) {
  3941. throw new Error("WebGL not supported");
  3942. }
  3943. if (!this._gl) {
  3944. throw new Error("WebGL not supported");
  3945. }
  3946. this._onBlur = function () {
  3947. _this._windowIsBackground = true;
  3948. };
  3949. this._onFocus = function () {
  3950. _this._windowIsBackground = false;
  3951. };
  3952. window.addEventListener("blur", this._onBlur);
  3953. window.addEventListener("focus", this._onFocus);
  3954. // Textures
  3955. this._workingCanvas = document.createElement("canvas");
  3956. this._workingContext = this._workingCanvas.getContext("2d");
  3957. // Viewport
  3958. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3959. this.resize();
  3960. // Caps
  3961. this._caps = new EngineCapabilities();
  3962. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3963. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3964. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3965. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3966. // Infos
  3967. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3968. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3969. if (rendererInfo != null) {
  3970. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3971. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3972. }
  3973. if (!this._glVendor) {
  3974. this._glVendor = "Unknown vendor";
  3975. }
  3976. if (!this._glRenderer) {
  3977. this._glRenderer = "Unknown renderer";
  3978. }
  3979. // Extensions
  3980. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3981. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3982. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3983. 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');
  3984. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3985. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3986. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3987. // Depth buffer
  3988. this.setDepthBuffer(true);
  3989. this.setDepthFunctionToLessOrEqual();
  3990. this.setDepthWrite(true);
  3991. // Fullscreen
  3992. this._onFullscreenChange = function () {
  3993. if (document.fullscreen !== undefined) {
  3994. _this.isFullscreen = document.fullscreen;
  3995. }
  3996. else if (document.mozFullScreen !== undefined) {
  3997. _this.isFullscreen = document.mozFullScreen;
  3998. }
  3999. else if (document.webkitIsFullScreen !== undefined) {
  4000. _this.isFullscreen = document.webkitIsFullScreen;
  4001. }
  4002. else if (document.msIsFullScreen !== undefined) {
  4003. _this.isFullscreen = document.msIsFullScreen;
  4004. }
  4005. // Pointer lock
  4006. if (_this.isFullscreen && _this._pointerLockRequested) {
  4007. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  4008. if (canvas.requestPointerLock) {
  4009. canvas.requestPointerLock();
  4010. }
  4011. }
  4012. };
  4013. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  4014. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  4015. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  4016. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  4017. // Pointer lock
  4018. this._onPointerLockChange = function () {
  4019. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  4020. };
  4021. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  4022. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  4023. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  4024. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  4025. if (!Engine.audioEngine) {
  4026. Engine.audioEngine = new BABYLON.AudioEngine();
  4027. }
  4028. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  4029. }
  4030. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  4031. get: function () {
  4032. return Engine._ALPHA_DISABLE;
  4033. },
  4034. enumerable: true,
  4035. configurable: true
  4036. });
  4037. Object.defineProperty(Engine, "ALPHA_ADD", {
  4038. get: function () {
  4039. return Engine._ALPHA_ADD;
  4040. },
  4041. enumerable: true,
  4042. configurable: true
  4043. });
  4044. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  4045. get: function () {
  4046. return Engine._ALPHA_COMBINE;
  4047. },
  4048. enumerable: true,
  4049. configurable: true
  4050. });
  4051. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  4052. get: function () {
  4053. return Engine._DELAYLOADSTATE_NONE;
  4054. },
  4055. enumerable: true,
  4056. configurable: true
  4057. });
  4058. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  4059. get: function () {
  4060. return Engine._DELAYLOADSTATE_LOADED;
  4061. },
  4062. enumerable: true,
  4063. configurable: true
  4064. });
  4065. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  4066. get: function () {
  4067. return Engine._DELAYLOADSTATE_LOADING;
  4068. },
  4069. enumerable: true,
  4070. configurable: true
  4071. });
  4072. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  4073. get: function () {
  4074. return Engine._DELAYLOADSTATE_NOTLOADED;
  4075. },
  4076. enumerable: true,
  4077. configurable: true
  4078. });
  4079. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  4080. get: function () {
  4081. return Engine._TEXTUREFORMAT_ALPHA;
  4082. },
  4083. enumerable: true,
  4084. configurable: true
  4085. });
  4086. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  4087. get: function () {
  4088. return Engine._TEXTUREFORMAT_LUMINANCE;
  4089. },
  4090. enumerable: true,
  4091. configurable: true
  4092. });
  4093. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  4094. get: function () {
  4095. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  4096. },
  4097. enumerable: true,
  4098. configurable: true
  4099. });
  4100. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  4101. get: function () {
  4102. return Engine._TEXTUREFORMAT_RGB;
  4103. },
  4104. enumerable: true,
  4105. configurable: true
  4106. });
  4107. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  4108. get: function () {
  4109. return Engine._TEXTUREFORMAT_RGBA;
  4110. },
  4111. enumerable: true,
  4112. configurable: true
  4113. });
  4114. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  4115. get: function () {
  4116. return Engine._TEXTURETYPE_UNSIGNED_INT;
  4117. },
  4118. enumerable: true,
  4119. configurable: true
  4120. });
  4121. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  4122. get: function () {
  4123. return Engine._TEXTURETYPE_FLOAT;
  4124. },
  4125. enumerable: true,
  4126. configurable: true
  4127. });
  4128. Object.defineProperty(Engine, "Version", {
  4129. get: function () {
  4130. return "2.1.0 alpha";
  4131. },
  4132. enumerable: true,
  4133. configurable: true
  4134. });
  4135. Engine.prototype.getGlInfo = function () {
  4136. return {
  4137. vendor: this._glVendor,
  4138. renderer: this._glRenderer,
  4139. version: this._glVersion
  4140. };
  4141. };
  4142. Engine.prototype.getAspectRatio = function (camera) {
  4143. var viewport = camera.viewport;
  4144. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  4145. };
  4146. Engine.prototype.getRenderWidth = function () {
  4147. if (this._currentRenderTarget) {
  4148. return this._currentRenderTarget._width;
  4149. }
  4150. return this._renderingCanvas.width;
  4151. };
  4152. Engine.prototype.getRenderHeight = function () {
  4153. if (this._currentRenderTarget) {
  4154. return this._currentRenderTarget._height;
  4155. }
  4156. return this._renderingCanvas.height;
  4157. };
  4158. Engine.prototype.getRenderingCanvas = function () {
  4159. return this._renderingCanvas;
  4160. };
  4161. Engine.prototype.getRenderingCanvasClientRect = function () {
  4162. return this._renderingCanvas.getBoundingClientRect();
  4163. };
  4164. Engine.prototype.setHardwareScalingLevel = function (level) {
  4165. this._hardwareScalingLevel = level;
  4166. this.resize();
  4167. };
  4168. Engine.prototype.getHardwareScalingLevel = function () {
  4169. return this._hardwareScalingLevel;
  4170. };
  4171. Engine.prototype.getLoadedTexturesCache = function () {
  4172. return this._loadedTexturesCache;
  4173. };
  4174. Engine.prototype.getCaps = function () {
  4175. return this._caps;
  4176. };
  4177. Object.defineProperty(Engine.prototype, "drawCalls", {
  4178. get: function () {
  4179. return this._drawCalls;
  4180. },
  4181. enumerable: true,
  4182. configurable: true
  4183. });
  4184. // Methods
  4185. Engine.prototype.resetDrawCalls = function () {
  4186. this._drawCalls = 0;
  4187. };
  4188. Engine.prototype.setDepthFunctionToGreater = function () {
  4189. this._depthCullingState.depthFunc = this._gl.GREATER;
  4190. };
  4191. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  4192. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  4193. };
  4194. Engine.prototype.setDepthFunctionToLess = function () {
  4195. this._depthCullingState.depthFunc = this._gl.LESS;
  4196. };
  4197. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  4198. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  4199. };
  4200. /**
  4201. * stop executing a render loop function and remove it from the execution array
  4202. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  4203. */
  4204. Engine.prototype.stopRenderLoop = function (renderFunction) {
  4205. if (!renderFunction) {
  4206. this._activeRenderLoops = [];
  4207. return;
  4208. }
  4209. var index = this._activeRenderLoops.indexOf(renderFunction);
  4210. if (index >= 0) {
  4211. this._activeRenderLoops.splice(index, 1);
  4212. }
  4213. };
  4214. Engine.prototype._renderLoop = function () {
  4215. var _this = this;
  4216. var shouldRender = true;
  4217. if (!this.renderEvenInBackground && this._windowIsBackground) {
  4218. shouldRender = false;
  4219. }
  4220. if (shouldRender) {
  4221. // Start new frame
  4222. this.beginFrame();
  4223. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  4224. var renderFunction = this._activeRenderLoops[index];
  4225. renderFunction();
  4226. }
  4227. // Present
  4228. this.endFrame();
  4229. }
  4230. if (this._activeRenderLoops.length > 0) {
  4231. // Register new frame
  4232. BABYLON.Tools.QueueNewFrame(function () {
  4233. _this._renderLoop();
  4234. });
  4235. }
  4236. else {
  4237. this._renderingQueueLaunched = false;
  4238. }
  4239. };
  4240. /**
  4241. * Register and execute a render loop. The engine can have more than one render function.
  4242. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  4243. * @example
  4244. * engine.runRenderLoop(function () {
  4245. * scene.render()
  4246. * })
  4247. */
  4248. Engine.prototype.runRenderLoop = function (renderFunction) {
  4249. var _this = this;
  4250. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  4251. return;
  4252. }
  4253. this._activeRenderLoops.push(renderFunction);
  4254. if (!this._renderingQueueLaunched) {
  4255. this._renderingQueueLaunched = true;
  4256. BABYLON.Tools.QueueNewFrame(function () {
  4257. _this._renderLoop();
  4258. });
  4259. }
  4260. };
  4261. /**
  4262. * Toggle full screen mode.
  4263. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  4264. */
  4265. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  4266. if (this.isFullscreen) {
  4267. BABYLON.Tools.ExitFullscreen();
  4268. }
  4269. else {
  4270. this._pointerLockRequested = requestPointerLock;
  4271. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  4272. }
  4273. };
  4274. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  4275. this.applyStates();
  4276. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  4277. if (this._depthCullingState.depthMask) {
  4278. this._gl.clearDepth(1.0);
  4279. }
  4280. var mode = 0;
  4281. if (backBuffer)
  4282. mode |= this._gl.COLOR_BUFFER_BIT;
  4283. if (depthStencil && this._depthCullingState.depthMask)
  4284. mode |= this._gl.DEPTH_BUFFER_BIT;
  4285. this._gl.clear(mode);
  4286. };
  4287. /**
  4288. * Set the WebGL's viewport
  4289. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  4290. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4291. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4292. */
  4293. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4294. var width = requiredWidth || this._renderingCanvas.width;
  4295. var height = requiredHeight || this._renderingCanvas.height;
  4296. var x = viewport.x || 0;
  4297. var y = viewport.y || 0;
  4298. this._cachedViewport = viewport;
  4299. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4300. };
  4301. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4302. this._cachedViewport = null;
  4303. this._gl.viewport(x, y, width, height);
  4304. };
  4305. Engine.prototype.beginFrame = function () {
  4306. this._measureFps();
  4307. };
  4308. Engine.prototype.endFrame = function () {
  4309. //this.flushFramebuffer();
  4310. };
  4311. /**
  4312. * resize the view according to the canvas' size.
  4313. * @example
  4314. * window.addEventListener("resize", function () {
  4315. * engine.resize();
  4316. * });
  4317. */
  4318. Engine.prototype.resize = function () {
  4319. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  4320. };
  4321. /**
  4322. * force a specific size of the canvas
  4323. * @param {number} width - the new canvas' width
  4324. * @param {number} height - the new canvas' height
  4325. */
  4326. Engine.prototype.setSize = function (width, height) {
  4327. this._renderingCanvas.width = width;
  4328. this._renderingCanvas.height = height;
  4329. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4330. };
  4331. Engine.prototype.bindFramebuffer = function (texture) {
  4332. this._currentRenderTarget = texture;
  4333. var gl = this._gl;
  4334. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4335. this._gl.viewport(0, 0, texture._width, texture._height);
  4336. this.wipeCaches();
  4337. };
  4338. Engine.prototype.unBindFramebuffer = function (texture) {
  4339. this._currentRenderTarget = null;
  4340. if (texture.generateMipMaps) {
  4341. var gl = this._gl;
  4342. gl.bindTexture(gl.TEXTURE_2D, texture);
  4343. gl.generateMipmap(gl.TEXTURE_2D);
  4344. gl.bindTexture(gl.TEXTURE_2D, null);
  4345. }
  4346. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4347. };
  4348. Engine.prototype.flushFramebuffer = function () {
  4349. this._gl.flush();
  4350. };
  4351. Engine.prototype.restoreDefaultFramebuffer = function () {
  4352. this._currentRenderTarget = null;
  4353. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4354. this.setViewport(this._cachedViewport);
  4355. this.wipeCaches();
  4356. };
  4357. // VBOs
  4358. Engine.prototype._resetVertexBufferBinding = function () {
  4359. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4360. this._cachedVertexBuffers = null;
  4361. };
  4362. Engine.prototype.createVertexBuffer = function (vertices) {
  4363. var vbo = this._gl.createBuffer();
  4364. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4365. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4366. this._resetVertexBufferBinding();
  4367. vbo.references = 1;
  4368. return vbo;
  4369. };
  4370. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4371. var vbo = this._gl.createBuffer();
  4372. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4373. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4374. this._resetVertexBufferBinding();
  4375. vbo.references = 1;
  4376. return vbo;
  4377. };
  4378. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4379. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4380. if (offset === undefined) {
  4381. offset = 0;
  4382. }
  4383. if (vertices instanceof Float32Array) {
  4384. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4385. }
  4386. else {
  4387. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4388. }
  4389. this._resetVertexBufferBinding();
  4390. };
  4391. Engine.prototype._resetIndexBufferBinding = function () {
  4392. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4393. this._cachedIndexBuffer = null;
  4394. };
  4395. Engine.prototype.createIndexBuffer = function (indices) {
  4396. var vbo = this._gl.createBuffer();
  4397. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4398. // Check for 32 bits indices
  4399. var arrayBuffer;
  4400. var need32Bits = false;
  4401. if (this._caps.uintIndices) {
  4402. for (var index = 0; index < indices.length; index++) {
  4403. if (indices[index] > 65535) {
  4404. need32Bits = true;
  4405. break;
  4406. }
  4407. }
  4408. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4409. }
  4410. else {
  4411. arrayBuffer = new Uint16Array(indices);
  4412. }
  4413. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4414. this._resetIndexBufferBinding();
  4415. vbo.references = 1;
  4416. vbo.is32Bits = need32Bits;
  4417. return vbo;
  4418. };
  4419. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4420. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4421. this._cachedVertexBuffers = vertexBuffer;
  4422. this._cachedEffectForVertexBuffers = effect;
  4423. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4424. var offset = 0;
  4425. for (var index = 0; index < vertexDeclaration.length; index++) {
  4426. var order = effect.getAttributeLocation(index);
  4427. if (order >= 0) {
  4428. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4429. }
  4430. offset += vertexDeclaration[index] * 4;
  4431. }
  4432. }
  4433. if (this._cachedIndexBuffer !== indexBuffer) {
  4434. this._cachedIndexBuffer = indexBuffer;
  4435. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4436. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4437. }
  4438. };
  4439. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4440. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4441. this._cachedVertexBuffers = vertexBuffers;
  4442. this._cachedEffectForVertexBuffers = effect;
  4443. var attributes = effect.getAttributesNames();
  4444. for (var index = 0; index < attributes.length; index++) {
  4445. var order = effect.getAttributeLocation(index);
  4446. if (order >= 0) {
  4447. var vertexBuffer = vertexBuffers[attributes[index]];
  4448. if (!vertexBuffer) {
  4449. continue;
  4450. }
  4451. var stride = vertexBuffer.getStrideSize();
  4452. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4453. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4454. }
  4455. }
  4456. }
  4457. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4458. this._cachedIndexBuffer = indexBuffer;
  4459. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4460. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4461. }
  4462. };
  4463. Engine.prototype._releaseBuffer = function (buffer) {
  4464. buffer.references--;
  4465. if (buffer.references === 0) {
  4466. this._gl.deleteBuffer(buffer);
  4467. return true;
  4468. }
  4469. return false;
  4470. };
  4471. Engine.prototype.createInstancesBuffer = function (capacity) {
  4472. var buffer = this._gl.createBuffer();
  4473. buffer.capacity = capacity;
  4474. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4475. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4476. return buffer;
  4477. };
  4478. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4479. this._gl.deleteBuffer(buffer);
  4480. };
  4481. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4482. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4483. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4484. for (var index = 0; index < 4; index++) {
  4485. var offsetLocation = offsetLocations[index];
  4486. this._gl.enableVertexAttribArray(offsetLocation);
  4487. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4488. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4489. }
  4490. };
  4491. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4492. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4493. for (var index = 0; index < 4; index++) {
  4494. var offsetLocation = offsetLocations[index];
  4495. this._gl.disableVertexAttribArray(offsetLocation);
  4496. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4497. }
  4498. };
  4499. Engine.prototype.applyStates = function () {
  4500. this._depthCullingState.apply(this._gl);
  4501. this._alphaState.apply(this._gl);
  4502. };
  4503. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4504. // Apply states
  4505. this.applyStates();
  4506. this._drawCalls++;
  4507. // Render
  4508. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4509. if (instancesCount) {
  4510. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4511. return;
  4512. }
  4513. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4514. };
  4515. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4516. // Apply states
  4517. this.applyStates();
  4518. this._drawCalls++;
  4519. if (instancesCount) {
  4520. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4521. return;
  4522. }
  4523. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4524. };
  4525. // Shaders
  4526. Engine.prototype._releaseEffect = function (effect) {
  4527. if (this._compiledEffects[effect._key]) {
  4528. delete this._compiledEffects[effect._key];
  4529. if (effect.getProgram()) {
  4530. this._gl.deleteProgram(effect.getProgram());
  4531. }
  4532. }
  4533. };
  4534. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4535. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4536. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4537. var name = vertex + "+" + fragment + "@" + defines;
  4538. if (this._compiledEffects[name]) {
  4539. return this._compiledEffects[name];
  4540. }
  4541. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4542. effect._key = name;
  4543. this._compiledEffects[name] = effect;
  4544. return effect;
  4545. };
  4546. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4547. if (uniformsNames === void 0) { uniformsNames = []; }
  4548. if (samplers === void 0) { samplers = []; }
  4549. if (defines === void 0) { defines = ""; }
  4550. return this.createEffect({
  4551. vertex: "particles",
  4552. fragmentElement: fragmentName
  4553. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4554. };
  4555. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4556. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4557. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4558. var shaderProgram = this._gl.createProgram();
  4559. this._gl.attachShader(shaderProgram, vertexShader);
  4560. this._gl.attachShader(shaderProgram, fragmentShader);
  4561. this._gl.linkProgram(shaderProgram);
  4562. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4563. if (!linked) {
  4564. var error = this._gl.getProgramInfoLog(shaderProgram);
  4565. if (error) {
  4566. throw new Error(error);
  4567. }
  4568. }
  4569. this._gl.deleteShader(vertexShader);
  4570. this._gl.deleteShader(fragmentShader);
  4571. return shaderProgram;
  4572. };
  4573. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4574. var results = [];
  4575. for (var index = 0; index < uniformsNames.length; index++) {
  4576. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4577. }
  4578. return results;
  4579. };
  4580. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4581. var results = [];
  4582. for (var index = 0; index < attributesNames.length; index++) {
  4583. try {
  4584. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4585. }
  4586. catch (e) {
  4587. results.push(-1);
  4588. }
  4589. }
  4590. return results;
  4591. };
  4592. Engine.prototype.enableEffect = function (effect) {
  4593. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4594. if (effect && effect.onBind) {
  4595. effect.onBind(effect);
  4596. }
  4597. return;
  4598. }
  4599. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4600. // Use program
  4601. this._gl.useProgram(effect.getProgram());
  4602. for (var i in this._vertexAttribArrays) {
  4603. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4604. continue;
  4605. }
  4606. this._vertexAttribArrays[i] = false;
  4607. this._gl.disableVertexAttribArray(i);
  4608. }
  4609. var attributesCount = effect.getAttributesCount();
  4610. for (var index = 0; index < attributesCount; index++) {
  4611. // Attributes
  4612. var order = effect.getAttributeLocation(index);
  4613. if (order >= 0) {
  4614. this._vertexAttribArrays[order] = true;
  4615. this._gl.enableVertexAttribArray(order);
  4616. }
  4617. }
  4618. this._currentEffect = effect;
  4619. if (effect.onBind) {
  4620. effect.onBind(effect);
  4621. }
  4622. };
  4623. Engine.prototype.setArray = function (uniform, array) {
  4624. if (!uniform)
  4625. return;
  4626. this._gl.uniform1fv(uniform, array);
  4627. };
  4628. Engine.prototype.setArray2 = function (uniform, array) {
  4629. if (!uniform || array.length % 2 !== 0)
  4630. return;
  4631. this._gl.uniform2fv(uniform, array);
  4632. };
  4633. Engine.prototype.setArray3 = function (uniform, array) {
  4634. if (!uniform || array.length % 3 !== 0)
  4635. return;
  4636. this._gl.uniform3fv(uniform, array);
  4637. };
  4638. Engine.prototype.setArray4 = function (uniform, array) {
  4639. if (!uniform || array.length % 4 !== 0)
  4640. return;
  4641. this._gl.uniform4fv(uniform, array);
  4642. };
  4643. Engine.prototype.setMatrices = function (uniform, matrices) {
  4644. if (!uniform)
  4645. return;
  4646. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4647. };
  4648. Engine.prototype.setMatrix = function (uniform, matrix) {
  4649. if (!uniform)
  4650. return;
  4651. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4652. };
  4653. Engine.prototype.setFloat = function (uniform, value) {
  4654. if (!uniform)
  4655. return;
  4656. this._gl.uniform1f(uniform, value);
  4657. };
  4658. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4659. if (!uniform)
  4660. return;
  4661. this._gl.uniform2f(uniform, x, y);
  4662. };
  4663. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4664. if (!uniform)
  4665. return;
  4666. this._gl.uniform3f(uniform, x, y, z);
  4667. };
  4668. Engine.prototype.setBool = function (uniform, bool) {
  4669. if (!uniform)
  4670. return;
  4671. this._gl.uniform1i(uniform, bool);
  4672. };
  4673. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4674. if (!uniform)
  4675. return;
  4676. this._gl.uniform4f(uniform, x, y, z, w);
  4677. };
  4678. Engine.prototype.setColor3 = function (uniform, color3) {
  4679. if (!uniform)
  4680. return;
  4681. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4682. };
  4683. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4684. if (!uniform)
  4685. return;
  4686. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4687. };
  4688. // States
  4689. Engine.prototype.setState = function (culling, force) {
  4690. // Culling
  4691. if (this._depthCullingState.cull !== culling || force) {
  4692. if (culling) {
  4693. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4694. this._depthCullingState.cull = true;
  4695. }
  4696. else {
  4697. this._depthCullingState.cull = false;
  4698. }
  4699. }
  4700. };
  4701. Engine.prototype.setDepthBuffer = function (enable) {
  4702. this._depthCullingState.depthTest = enable;
  4703. };
  4704. Engine.prototype.getDepthWrite = function () {
  4705. return this._depthCullingState.depthMask;
  4706. };
  4707. Engine.prototype.setDepthWrite = function (enable) {
  4708. this._depthCullingState.depthMask = enable;
  4709. };
  4710. Engine.prototype.setColorWrite = function (enable) {
  4711. this._gl.colorMask(enable, enable, enable, enable);
  4712. };
  4713. Engine.prototype.setAlphaMode = function (mode) {
  4714. switch (mode) {
  4715. case Engine.ALPHA_DISABLE:
  4716. this.setDepthWrite(true);
  4717. this._alphaState.alphaBlend = false;
  4718. break;
  4719. case Engine.ALPHA_COMBINE:
  4720. this.setDepthWrite(false);
  4721. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4722. this._alphaState.alphaBlend = true;
  4723. break;
  4724. case Engine.ALPHA_ADD:
  4725. this.setDepthWrite(false);
  4726. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4727. this._alphaState.alphaBlend = true;
  4728. break;
  4729. }
  4730. this._alphaMode = mode;
  4731. };
  4732. Engine.prototype.getAlphaMode = function () {
  4733. return this._alphaMode;
  4734. };
  4735. Engine.prototype.setAlphaTesting = function (enable) {
  4736. this._alphaTest = enable;
  4737. };
  4738. Engine.prototype.getAlphaTesting = function () {
  4739. return this._alphaTest;
  4740. };
  4741. // Textures
  4742. Engine.prototype.wipeCaches = function () {
  4743. this._activeTexturesCache = [];
  4744. this._currentEffect = null;
  4745. this._depthCullingState.reset();
  4746. this._alphaState.reset();
  4747. this._cachedVertexBuffers = null;
  4748. this._cachedIndexBuffer = null;
  4749. this._cachedEffectForVertexBuffers = null;
  4750. };
  4751. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4752. var gl = this._gl;
  4753. gl.bindTexture(gl.TEXTURE_2D, texture);
  4754. var magFilter = gl.NEAREST;
  4755. var minFilter = gl.NEAREST;
  4756. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4757. magFilter = gl.LINEAR;
  4758. minFilter = gl.LINEAR;
  4759. }
  4760. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4761. magFilter = gl.LINEAR;
  4762. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4763. }
  4764. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4765. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4766. gl.bindTexture(gl.TEXTURE_2D, null);
  4767. texture.samplingMode = samplingMode;
  4768. };
  4769. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4770. var _this = this;
  4771. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4772. if (onLoad === void 0) { onLoad = null; }
  4773. if (onError === void 0) { onError = null; }
  4774. if (buffer === void 0) { buffer = null; }
  4775. var texture = this._gl.createTexture();
  4776. var extension;
  4777. var fromData = false;
  4778. if (url.substr(0, 5) === "data:") {
  4779. fromData = true;
  4780. }
  4781. if (!fromData)
  4782. extension = url.substr(url.length - 4, 4).toLowerCase();
  4783. else {
  4784. var oldUrl = url;
  4785. fromData = oldUrl.split(':');
  4786. url = oldUrl;
  4787. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4788. }
  4789. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4790. var isTGA = (extension === ".tga");
  4791. scene._addPendingData(texture);
  4792. texture.url = url;
  4793. texture.noMipmap = noMipmap;
  4794. texture.references = 1;
  4795. this._loadedTexturesCache.push(texture);
  4796. var onerror = function () {
  4797. scene._removePendingData(texture);
  4798. if (onError) {
  4799. onError();
  4800. }
  4801. };
  4802. if (isTGA) {
  4803. var callback = function (arrayBuffer) {
  4804. var data = new Uint8Array(arrayBuffer);
  4805. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4806. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4807. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4808. if (onLoad) {
  4809. onLoad();
  4810. }
  4811. }, samplingMode);
  4812. };
  4813. if (!(fromData instanceof Array))
  4814. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4815. callback(arrayBuffer);
  4816. }, onerror, scene.database, true);
  4817. else
  4818. callback(buffer);
  4819. }
  4820. else if (isDDS) {
  4821. callback = function (data) {
  4822. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4823. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4824. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4825. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4826. if (onLoad) {
  4827. onLoad();
  4828. }
  4829. }, samplingMode);
  4830. };
  4831. if (!(fromData instanceof Array))
  4832. BABYLON.Tools.LoadFile(url, function (data) {
  4833. callback(data);
  4834. }, onerror, scene.database, true);
  4835. else
  4836. callback(buffer);
  4837. }
  4838. else {
  4839. var onload = function (img) {
  4840. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4841. var isPot = (img.width === potWidth && img.height === potHeight);
  4842. if (!isPot) {
  4843. _this._workingCanvas.width = potWidth;
  4844. _this._workingCanvas.height = potHeight;
  4845. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4846. _this._workingContext.imageSmoothingEnabled = false;
  4847. _this._workingContext.mozImageSmoothingEnabled = false;
  4848. _this._workingContext.oImageSmoothingEnabled = false;
  4849. _this._workingContext.webkitImageSmoothingEnabled = false;
  4850. _this._workingContext.msImageSmoothingEnabled = false;
  4851. }
  4852. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4853. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4854. _this._workingContext.imageSmoothingEnabled = true;
  4855. _this._workingContext.mozImageSmoothingEnabled = true;
  4856. _this._workingContext.oImageSmoothingEnabled = true;
  4857. _this._workingContext.webkitImageSmoothingEnabled = true;
  4858. _this._workingContext.msImageSmoothingEnabled = true;
  4859. }
  4860. }
  4861. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4862. if (onLoad) {
  4863. onLoad();
  4864. }
  4865. }, samplingMode);
  4866. };
  4867. if (!(fromData instanceof Array))
  4868. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4869. else
  4870. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4871. }
  4872. return texture;
  4873. };
  4874. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4875. var texture = this._gl.createTexture();
  4876. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4877. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4878. // Format
  4879. var internalFormat = this._gl.RGBA;
  4880. switch (format) {
  4881. case Engine.TEXTUREFORMAT_ALPHA:
  4882. internalFormat = this._gl.ALPHA;
  4883. break;
  4884. case Engine.TEXTUREFORMAT_LUMINANCE:
  4885. internalFormat = this._gl.LUMINANCE;
  4886. break;
  4887. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4888. internalFormat = this._gl.LUMINANCE_ALPHA;
  4889. break;
  4890. case Engine.TEXTUREFORMAT_RGB:
  4891. internalFormat = this._gl.RGB;
  4892. break;
  4893. case Engine.TEXTUREFORMAT_RGBA:
  4894. internalFormat = this._gl.RGBA;
  4895. break;
  4896. }
  4897. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4898. if (generateMipMaps) {
  4899. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4900. }
  4901. // Filters
  4902. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4903. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4904. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4905. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4906. this._activeTexturesCache = [];
  4907. texture._baseWidth = width;
  4908. texture._baseHeight = height;
  4909. texture._width = width;
  4910. texture._height = height;
  4911. texture.isReady = true;
  4912. texture.references = 1;
  4913. texture.samplingMode = samplingMode;
  4914. this._loadedTexturesCache.push(texture);
  4915. return texture;
  4916. };
  4917. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4918. var texture = this._gl.createTexture();
  4919. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4920. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4921. this._activeTexturesCache = [];
  4922. texture._baseWidth = width;
  4923. texture._baseHeight = height;
  4924. texture._width = width;
  4925. texture._height = height;
  4926. texture.isReady = false;
  4927. texture.generateMipMaps = generateMipMaps;
  4928. texture.references = 1;
  4929. texture.samplingMode = samplingMode;
  4930. this.updateTextureSamplingMode(samplingMode, texture);
  4931. this._loadedTexturesCache.push(texture);
  4932. return texture;
  4933. };
  4934. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  4935. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  4936. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4937. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4938. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4939. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4940. };
  4941. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4942. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4943. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4944. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4945. if (texture.generateMipMaps) {
  4946. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4947. }
  4948. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4949. this._activeTexturesCache = [];
  4950. texture.isReady = true;
  4951. };
  4952. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4953. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4954. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4955. // Scale the video if it is a NPOT using the current working canvas
  4956. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4957. if (!texture._workingCanvas) {
  4958. texture._workingCanvas = document.createElement("canvas");
  4959. texture._workingContext = texture._workingCanvas.getContext("2d");
  4960. texture._workingCanvas.width = texture._width;
  4961. texture._workingCanvas.height = texture._height;
  4962. }
  4963. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4964. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4965. }
  4966. else {
  4967. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4968. }
  4969. if (texture.generateMipMaps) {
  4970. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4971. }
  4972. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4973. this._activeTexturesCache = [];
  4974. texture.isReady = true;
  4975. };
  4976. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4977. // old version had a "generateMipMaps" arg instead of options.
  4978. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4979. // in the same way, generateDepthBuffer is defaulted to true
  4980. var generateMipMaps = false;
  4981. var generateDepthBuffer = true;
  4982. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4983. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4984. if (options !== undefined) {
  4985. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4986. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4987. type = options.type === undefined ? type : options.type;
  4988. if (options.samplingMode !== undefined) {
  4989. samplingMode = options.samplingMode;
  4990. }
  4991. if (type === Engine.TEXTURETYPE_FLOAT) {
  4992. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4993. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4994. }
  4995. }
  4996. var gl = this._gl;
  4997. var texture = gl.createTexture();
  4998. gl.bindTexture(gl.TEXTURE_2D, texture);
  4999. var width = size.width || size;
  5000. var height = size.height || size;
  5001. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  5002. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  5003. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5004. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  5005. }
  5006. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5007. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5008. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5009. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5010. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  5011. var depthBuffer;
  5012. // Create the depth buffer
  5013. if (generateDepthBuffer) {
  5014. depthBuffer = gl.createRenderbuffer();
  5015. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  5016. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  5017. }
  5018. // Create the framebuffer
  5019. var framebuffer = gl.createFramebuffer();
  5020. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  5021. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5022. if (generateDepthBuffer) {
  5023. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  5024. }
  5025. // Unbind
  5026. gl.bindTexture(gl.TEXTURE_2D, null);
  5027. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  5028. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5029. texture._framebuffer = framebuffer;
  5030. if (generateDepthBuffer) {
  5031. texture._depthBuffer = depthBuffer;
  5032. }
  5033. texture._width = width;
  5034. texture._height = height;
  5035. texture.isReady = true;
  5036. texture.generateMipMaps = generateMipMaps;
  5037. texture.references = 1;
  5038. texture.samplingMode = samplingMode;
  5039. this._activeTexturesCache = [];
  5040. this._loadedTexturesCache.push(texture);
  5041. return texture;
  5042. };
  5043. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  5044. var _this = this;
  5045. var gl = this._gl;
  5046. var texture = gl.createTexture();
  5047. texture.isCube = true;
  5048. texture.url = rootUrl;
  5049. texture.references = 1;
  5050. this._loadedTexturesCache.push(texture);
  5051. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  5052. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  5053. if (isDDS) {
  5054. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  5055. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  5056. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  5057. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5058. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  5059. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  5060. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  5061. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5062. }
  5063. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5064. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  5065. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5066. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5067. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5068. _this._activeTexturesCache = [];
  5069. texture._width = info.width;
  5070. texture._height = info.height;
  5071. texture.isReady = true;
  5072. }, null, null, true);
  5073. }
  5074. else {
  5075. cascadeLoad(rootUrl, scene, function (imgs) {
  5076. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  5077. var height = width;
  5078. _this._workingCanvas.width = width;
  5079. _this._workingCanvas.height = height;
  5080. var faces = [
  5081. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  5082. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  5083. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  5084. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  5085. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  5086. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  5087. ];
  5088. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5089. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  5090. for (var index = 0; index < faces.length; index++) {
  5091. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  5092. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  5093. }
  5094. if (!noMipmap) {
  5095. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5096. }
  5097. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5098. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  5099. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5100. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5101. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5102. _this._activeTexturesCache = [];
  5103. texture._width = width;
  5104. texture._height = height;
  5105. texture.isReady = true;
  5106. }, extensions);
  5107. }
  5108. return texture;
  5109. };
  5110. Engine.prototype._releaseTexture = function (texture) {
  5111. var gl = this._gl;
  5112. if (texture._framebuffer) {
  5113. gl.deleteFramebuffer(texture._framebuffer);
  5114. }
  5115. if (texture._depthBuffer) {
  5116. gl.deleteRenderbuffer(texture._depthBuffer);
  5117. }
  5118. gl.deleteTexture(texture);
  5119. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  5120. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5121. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5122. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5123. this._activeTexturesCache[channel] = null;
  5124. }
  5125. var index = this._loadedTexturesCache.indexOf(texture);
  5126. if (index !== -1) {
  5127. this._loadedTexturesCache.splice(index, 1);
  5128. }
  5129. };
  5130. Engine.prototype.bindSamplers = function (effect) {
  5131. this._gl.useProgram(effect.getProgram());
  5132. var samplers = effect.getSamplers();
  5133. for (var index = 0; index < samplers.length; index++) {
  5134. var uniform = effect.getUniform(samplers[index]);
  5135. this._gl.uniform1i(uniform, index);
  5136. }
  5137. this._currentEffect = null;
  5138. };
  5139. Engine.prototype._bindTexture = function (channel, texture) {
  5140. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5141. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5142. this._activeTexturesCache[channel] = null;
  5143. };
  5144. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  5145. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  5146. };
  5147. Engine.prototype.setTexture = function (channel, texture) {
  5148. if (channel < 0) {
  5149. return;
  5150. }
  5151. // Not ready?
  5152. if (!texture || !texture.isReady()) {
  5153. if (this._activeTexturesCache[channel] != null) {
  5154. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5155. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5156. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5157. this._activeTexturesCache[channel] = null;
  5158. }
  5159. return;
  5160. }
  5161. // Video
  5162. if (texture instanceof BABYLON.VideoTexture) {
  5163. if (texture.update()) {
  5164. this._activeTexturesCache[channel] = null;
  5165. }
  5166. }
  5167. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  5168. texture.delayLoad();
  5169. return;
  5170. }
  5171. if (this._activeTexturesCache[channel] === texture) {
  5172. return;
  5173. }
  5174. this._activeTexturesCache[channel] = texture;
  5175. var internalTexture = texture.getInternalTexture();
  5176. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5177. if (internalTexture.isCube) {
  5178. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  5179. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  5180. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  5181. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  5182. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  5183. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  5184. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  5185. }
  5186. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  5187. }
  5188. else {
  5189. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  5190. if (internalTexture._cachedWrapU !== texture.wrapU) {
  5191. internalTexture._cachedWrapU = texture.wrapU;
  5192. switch (texture.wrapU) {
  5193. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5194. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  5195. break;
  5196. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5197. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  5198. break;
  5199. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5200. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  5201. break;
  5202. }
  5203. }
  5204. if (internalTexture._cachedWrapV !== texture.wrapV) {
  5205. internalTexture._cachedWrapV = texture.wrapV;
  5206. switch (texture.wrapV) {
  5207. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5208. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  5209. break;
  5210. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5211. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  5212. break;
  5213. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5214. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  5215. break;
  5216. }
  5217. }
  5218. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  5219. }
  5220. };
  5221. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  5222. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5223. var value = texture.anisotropicFilteringLevel;
  5224. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5225. value = 1;
  5226. }
  5227. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  5228. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  5229. texture._cachedAnisotropicFilteringLevel = value;
  5230. }
  5231. };
  5232. Engine.prototype.readPixels = function (x, y, width, height) {
  5233. var data = new Uint8Array(height * width * 4);
  5234. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5235. return data;
  5236. };
  5237. // Dispose
  5238. Engine.prototype.dispose = function () {
  5239. this.hideLoadingUI();
  5240. this.stopRenderLoop();
  5241. while (this.scenes.length) {
  5242. this.scenes[0].dispose();
  5243. }
  5244. // Release audio engine
  5245. Engine.audioEngine.dispose();
  5246. for (var name in this._compiledEffects) {
  5247. this._gl.deleteProgram(this._compiledEffects[name]._program);
  5248. }
  5249. for (var i in this._vertexAttribArrays) {
  5250. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5251. continue;
  5252. }
  5253. this._gl.disableVertexAttribArray(i);
  5254. }
  5255. // Events
  5256. window.removeEventListener("blur", this._onBlur);
  5257. window.removeEventListener("focus", this._onFocus);
  5258. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5259. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5260. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5261. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5262. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5263. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5264. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5265. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5266. };
  5267. // Loading screen
  5268. Engine.prototype.displayLoadingUI = function () {
  5269. var _this = this;
  5270. this._loadingDiv = document.createElement("div");
  5271. this._loadingDiv.style.opacity = "0";
  5272. this._loadingDiv.style.transition = "opacity 1.5s ease";
  5273. // Loading text
  5274. this._loadingTextDiv = document.createElement("div");
  5275. this._loadingTextDiv.style.position = "absolute";
  5276. this._loadingTextDiv.style.left = "0";
  5277. this._loadingTextDiv.style.top = "50%";
  5278. this._loadingTextDiv.style.marginTop = "80px";
  5279. this._loadingTextDiv.style.width = "100%";
  5280. this._loadingTextDiv.style.height = "20px";
  5281. this._loadingTextDiv.style.fontFamily = "Arial";
  5282. this._loadingTextDiv.style.fontSize = "14px";
  5283. this._loadingTextDiv.style.color = "white";
  5284. this._loadingTextDiv.style.textAlign = "center";
  5285. this._loadingTextDiv.innerHTML = "Loading";
  5286. this._loadingDiv.appendChild(this._loadingTextDiv);
  5287. // Loading img
  5288. var imgBack = new Image();
  5289. 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==";
  5290. imgBack.style.position = "absolute";
  5291. imgBack.style.left = "50%";
  5292. imgBack.style.top = "50%";
  5293. imgBack.style.marginLeft = "-50px";
  5294. imgBack.style.marginTop = "-50px";
  5295. imgBack.style.transition = "transform 1.0s ease";
  5296. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  5297. var deg = 360;
  5298. var onTransitionEnd = function () {
  5299. deg += 360;
  5300. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5301. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5302. };
  5303. imgBack.addEventListener("transitionend", onTransitionEnd);
  5304. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5305. this._loadingDiv.appendChild(imgBack);
  5306. // front image
  5307. var imgFront = new Image();
  5308. 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=";
  5309. imgFront.style.position = "absolute";
  5310. imgFront.style.left = "50%";
  5311. imgFront.style.top = "50%";
  5312. imgFront.style.marginLeft = "-50px";
  5313. imgFront.style.marginTop = "-50px";
  5314. this._loadingDiv.appendChild(imgFront);
  5315. // Resize
  5316. this._resizeLoadingUI = function () {
  5317. var canvasRect = _this.getRenderingCanvasClientRect();
  5318. _this._loadingDiv.style.position = "absolute";
  5319. _this._loadingDiv.style.left = canvasRect.left + "px";
  5320. _this._loadingDiv.style.top = canvasRect.top + "px";
  5321. _this._loadingDiv.style.width = canvasRect.width + "px";
  5322. _this._loadingDiv.style.height = canvasRect.height + "px";
  5323. };
  5324. this._resizeLoadingUI();
  5325. window.addEventListener("resize", this._resizeLoadingUI);
  5326. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5327. document.body.appendChild(this._loadingDiv);
  5328. setTimeout(function () {
  5329. _this._loadingDiv.style.opacity = "1";
  5330. imgBack.style.transform = "rotateZ(360deg)";
  5331. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5332. }, 0);
  5333. };
  5334. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5335. set: function (text) {
  5336. if (!this._loadingDiv) {
  5337. return;
  5338. }
  5339. this._loadingTextDiv.innerHTML = text;
  5340. },
  5341. enumerable: true,
  5342. configurable: true
  5343. });
  5344. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5345. get: function () {
  5346. return this._loadingDivBackgroundColor;
  5347. },
  5348. set: function (color) {
  5349. this._loadingDivBackgroundColor = color;
  5350. if (!this._loadingDiv) {
  5351. return;
  5352. }
  5353. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5354. },
  5355. enumerable: true,
  5356. configurable: true
  5357. });
  5358. Engine.prototype.hideLoadingUI = function () {
  5359. var _this = this;
  5360. if (!this._loadingDiv) {
  5361. return;
  5362. }
  5363. var onTransitionEnd = function () {
  5364. if (!_this._loadingDiv) {
  5365. return;
  5366. }
  5367. document.body.removeChild(_this._loadingDiv);
  5368. window.removeEventListener("resize", _this._resizeLoadingUI);
  5369. _this._loadingDiv = null;
  5370. };
  5371. this._loadingDiv.style.opacity = "0";
  5372. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5373. };
  5374. // FPS
  5375. Engine.prototype.getFps = function () {
  5376. return this.fps;
  5377. };
  5378. Engine.prototype.getDeltaTime = function () {
  5379. return this.deltaTime;
  5380. };
  5381. Engine.prototype._measureFps = function () {
  5382. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5383. var length = this.previousFramesDuration.length;
  5384. if (length >= 2) {
  5385. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5386. }
  5387. if (length >= this.fpsRange) {
  5388. if (length > this.fpsRange) {
  5389. this.previousFramesDuration.splice(0, 1);
  5390. length = this.previousFramesDuration.length;
  5391. }
  5392. var sum = 0;
  5393. for (var id = 0; id < length - 1; id++) {
  5394. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5395. }
  5396. this.fps = 1000.0 / (sum / (length - 1));
  5397. }
  5398. };
  5399. // Statics
  5400. Engine.isSupported = function () {
  5401. try {
  5402. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5403. if (navigator.isCocoonJS) {
  5404. return true;
  5405. }
  5406. var tempcanvas = document.createElement("canvas");
  5407. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5408. return gl != null && !!window.WebGLRenderingContext;
  5409. }
  5410. catch (e) {
  5411. return false;
  5412. }
  5413. };
  5414. // Const statics
  5415. Engine._ALPHA_DISABLE = 0;
  5416. Engine._ALPHA_ADD = 1;
  5417. Engine._ALPHA_COMBINE = 2;
  5418. Engine._DELAYLOADSTATE_NONE = 0;
  5419. Engine._DELAYLOADSTATE_LOADED = 1;
  5420. Engine._DELAYLOADSTATE_LOADING = 2;
  5421. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5422. Engine._TEXTUREFORMAT_ALPHA = 0;
  5423. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5424. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5425. Engine._TEXTUREFORMAT_RGB = 4;
  5426. Engine._TEXTUREFORMAT_RGBA = 4;
  5427. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5428. Engine._TEXTURETYPE_FLOAT = 1;
  5429. // Updatable statics so stick with vars here
  5430. Engine.Epsilon = 0.001;
  5431. Engine.CollisionsEpsilon = 0.001;
  5432. Engine.ShadersRepository = "Babylon/Shaders/";
  5433. return Engine;
  5434. })();
  5435. BABYLON.Engine = Engine;
  5436. })(BABYLON || (BABYLON = {}));
  5437. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5438. (function (BABYLON) {
  5439. /**
  5440. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5441. */
  5442. var Node = (function () {
  5443. /**
  5444. * @constructor
  5445. * @param {string} name - the name and id to be given to this node
  5446. * @param {BABYLON.Scene} the scene this node will be added to
  5447. */
  5448. function Node(name, scene) {
  5449. this.state = "";
  5450. this.animations = new Array();
  5451. this._childrenFlag = -1;
  5452. this._isEnabled = true;
  5453. this._isReady = true;
  5454. this._currentRenderId = -1;
  5455. this._parentRenderId = -1;
  5456. this.name = name;
  5457. this.id = name;
  5458. this._scene = scene;
  5459. this._initCache();
  5460. }
  5461. Node.prototype.getScene = function () {
  5462. return this._scene;
  5463. };
  5464. Node.prototype.getEngine = function () {
  5465. return this._scene.getEngine();
  5466. };
  5467. // override it in derived class
  5468. Node.prototype.getWorldMatrix = function () {
  5469. return BABYLON.Matrix.Identity();
  5470. };
  5471. // override it in derived class if you add new variables to the cache
  5472. // and call the parent class method
  5473. Node.prototype._initCache = function () {
  5474. this._cache = {};
  5475. this._cache.parent = undefined;
  5476. };
  5477. Node.prototype.updateCache = function (force) {
  5478. if (!force && this.isSynchronized())
  5479. return;
  5480. this._cache.parent = this.parent;
  5481. this._updateCache();
  5482. };
  5483. // override it in derived class if you add new variables to the cache
  5484. // and call the parent class method if !ignoreParentClass
  5485. Node.prototype._updateCache = function (ignoreParentClass) {
  5486. };
  5487. // override it in derived class if you add new variables to the cache
  5488. Node.prototype._isSynchronized = function () {
  5489. return true;
  5490. };
  5491. Node.prototype.isSynchronizedWithParent = function () {
  5492. if (!this.parent) {
  5493. return true;
  5494. }
  5495. if (this._parentRenderId !== this.parent._currentRenderId) {
  5496. return false;
  5497. }
  5498. this._parentRenderId = this.parent._currentRenderId;
  5499. return this.parent._currentRenderId <= this._currentRenderId && this.parent.isSynchronized();
  5500. };
  5501. Node.prototype.isSynchronized = function (updateCache) {
  5502. var check = this.hasNewParent();
  5503. check = check || !this.isSynchronizedWithParent();
  5504. check = check || !this._isSynchronized();
  5505. if (updateCache)
  5506. this.updateCache(true);
  5507. return !check;
  5508. };
  5509. Node.prototype.hasNewParent = function (update) {
  5510. if (this._cache.parent === this.parent)
  5511. return false;
  5512. if (update)
  5513. this._cache.parent = this.parent;
  5514. return true;
  5515. };
  5516. /**
  5517. * Is this node ready to be used/rendered
  5518. * @return {boolean} is it ready
  5519. */
  5520. Node.prototype.isReady = function () {
  5521. return this._isReady;
  5522. };
  5523. /**
  5524. * Is this node enabled.
  5525. * If the node has a parent and is enabled, the parent will be inspected as well.
  5526. * @return {boolean} whether this node (and its parent) is enabled.
  5527. * @see setEnabled
  5528. */
  5529. Node.prototype.isEnabled = function () {
  5530. if (!this._isEnabled) {
  5531. return false;
  5532. }
  5533. if (this.parent) {
  5534. return this.parent.isEnabled();
  5535. }
  5536. return true;
  5537. };
  5538. /**
  5539. * Set the enabled state of this node.
  5540. * @param {boolean} value - the new enabled state
  5541. * @see isEnabled
  5542. */
  5543. Node.prototype.setEnabled = function (value) {
  5544. this._isEnabled = value;
  5545. };
  5546. /**
  5547. * Is this node a descendant of the given node.
  5548. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5549. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5550. * @see parent
  5551. */
  5552. Node.prototype.isDescendantOf = function (ancestor) {
  5553. if (this.parent) {
  5554. if (this.parent === ancestor) {
  5555. return true;
  5556. }
  5557. return this.parent.isDescendantOf(ancestor);
  5558. }
  5559. return false;
  5560. };
  5561. Node.prototype._getDescendants = function (list, results) {
  5562. for (var index = 0; index < list.length; index++) {
  5563. var item = list[index];
  5564. if (item.isDescendantOf(this)) {
  5565. results.push(item);
  5566. }
  5567. }
  5568. };
  5569. /**
  5570. * Will return all nodes that have this node as parent.
  5571. * @return {BABYLON.Node[]} all children nodes of all types.
  5572. */
  5573. Node.prototype.getDescendants = function () {
  5574. var results = [];
  5575. this._getDescendants(this._scene.meshes, results);
  5576. this._getDescendants(this._scene.lights, results);
  5577. this._getDescendants(this._scene.cameras, results);
  5578. return results;
  5579. };
  5580. Node.prototype._setReady = function (state) {
  5581. if (state == this._isReady) {
  5582. return;
  5583. }
  5584. if (!state) {
  5585. this._isReady = false;
  5586. return;
  5587. }
  5588. this._isReady = true;
  5589. if (this.onReady) {
  5590. this.onReady(this);
  5591. }
  5592. };
  5593. return Node;
  5594. })();
  5595. BABYLON.Node = Node;
  5596. })(BABYLON || (BABYLON = {}));
  5597. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5598. (function (BABYLON) {
  5599. var BoundingSphere = (function () {
  5600. function BoundingSphere(minimum, maximum) {
  5601. this.minimum = minimum;
  5602. this.maximum = maximum;
  5603. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5604. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5605. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5606. this.radius = distance * 0.5;
  5607. this.centerWorld = BABYLON.Vector3.Zero();
  5608. this._update(BABYLON.Matrix.Identity());
  5609. }
  5610. // Methods
  5611. BoundingSphere.prototype._update = function (world) {
  5612. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5613. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5614. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5615. };
  5616. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5617. for (var i = 0; i < 6; i++) {
  5618. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5619. return false;
  5620. }
  5621. return true;
  5622. };
  5623. BoundingSphere.prototype.intersectsPoint = function (point) {
  5624. var x = this.centerWorld.x - point.x;
  5625. var y = this.centerWorld.y - point.y;
  5626. var z = this.centerWorld.z - point.z;
  5627. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5628. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5629. return false;
  5630. return true;
  5631. };
  5632. // Statics
  5633. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5634. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5635. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5636. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5637. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5638. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5639. return false;
  5640. return true;
  5641. };
  5642. return BoundingSphere;
  5643. })();
  5644. BABYLON.BoundingSphere = BoundingSphere;
  5645. })(BABYLON || (BABYLON = {}));
  5646. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5647. (function (BABYLON) {
  5648. var BoundingBox = (function () {
  5649. function BoundingBox(minimum, maximum) {
  5650. this.minimum = minimum;
  5651. this.maximum = maximum;
  5652. this.vectors = new Array();
  5653. this.vectorsWorld = new Array();
  5654. // Bounding vectors
  5655. this.vectors.push(this.minimum.clone());
  5656. this.vectors.push(this.maximum.clone());
  5657. this.vectors.push(this.minimum.clone());
  5658. this.vectors[2].x = this.maximum.x;
  5659. this.vectors.push(this.minimum.clone());
  5660. this.vectors[3].y = this.maximum.y;
  5661. this.vectors.push(this.minimum.clone());
  5662. this.vectors[4].z = this.maximum.z;
  5663. this.vectors.push(this.maximum.clone());
  5664. this.vectors[5].z = this.minimum.z;
  5665. this.vectors.push(this.maximum.clone());
  5666. this.vectors[6].x = this.minimum.x;
  5667. this.vectors.push(this.maximum.clone());
  5668. this.vectors[7].y = this.minimum.y;
  5669. // OBB
  5670. this.center = this.maximum.add(this.minimum).scale(0.5);
  5671. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5672. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5673. for (var index = 0; index < this.vectors.length; index++) {
  5674. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5675. }
  5676. this.minimumWorld = BABYLON.Vector3.Zero();
  5677. this.maximumWorld = BABYLON.Vector3.Zero();
  5678. this._update(BABYLON.Matrix.Identity());
  5679. }
  5680. // Methods
  5681. BoundingBox.prototype.getWorldMatrix = function () {
  5682. return this._worldMatrix;
  5683. };
  5684. BoundingBox.prototype._update = function (world) {
  5685. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5686. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5687. for (var index = 0; index < this.vectors.length; index++) {
  5688. var v = this.vectorsWorld[index];
  5689. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5690. if (v.x < this.minimumWorld.x)
  5691. this.minimumWorld.x = v.x;
  5692. if (v.y < this.minimumWorld.y)
  5693. this.minimumWorld.y = v.y;
  5694. if (v.z < this.minimumWorld.z)
  5695. this.minimumWorld.z = v.z;
  5696. if (v.x > this.maximumWorld.x)
  5697. this.maximumWorld.x = v.x;
  5698. if (v.y > this.maximumWorld.y)
  5699. this.maximumWorld.y = v.y;
  5700. if (v.z > this.maximumWorld.z)
  5701. this.maximumWorld.z = v.z;
  5702. }
  5703. // OBB
  5704. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5705. this.center.scaleInPlace(0.5);
  5706. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5707. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5708. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5709. this._worldMatrix = world;
  5710. };
  5711. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5712. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5713. };
  5714. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5715. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5716. };
  5717. BoundingBox.prototype.intersectsPoint = function (point) {
  5718. var delta = BABYLON.Engine.Epsilon;
  5719. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5720. return false;
  5721. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5722. return false;
  5723. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5724. return false;
  5725. return true;
  5726. };
  5727. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5728. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5729. };
  5730. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5731. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5732. return false;
  5733. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5734. return false;
  5735. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5736. return false;
  5737. return true;
  5738. };
  5739. // Statics
  5740. BoundingBox.Intersects = function (box0, box1) {
  5741. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5742. return false;
  5743. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5744. return false;
  5745. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5746. return false;
  5747. return true;
  5748. };
  5749. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5750. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5751. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5752. return (num <= (sphereRadius * sphereRadius));
  5753. };
  5754. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5755. for (var p = 0; p < 6; p++) {
  5756. for (var i = 0; i < 8; i++) {
  5757. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5758. return false;
  5759. }
  5760. }
  5761. }
  5762. return true;
  5763. };
  5764. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5765. for (var p = 0; p < 6; p++) {
  5766. var inCount = 8;
  5767. for (var i = 0; i < 8; i++) {
  5768. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5769. --inCount;
  5770. }
  5771. else {
  5772. break;
  5773. }
  5774. }
  5775. if (inCount === 0)
  5776. return false;
  5777. }
  5778. return true;
  5779. };
  5780. return BoundingBox;
  5781. })();
  5782. BABYLON.BoundingBox = BoundingBox;
  5783. })(BABYLON || (BABYLON = {}));
  5784. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5785. (function (BABYLON) {
  5786. var computeBoxExtents = function (axis, box) {
  5787. var p = BABYLON.Vector3.Dot(box.center, axis);
  5788. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5789. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5790. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5791. var r = r0 + r1 + r2;
  5792. return {
  5793. min: p - r,
  5794. max: p + r
  5795. };
  5796. };
  5797. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5798. var axisOverlap = function (axis, box0, box1) {
  5799. var result0 = computeBoxExtents(axis, box0);
  5800. var result1 = computeBoxExtents(axis, box1);
  5801. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5802. };
  5803. var BoundingInfo = (function () {
  5804. function BoundingInfo(minimum, maximum) {
  5805. this.minimum = minimum;
  5806. this.maximum = maximum;
  5807. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5808. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5809. }
  5810. // Methods
  5811. BoundingInfo.prototype._update = function (world) {
  5812. this.boundingBox._update(world);
  5813. this.boundingSphere._update(world);
  5814. };
  5815. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5816. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5817. return false;
  5818. return this.boundingBox.isInFrustum(frustumPlanes);
  5819. };
  5820. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5821. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5822. };
  5823. BoundingInfo.prototype._checkCollision = function (collider) {
  5824. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5825. };
  5826. BoundingInfo.prototype.intersectsPoint = function (point) {
  5827. if (!this.boundingSphere.centerWorld) {
  5828. return false;
  5829. }
  5830. if (!this.boundingSphere.intersectsPoint(point)) {
  5831. return false;
  5832. }
  5833. if (!this.boundingBox.intersectsPoint(point)) {
  5834. return false;
  5835. }
  5836. return true;
  5837. };
  5838. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5839. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5840. return false;
  5841. }
  5842. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5843. return false;
  5844. }
  5845. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5846. return false;
  5847. }
  5848. if (!precise) {
  5849. return true;
  5850. }
  5851. var box0 = this.boundingBox;
  5852. var box1 = boundingInfo.boundingBox;
  5853. if (!axisOverlap(box0.directions[0], box0, box1))
  5854. return false;
  5855. if (!axisOverlap(box0.directions[1], box0, box1))
  5856. return false;
  5857. if (!axisOverlap(box0.directions[2], box0, box1))
  5858. return false;
  5859. if (!axisOverlap(box1.directions[0], box0, box1))
  5860. return false;
  5861. if (!axisOverlap(box1.directions[1], box0, box1))
  5862. return false;
  5863. if (!axisOverlap(box1.directions[2], box0, box1))
  5864. return false;
  5865. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5866. return false;
  5867. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5868. return false;
  5869. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5870. return false;
  5871. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5872. return false;
  5873. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5874. return false;
  5875. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5876. return false;
  5877. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5878. return false;
  5879. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5880. return false;
  5881. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5882. return false;
  5883. return true;
  5884. };
  5885. return BoundingInfo;
  5886. })();
  5887. BABYLON.BoundingInfo = BoundingInfo;
  5888. })(BABYLON || (BABYLON = {}));
  5889. //# sourceMappingURL=babylon.boundingInfo.js.map
  5890. var BABYLON;
  5891. (function (BABYLON) {
  5892. var Light = (function (_super) {
  5893. __extends(Light, _super);
  5894. function Light(name, scene) {
  5895. _super.call(this, name, scene);
  5896. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5897. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5898. this.intensity = 1.0;
  5899. this.range = Number.MAX_VALUE;
  5900. this.includedOnlyMeshes = new Array();
  5901. this.excludedMeshes = new Array();
  5902. this._excludedMeshesIds = new Array();
  5903. this._includedOnlyMeshesIds = new Array();
  5904. scene.addLight(this);
  5905. }
  5906. Light.prototype.getShadowGenerator = function () {
  5907. return this._shadowGenerator;
  5908. };
  5909. Light.prototype.getAbsolutePosition = function () {
  5910. return BABYLON.Vector3.Zero();
  5911. };
  5912. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5913. };
  5914. Light.prototype._getWorldMatrix = function () {
  5915. return BABYLON.Matrix.Identity();
  5916. };
  5917. Light.prototype.canAffectMesh = function (mesh) {
  5918. if (!mesh) {
  5919. return true;
  5920. }
  5921. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5922. return false;
  5923. }
  5924. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5925. return false;
  5926. }
  5927. return true;
  5928. };
  5929. Light.prototype.getWorldMatrix = function () {
  5930. this._currentRenderId = this.getScene().getRenderId();
  5931. var worldMatrix = this._getWorldMatrix();
  5932. if (this.parent && this.parent.getWorldMatrix) {
  5933. if (!this._parentedWorldMatrix) {
  5934. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5935. }
  5936. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5937. return this._parentedWorldMatrix;
  5938. }
  5939. return worldMatrix;
  5940. };
  5941. Light.prototype.dispose = function () {
  5942. if (this._shadowGenerator) {
  5943. this._shadowGenerator.dispose();
  5944. this._shadowGenerator = null;
  5945. }
  5946. // Remove from scene
  5947. this.getScene().removeLight(this);
  5948. };
  5949. return Light;
  5950. })(BABYLON.Node);
  5951. BABYLON.Light = Light;
  5952. })(BABYLON || (BABYLON = {}));
  5953. //# sourceMappingURL=babylon.light.js.map
  5954. var BABYLON;
  5955. (function (BABYLON) {
  5956. var PointLight = (function (_super) {
  5957. __extends(PointLight, _super);
  5958. function PointLight(name, position, scene) {
  5959. _super.call(this, name, scene);
  5960. this.position = position;
  5961. }
  5962. PointLight.prototype.getAbsolutePosition = function () {
  5963. return this._transformedPosition ? this._transformedPosition : this.position;
  5964. };
  5965. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5966. if (this.parent && this.parent.getWorldMatrix) {
  5967. if (!this._transformedPosition) {
  5968. this._transformedPosition = BABYLON.Vector3.Zero();
  5969. }
  5970. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5971. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5972. return;
  5973. }
  5974. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5975. };
  5976. PointLight.prototype.getShadowGenerator = function () {
  5977. return null;
  5978. };
  5979. PointLight.prototype._getWorldMatrix = function () {
  5980. if (!this._worldMatrix) {
  5981. this._worldMatrix = BABYLON.Matrix.Identity();
  5982. }
  5983. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5984. return this._worldMatrix;
  5985. };
  5986. return PointLight;
  5987. })(BABYLON.Light);
  5988. BABYLON.PointLight = PointLight;
  5989. })(BABYLON || (BABYLON = {}));
  5990. //# sourceMappingURL=babylon.pointLight.js.map
  5991. var BABYLON;
  5992. (function (BABYLON) {
  5993. var SpotLight = (function (_super) {
  5994. __extends(SpotLight, _super);
  5995. function SpotLight(name, position, direction, angle, exponent, scene) {
  5996. _super.call(this, name, scene);
  5997. this.position = position;
  5998. this.direction = direction;
  5999. this.angle = angle;
  6000. this.exponent = exponent;
  6001. }
  6002. SpotLight.prototype.getAbsolutePosition = function () {
  6003. return this.transformedPosition ? this.transformedPosition : this.position;
  6004. };
  6005. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6006. var activeCamera = this.getScene().activeCamera;
  6007. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  6008. };
  6009. SpotLight.prototype.supportsVSM = function () {
  6010. return true;
  6011. };
  6012. SpotLight.prototype.needRefreshPerFrame = function () {
  6013. return false;
  6014. };
  6015. SpotLight.prototype.setDirectionToTarget = function (target) {
  6016. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6017. return this.direction;
  6018. };
  6019. SpotLight.prototype.computeTransformedPosition = function () {
  6020. if (this.parent && this.parent.getWorldMatrix) {
  6021. if (!this.transformedPosition) {
  6022. this.transformedPosition = BABYLON.Vector3.Zero();
  6023. }
  6024. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6025. return true;
  6026. }
  6027. return false;
  6028. };
  6029. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  6030. var normalizeDirection;
  6031. if (this.parent && this.parent.getWorldMatrix) {
  6032. if (!this._transformedDirection) {
  6033. this._transformedDirection = BABYLON.Vector3.Zero();
  6034. }
  6035. this.computeTransformedPosition();
  6036. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6037. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  6038. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  6039. }
  6040. else {
  6041. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  6042. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6043. }
  6044. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  6045. };
  6046. SpotLight.prototype._getWorldMatrix = function () {
  6047. if (!this._worldMatrix) {
  6048. this._worldMatrix = BABYLON.Matrix.Identity();
  6049. }
  6050. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6051. return this._worldMatrix;
  6052. };
  6053. return SpotLight;
  6054. })(BABYLON.Light);
  6055. BABYLON.SpotLight = SpotLight;
  6056. })(BABYLON || (BABYLON = {}));
  6057. //# sourceMappingURL=babylon.spotLight.js.map
  6058. var BABYLON;
  6059. (function (BABYLON) {
  6060. var DirectionalLight = (function (_super) {
  6061. __extends(DirectionalLight, _super);
  6062. function DirectionalLight(name, direction, scene) {
  6063. _super.call(this, name, scene);
  6064. this.direction = direction;
  6065. this.shadowOrthoScale = 0.5;
  6066. this.position = direction.scale(-1);
  6067. }
  6068. DirectionalLight.prototype.getAbsolutePosition = function () {
  6069. return this.transformedPosition ? this.transformedPosition : this.position;
  6070. };
  6071. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  6072. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6073. return this.direction;
  6074. };
  6075. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6076. var orthoLeft = Number.MAX_VALUE;
  6077. var orthoRight = Number.MIN_VALUE;
  6078. var orthoTop = Number.MIN_VALUE;
  6079. var orthoBottom = Number.MAX_VALUE;
  6080. var tempVector3 = BABYLON.Vector3.Zero();
  6081. var activeCamera = this.getScene().activeCamera;
  6082. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  6083. var mesh = renderList[meshIndex];
  6084. if (!mesh) {
  6085. continue;
  6086. }
  6087. var boundingInfo = mesh.getBoundingInfo();
  6088. if (!boundingInfo) {
  6089. continue;
  6090. }
  6091. var boundingBox = boundingInfo.boundingBox;
  6092. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  6093. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  6094. if (tempVector3.x < orthoLeft)
  6095. orthoLeft = tempVector3.x;
  6096. if (tempVector3.y < orthoBottom)
  6097. orthoBottom = tempVector3.y;
  6098. if (tempVector3.x > orthoRight)
  6099. orthoRight = tempVector3.x;
  6100. if (tempVector3.y > orthoTop)
  6101. orthoTop = tempVector3.y;
  6102. }
  6103. }
  6104. var xOffset = orthoRight - orthoLeft;
  6105. var yOffset = orthoTop - orthoBottom;
  6106. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  6107. };
  6108. DirectionalLight.prototype.supportsVSM = function () {
  6109. return true;
  6110. };
  6111. DirectionalLight.prototype.needRefreshPerFrame = function () {
  6112. return true;
  6113. };
  6114. DirectionalLight.prototype.computeTransformedPosition = function () {
  6115. if (this.parent && this.parent.getWorldMatrix) {
  6116. if (!this.transformedPosition) {
  6117. this.transformedPosition = BABYLON.Vector3.Zero();
  6118. }
  6119. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6120. return true;
  6121. }
  6122. return false;
  6123. };
  6124. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  6125. if (this.parent && this.parent.getWorldMatrix) {
  6126. if (!this._transformedDirection) {
  6127. this._transformedDirection = BABYLON.Vector3.Zero();
  6128. }
  6129. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6130. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  6131. return;
  6132. }
  6133. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  6134. };
  6135. DirectionalLight.prototype._getWorldMatrix = function () {
  6136. if (!this._worldMatrix) {
  6137. this._worldMatrix = BABYLON.Matrix.Identity();
  6138. }
  6139. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6140. return this._worldMatrix;
  6141. };
  6142. return DirectionalLight;
  6143. })(BABYLON.Light);
  6144. BABYLON.DirectionalLight = DirectionalLight;
  6145. })(BABYLON || (BABYLON = {}));
  6146. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  6147. (function (BABYLON) {
  6148. var ShadowGenerator = (function () {
  6149. function ShadowGenerator(mapSize, light) {
  6150. var _this = this;
  6151. // Members
  6152. this._filter = ShadowGenerator.FILTER_NONE;
  6153. this.blurScale = 2;
  6154. this._blurBoxOffset = 0;
  6155. this._bias = 0.00005;
  6156. this._darkness = 0;
  6157. this._transparencyShadow = false;
  6158. this._viewMatrix = BABYLON.Matrix.Zero();
  6159. this._projectionMatrix = BABYLON.Matrix.Zero();
  6160. this._transformMatrix = BABYLON.Matrix.Zero();
  6161. this._worldViewProjection = BABYLON.Matrix.Zero();
  6162. this._light = light;
  6163. this._scene = light.getScene();
  6164. this._mapSize = mapSize;
  6165. light._shadowGenerator = this;
  6166. // Render target
  6167. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  6168. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6169. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6170. this._shadowMap.anisotropicFilteringLevel = 1;
  6171. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6172. this._shadowMap.renderParticles = false;
  6173. this._shadowMap.onAfterUnbind = function () {
  6174. if (!_this.useBlurVarianceShadowMap) {
  6175. return;
  6176. }
  6177. if (!_this._shadowMap2) {
  6178. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  6179. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6180. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6181. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  6182. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  6183. _this._downSamplePostprocess.onApply = function (effect) {
  6184. effect.setTexture("textureSampler", _this._shadowMap);
  6185. };
  6186. _this.blurBoxOffset = 1;
  6187. }
  6188. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  6189. };
  6190. // Custom render function
  6191. var renderSubMesh = function (subMesh) {
  6192. var mesh = subMesh.getRenderingMesh();
  6193. var scene = _this._scene;
  6194. var engine = scene.getEngine();
  6195. // Culling
  6196. engine.setState(subMesh.getMaterial().backFaceCulling);
  6197. // Managing instances
  6198. var batch = mesh._getInstancesRenderList(subMesh._id);
  6199. if (batch.mustReturn) {
  6200. return;
  6201. }
  6202. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  6203. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  6204. engine.enableEffect(_this._effect);
  6205. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  6206. var material = subMesh.getMaterial();
  6207. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  6208. // Alpha test
  6209. if (material && material.needAlphaTesting()) {
  6210. var alphaTexture = material.getAlphaTestTexture();
  6211. _this._effect.setTexture("diffuseSampler", alphaTexture);
  6212. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  6213. }
  6214. // Bones
  6215. if (mesh.useBones) {
  6216. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  6217. }
  6218. // Draw
  6219. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  6220. }
  6221. else {
  6222. // Need to reset refresh rate of the shadowMap
  6223. _this._shadowMap.resetRefreshCounter();
  6224. }
  6225. };
  6226. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  6227. var index;
  6228. for (index = 0; index < opaqueSubMeshes.length; index++) {
  6229. renderSubMesh(opaqueSubMeshes.data[index]);
  6230. }
  6231. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  6232. renderSubMesh(alphaTestSubMeshes.data[index]);
  6233. }
  6234. if (_this._transparencyShadow) {
  6235. for (index = 0; index < transparentSubMeshes.length; index++) {
  6236. renderSubMesh(transparentSubMeshes.data[index]);
  6237. }
  6238. }
  6239. };
  6240. this._shadowMap.onClear = function (engine) {
  6241. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  6242. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  6243. }
  6244. else {
  6245. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  6246. }
  6247. };
  6248. }
  6249. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  6250. // Static
  6251. get: function () {
  6252. return ShadowGenerator._FILTER_NONE;
  6253. },
  6254. enumerable: true,
  6255. configurable: true
  6256. });
  6257. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  6258. get: function () {
  6259. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  6260. },
  6261. enumerable: true,
  6262. configurable: true
  6263. });
  6264. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  6265. get: function () {
  6266. return ShadowGenerator._FILTER_POISSONSAMPLING;
  6267. },
  6268. enumerable: true,
  6269. configurable: true
  6270. });
  6271. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  6272. get: function () {
  6273. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  6274. },
  6275. enumerable: true,
  6276. configurable: true
  6277. });
  6278. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  6279. get: function () {
  6280. return this._bias;
  6281. },
  6282. set: function (bias) {
  6283. this._bias = bias;
  6284. },
  6285. enumerable: true,
  6286. configurable: true
  6287. });
  6288. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  6289. get: function () {
  6290. return this._blurBoxOffset;
  6291. },
  6292. set: function (value) {
  6293. var _this = this;
  6294. if (this._blurBoxOffset === value) {
  6295. return;
  6296. }
  6297. this._blurBoxOffset = value;
  6298. if (this._boxBlurPostprocess) {
  6299. this._boxBlurPostprocess.dispose();
  6300. }
  6301. 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);
  6302. this._boxBlurPostprocess.onApply = function (effect) {
  6303. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  6304. };
  6305. },
  6306. enumerable: true,
  6307. configurable: true
  6308. });
  6309. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  6310. get: function () {
  6311. return this._filter;
  6312. },
  6313. set: function (value) {
  6314. if (this._filter === value) {
  6315. return;
  6316. }
  6317. this._filter = value;
  6318. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6319. this._shadowMap.anisotropicFilteringLevel = 16;
  6320. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  6321. }
  6322. else {
  6323. this._shadowMap.anisotropicFilteringLevel = 1;
  6324. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6325. }
  6326. },
  6327. enumerable: true,
  6328. configurable: true
  6329. });
  6330. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  6331. get: function () {
  6332. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  6333. },
  6334. set: function (value) {
  6335. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6336. },
  6337. enumerable: true,
  6338. configurable: true
  6339. });
  6340. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  6341. get: function () {
  6342. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  6343. },
  6344. set: function (value) {
  6345. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  6346. },
  6347. enumerable: true,
  6348. configurable: true
  6349. });
  6350. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  6351. get: function () {
  6352. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  6353. },
  6354. set: function (value) {
  6355. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6356. },
  6357. enumerable: true,
  6358. configurable: true
  6359. });
  6360. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  6361. var defines = [];
  6362. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6363. defines.push("#define VSM");
  6364. }
  6365. var attribs = [BABYLON.VertexBuffer.PositionKind];
  6366. var mesh = subMesh.getMesh();
  6367. var material = subMesh.getMaterial();
  6368. // Alpha test
  6369. if (material && material.needAlphaTesting()) {
  6370. defines.push("#define ALPHATEST");
  6371. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  6372. attribs.push(BABYLON.VertexBuffer.UVKind);
  6373. defines.push("#define UV1");
  6374. }
  6375. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  6376. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  6377. defines.push("#define UV2");
  6378. }
  6379. }
  6380. // Bones
  6381. if (mesh.useBones) {
  6382. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  6383. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  6384. defines.push("#define BONES");
  6385. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  6386. }
  6387. // Instances
  6388. if (useInstances) {
  6389. defines.push("#define INSTANCES");
  6390. attribs.push("world0");
  6391. attribs.push("world1");
  6392. attribs.push("world2");
  6393. attribs.push("world3");
  6394. }
  6395. // Get correct effect
  6396. var join = defines.join("\n");
  6397. if (this._cachedDefines !== join) {
  6398. this._cachedDefines = join;
  6399. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  6400. }
  6401. return this._effect.isReady();
  6402. };
  6403. ShadowGenerator.prototype.getShadowMap = function () {
  6404. return this._shadowMap;
  6405. };
  6406. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  6407. if (this._shadowMap2) {
  6408. return this._shadowMap2;
  6409. }
  6410. return this._shadowMap;
  6411. };
  6412. ShadowGenerator.prototype.getLight = function () {
  6413. return this._light;
  6414. };
  6415. // Methods
  6416. ShadowGenerator.prototype.getTransformMatrix = function () {
  6417. var scene = this._scene;
  6418. if (this._currentRenderID === scene.getRenderId()) {
  6419. return this._transformMatrix;
  6420. }
  6421. this._currentRenderID = scene.getRenderId();
  6422. var lightPosition = this._light.position;
  6423. var lightDirection = this._light.direction;
  6424. if (this._light.computeTransformedPosition()) {
  6425. lightPosition = this._light.transformedPosition;
  6426. }
  6427. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6428. this._cachedPosition = lightPosition.clone();
  6429. this._cachedDirection = lightDirection.clone();
  6430. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6431. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  6432. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6433. }
  6434. return this._transformMatrix;
  6435. };
  6436. ShadowGenerator.prototype.getDarkness = function () {
  6437. return this._darkness;
  6438. };
  6439. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6440. if (darkness >= 1.0)
  6441. this._darkness = 1.0;
  6442. else if (darkness <= 0.0)
  6443. this._darkness = 0.0;
  6444. else
  6445. this._darkness = darkness;
  6446. };
  6447. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6448. this._transparencyShadow = hasShadow;
  6449. };
  6450. ShadowGenerator.prototype._packHalf = function (depth) {
  6451. var scale = depth * 255.0;
  6452. var fract = scale - Math.floor(scale);
  6453. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  6454. };
  6455. ShadowGenerator.prototype.dispose = function () {
  6456. this._shadowMap.dispose();
  6457. if (this._shadowMap2) {
  6458. this._shadowMap2.dispose();
  6459. }
  6460. if (this._downSamplePostprocess) {
  6461. this._downSamplePostprocess.dispose();
  6462. }
  6463. if (this._boxBlurPostprocess) {
  6464. this._boxBlurPostprocess.dispose();
  6465. }
  6466. };
  6467. ShadowGenerator._FILTER_NONE = 0;
  6468. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6469. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6470. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  6471. return ShadowGenerator;
  6472. })();
  6473. BABYLON.ShadowGenerator = ShadowGenerator;
  6474. })(BABYLON || (BABYLON = {}));
  6475. //# sourceMappingURL=babylon.shadowGenerator.js.map
  6476. var BABYLON;
  6477. (function (BABYLON) {
  6478. var HemisphericLight = (function (_super) {
  6479. __extends(HemisphericLight, _super);
  6480. function HemisphericLight(name, direction, scene) {
  6481. _super.call(this, name, scene);
  6482. this.direction = direction;
  6483. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6484. }
  6485. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6486. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6487. return this.direction;
  6488. };
  6489. HemisphericLight.prototype.getShadowGenerator = function () {
  6490. return null;
  6491. };
  6492. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6493. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6494. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6495. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6496. };
  6497. HemisphericLight.prototype._getWorldMatrix = function () {
  6498. if (!this._worldMatrix) {
  6499. this._worldMatrix = BABYLON.Matrix.Identity();
  6500. }
  6501. return this._worldMatrix;
  6502. };
  6503. return HemisphericLight;
  6504. })(BABYLON.Light);
  6505. BABYLON.HemisphericLight = HemisphericLight;
  6506. })(BABYLON || (BABYLON = {}));
  6507. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6508. (function (BABYLON) {
  6509. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6510. if (boxMin.x > sphereCenter.x + sphereRadius)
  6511. return false;
  6512. if (sphereCenter.x - sphereRadius > boxMax.x)
  6513. return false;
  6514. if (boxMin.y > sphereCenter.y + sphereRadius)
  6515. return false;
  6516. if (sphereCenter.y - sphereRadius > boxMax.y)
  6517. return false;
  6518. if (boxMin.z > sphereCenter.z + sphereRadius)
  6519. return false;
  6520. if (sphereCenter.z - sphereRadius > boxMax.z)
  6521. return false;
  6522. return true;
  6523. };
  6524. var getLowestRoot = function (a, b, c, maxR) {
  6525. var determinant = b * b - 4.0 * a * c;
  6526. var result = { root: 0, found: false };
  6527. if (determinant < 0)
  6528. return result;
  6529. var sqrtD = Math.sqrt(determinant);
  6530. var r1 = (-b - sqrtD) / (2.0 * a);
  6531. var r2 = (-b + sqrtD) / (2.0 * a);
  6532. if (r1 > r2) {
  6533. var temp = r2;
  6534. r2 = r1;
  6535. r1 = temp;
  6536. }
  6537. if (r1 > 0 && r1 < maxR) {
  6538. result.root = r1;
  6539. result.found = true;
  6540. return result;
  6541. }
  6542. if (r2 > 0 && r2 < maxR) {
  6543. result.root = r2;
  6544. result.found = true;
  6545. return result;
  6546. }
  6547. return result;
  6548. };
  6549. var Collider = (function () {
  6550. function Collider() {
  6551. this.radius = new BABYLON.Vector3(1, 1, 1);
  6552. this.retry = 0;
  6553. this.basePointWorld = BABYLON.Vector3.Zero();
  6554. this.velocityWorld = BABYLON.Vector3.Zero();
  6555. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6556. this._collisionPoint = BABYLON.Vector3.Zero();
  6557. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6558. this._tempVector = BABYLON.Vector3.Zero();
  6559. this._tempVector2 = BABYLON.Vector3.Zero();
  6560. this._tempVector3 = BABYLON.Vector3.Zero();
  6561. this._tempVector4 = BABYLON.Vector3.Zero();
  6562. this._edge = BABYLON.Vector3.Zero();
  6563. this._baseToVertex = BABYLON.Vector3.Zero();
  6564. this._destinationPoint = BABYLON.Vector3.Zero();
  6565. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6566. this._displacementVector = BABYLON.Vector3.Zero();
  6567. }
  6568. // Methods
  6569. Collider.prototype._initialize = function (source, dir, e) {
  6570. this.velocity = dir;
  6571. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6572. this.basePoint = source;
  6573. source.multiplyToRef(this.radius, this.basePointWorld);
  6574. dir.multiplyToRef(this.radius, this.velocityWorld);
  6575. this.velocityWorldLength = this.velocityWorld.length();
  6576. this.epsilon = e;
  6577. this.collisionFound = false;
  6578. };
  6579. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6580. pa.subtractToRef(point, this._tempVector);
  6581. pb.subtractToRef(point, this._tempVector2);
  6582. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6583. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6584. if (d < 0)
  6585. return false;
  6586. pc.subtractToRef(point, this._tempVector3);
  6587. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6588. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6589. if (d < 0)
  6590. return false;
  6591. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6592. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6593. return d >= 0;
  6594. };
  6595. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6596. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6597. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6598. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6599. return false;
  6600. }
  6601. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6602. return false;
  6603. return true;
  6604. };
  6605. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6606. var t0;
  6607. var embeddedInPlane = false;
  6608. if (!subMesh._trianglePlanes) {
  6609. subMesh._trianglePlanes = [];
  6610. }
  6611. if (!subMesh._trianglePlanes[faceIndex]) {
  6612. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6613. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6614. }
  6615. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6616. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6617. return;
  6618. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6619. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6620. if (normalDotVelocity == 0) {
  6621. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6622. return;
  6623. embeddedInPlane = true;
  6624. t0 = 0;
  6625. }
  6626. else {
  6627. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6628. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6629. if (t0 > t1) {
  6630. var temp = t1;
  6631. t1 = t0;
  6632. t0 = temp;
  6633. }
  6634. if (t0 > 1.0 || t1 < 0.0)
  6635. return;
  6636. if (t0 < 0)
  6637. t0 = 0;
  6638. if (t0 > 1.0)
  6639. t0 = 1.0;
  6640. }
  6641. this._collisionPoint.copyFromFloats(0, 0, 0);
  6642. var found = false;
  6643. var t = 1.0;
  6644. if (!embeddedInPlane) {
  6645. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6646. this.velocity.scaleToRef(t0, this._tempVector);
  6647. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6648. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6649. found = true;
  6650. t = t0;
  6651. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6652. }
  6653. }
  6654. if (!found) {
  6655. var velocitySquaredLength = this.velocity.lengthSquared();
  6656. var a = velocitySquaredLength;
  6657. this.basePoint.subtractToRef(p1, this._tempVector);
  6658. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6659. var c = this._tempVector.lengthSquared() - 1.0;
  6660. var lowestRoot = getLowestRoot(a, b, c, t);
  6661. if (lowestRoot.found) {
  6662. t = lowestRoot.root;
  6663. found = true;
  6664. this._collisionPoint.copyFrom(p1);
  6665. }
  6666. this.basePoint.subtractToRef(p2, this._tempVector);
  6667. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6668. c = this._tempVector.lengthSquared() - 1.0;
  6669. lowestRoot = getLowestRoot(a, b, c, t);
  6670. if (lowestRoot.found) {
  6671. t = lowestRoot.root;
  6672. found = true;
  6673. this._collisionPoint.copyFrom(p2);
  6674. }
  6675. this.basePoint.subtractToRef(p3, this._tempVector);
  6676. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6677. c = this._tempVector.lengthSquared() - 1.0;
  6678. lowestRoot = getLowestRoot(a, b, c, t);
  6679. if (lowestRoot.found) {
  6680. t = lowestRoot.root;
  6681. found = true;
  6682. this._collisionPoint.copyFrom(p3);
  6683. }
  6684. p2.subtractToRef(p1, this._edge);
  6685. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6686. var edgeSquaredLength = this._edge.lengthSquared();
  6687. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6688. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6689. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6690. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6691. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6692. lowestRoot = getLowestRoot(a, b, c, t);
  6693. if (lowestRoot.found) {
  6694. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6695. if (f >= 0.0 && f <= 1.0) {
  6696. t = lowestRoot.root;
  6697. found = true;
  6698. this._edge.scaleInPlace(f);
  6699. p1.addToRef(this._edge, this._collisionPoint);
  6700. }
  6701. }
  6702. p3.subtractToRef(p2, this._edge);
  6703. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6704. edgeSquaredLength = this._edge.lengthSquared();
  6705. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6706. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6707. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6708. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6709. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6710. lowestRoot = getLowestRoot(a, b, c, t);
  6711. if (lowestRoot.found) {
  6712. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6713. if (f >= 0.0 && f <= 1.0) {
  6714. t = lowestRoot.root;
  6715. found = true;
  6716. this._edge.scaleInPlace(f);
  6717. p2.addToRef(this._edge, this._collisionPoint);
  6718. }
  6719. }
  6720. p1.subtractToRef(p3, this._edge);
  6721. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6722. edgeSquaredLength = this._edge.lengthSquared();
  6723. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6724. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6725. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6726. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6727. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6728. lowestRoot = getLowestRoot(a, b, c, t);
  6729. if (lowestRoot.found) {
  6730. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6731. if (f >= 0.0 && f <= 1.0) {
  6732. t = lowestRoot.root;
  6733. found = true;
  6734. this._edge.scaleInPlace(f);
  6735. p3.addToRef(this._edge, this._collisionPoint);
  6736. }
  6737. }
  6738. }
  6739. if (found) {
  6740. var distToCollision = t * this.velocity.length();
  6741. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6742. if (!this.intersectionPoint) {
  6743. this.intersectionPoint = this._collisionPoint.clone();
  6744. }
  6745. else {
  6746. this.intersectionPoint.copyFrom(this._collisionPoint);
  6747. }
  6748. this.nearestDistance = distToCollision;
  6749. this.collisionFound = true;
  6750. this.collidedMesh = subMesh.getMesh();
  6751. }
  6752. }
  6753. };
  6754. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6755. for (var i = indexStart; i < indexEnd; i += 3) {
  6756. var p1 = pts[indices[i] - decal];
  6757. var p2 = pts[indices[i + 1] - decal];
  6758. var p3 = pts[indices[i + 2] - decal];
  6759. this._testTriangle(i, subMesh, p3, p2, p1);
  6760. }
  6761. };
  6762. Collider.prototype._getResponse = function (pos, vel) {
  6763. pos.addToRef(vel, this._destinationPoint);
  6764. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6765. this.basePoint.addToRef(vel, pos);
  6766. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6767. this._slidePlaneNormal.normalize();
  6768. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6769. pos.addInPlace(this._displacementVector);
  6770. this.intersectionPoint.addInPlace(this._displacementVector);
  6771. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6772. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6773. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6774. };
  6775. return Collider;
  6776. })();
  6777. BABYLON.Collider = Collider;
  6778. })(BABYLON || (BABYLON = {}));
  6779. //# sourceMappingURL=babylon.collider.js.map
  6780. var BABYLON;
  6781. (function (BABYLON) {
  6782. var Camera = (function (_super) {
  6783. __extends(Camera, _super);
  6784. function Camera(name, position, scene) {
  6785. _super.call(this, name, scene);
  6786. this.position = position;
  6787. // Members
  6788. this.upVector = BABYLON.Vector3.Up();
  6789. this.orthoLeft = null;
  6790. this.orthoRight = null;
  6791. this.orthoBottom = null;
  6792. this.orthoTop = null;
  6793. this.fov = 0.8;
  6794. this.minZ = 1.0;
  6795. this.maxZ = 10000.0;
  6796. this.inertia = 0.9;
  6797. this.mode = Camera.PERSPECTIVE_CAMERA;
  6798. this.isIntermediate = false;
  6799. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6800. this.subCameras = [];
  6801. this.layerMask = 0xFFFFFFFF;
  6802. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6803. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6804. this._projectionMatrix = new BABYLON.Matrix();
  6805. this._postProcesses = new Array();
  6806. this._postProcessesTakenIndices = [];
  6807. this._activeMeshes = new BABYLON.SmartArray(256);
  6808. scene.addCamera(this);
  6809. if (!scene.activeCamera) {
  6810. scene.activeCamera = this;
  6811. }
  6812. }
  6813. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6814. get: function () {
  6815. return Camera._PERSPECTIVE_CAMERA;
  6816. },
  6817. enumerable: true,
  6818. configurable: true
  6819. });
  6820. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6821. get: function () {
  6822. return Camera._ORTHOGRAPHIC_CAMERA;
  6823. },
  6824. enumerable: true,
  6825. configurable: true
  6826. });
  6827. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6828. get: function () {
  6829. return Camera._FOVMODE_VERTICAL_FIXED;
  6830. },
  6831. enumerable: true,
  6832. configurable: true
  6833. });
  6834. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6835. get: function () {
  6836. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6837. },
  6838. enumerable: true,
  6839. configurable: true
  6840. });
  6841. Camera.prototype.getActiveMeshes = function () {
  6842. return this._activeMeshes;
  6843. };
  6844. Camera.prototype.isActiveMesh = function (mesh) {
  6845. return (this._activeMeshes.indexOf(mesh) !== -1);
  6846. };
  6847. //Cache
  6848. Camera.prototype._initCache = function () {
  6849. _super.prototype._initCache.call(this);
  6850. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6851. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6852. this._cache.mode = undefined;
  6853. this._cache.minZ = undefined;
  6854. this._cache.maxZ = undefined;
  6855. this._cache.fov = undefined;
  6856. this._cache.aspectRatio = undefined;
  6857. this._cache.orthoLeft = undefined;
  6858. this._cache.orthoRight = undefined;
  6859. this._cache.orthoBottom = undefined;
  6860. this._cache.orthoTop = undefined;
  6861. this._cache.renderWidth = undefined;
  6862. this._cache.renderHeight = undefined;
  6863. };
  6864. Camera.prototype._updateCache = function (ignoreParentClass) {
  6865. if (!ignoreParentClass) {
  6866. _super.prototype._updateCache.call(this);
  6867. }
  6868. var engine = this.getEngine();
  6869. this._cache.position.copyFrom(this.position);
  6870. this._cache.upVector.copyFrom(this.upVector);
  6871. this._cache.mode = this.mode;
  6872. this._cache.minZ = this.minZ;
  6873. this._cache.maxZ = this.maxZ;
  6874. this._cache.fov = this.fov;
  6875. this._cache.aspectRatio = engine.getAspectRatio(this);
  6876. this._cache.orthoLeft = this.orthoLeft;
  6877. this._cache.orthoRight = this.orthoRight;
  6878. this._cache.orthoBottom = this.orthoBottom;
  6879. this._cache.orthoTop = this.orthoTop;
  6880. this._cache.renderWidth = engine.getRenderWidth();
  6881. this._cache.renderHeight = engine.getRenderHeight();
  6882. };
  6883. Camera.prototype._updateFromScene = function () {
  6884. this.updateCache();
  6885. this._update();
  6886. };
  6887. // Synchronized
  6888. Camera.prototype._isSynchronized = function () {
  6889. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6890. };
  6891. Camera.prototype._isSynchronizedViewMatrix = function () {
  6892. if (!_super.prototype._isSynchronized.call(this))
  6893. return false;
  6894. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6895. };
  6896. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6897. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6898. if (!check) {
  6899. return false;
  6900. }
  6901. var engine = this.getEngine();
  6902. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6903. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6904. }
  6905. else {
  6906. 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();
  6907. }
  6908. return check;
  6909. };
  6910. // Controls
  6911. Camera.prototype.attachControl = function (element) {
  6912. };
  6913. Camera.prototype.detachControl = function (element) {
  6914. };
  6915. Camera.prototype._update = function () {
  6916. };
  6917. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6918. if (insertAt === void 0) { insertAt = null; }
  6919. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6920. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6921. return 0;
  6922. }
  6923. if (insertAt == null || insertAt < 0) {
  6924. this._postProcesses.push(postProcess);
  6925. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6926. return this._postProcesses.length - 1;
  6927. }
  6928. var add = 0;
  6929. if (this._postProcesses[insertAt]) {
  6930. var start = this._postProcesses.length - 1;
  6931. for (var i = start; i >= insertAt + 1; --i) {
  6932. this._postProcesses[i + 1] = this._postProcesses[i];
  6933. }
  6934. add = 1;
  6935. }
  6936. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6937. if (this._postProcessesTakenIndices[i] < insertAt) {
  6938. continue;
  6939. }
  6940. start = this._postProcessesTakenIndices.length - 1;
  6941. for (var j = start; j >= i; --j) {
  6942. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6943. }
  6944. this._postProcessesTakenIndices[i] = insertAt;
  6945. break;
  6946. }
  6947. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6948. this._postProcessesTakenIndices.push(insertAt);
  6949. }
  6950. var result = insertAt + add;
  6951. this._postProcesses[result] = postProcess;
  6952. return result;
  6953. };
  6954. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6955. if (atIndices === void 0) { atIndices = null; }
  6956. var result = [];
  6957. if (!atIndices) {
  6958. var length = this._postProcesses.length;
  6959. for (var i = 0; i < length; i++) {
  6960. if (this._postProcesses[i] !== postProcess) {
  6961. continue;
  6962. }
  6963. delete this._postProcesses[i];
  6964. var index = this._postProcessesTakenIndices.indexOf(i);
  6965. this._postProcessesTakenIndices.splice(index, 1);
  6966. }
  6967. }
  6968. else {
  6969. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6970. for (i = 0; i < atIndices.length; i++) {
  6971. var foundPostProcess = this._postProcesses[atIndices[i]];
  6972. if (foundPostProcess !== postProcess) {
  6973. result.push(i);
  6974. continue;
  6975. }
  6976. delete this._postProcesses[atIndices[i]];
  6977. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6978. this._postProcessesTakenIndices.splice(index, 1);
  6979. }
  6980. }
  6981. return result;
  6982. };
  6983. Camera.prototype.getWorldMatrix = function () {
  6984. if (!this._worldMatrix) {
  6985. this._worldMatrix = BABYLON.Matrix.Identity();
  6986. }
  6987. var viewMatrix = this.getViewMatrix();
  6988. viewMatrix.invertToRef(this._worldMatrix);
  6989. return this._worldMatrix;
  6990. };
  6991. Camera.prototype._getViewMatrix = function () {
  6992. return BABYLON.Matrix.Identity();
  6993. };
  6994. Camera.prototype.getViewMatrix = function () {
  6995. this._computedViewMatrix = this._computeViewMatrix();
  6996. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6997. return this._computedViewMatrix;
  6998. }
  6999. if (!this._worldMatrix) {
  7000. this._worldMatrix = BABYLON.Matrix.Identity();
  7001. }
  7002. this._computedViewMatrix.invertToRef(this._worldMatrix);
  7003. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  7004. this._computedViewMatrix.invert();
  7005. this._currentRenderId = this.getScene().getRenderId();
  7006. return this._computedViewMatrix;
  7007. };
  7008. Camera.prototype._computeViewMatrix = function (force) {
  7009. if (!force && this._isSynchronizedViewMatrix()) {
  7010. return this._computedViewMatrix;
  7011. }
  7012. this._computedViewMatrix = this._getViewMatrix();
  7013. if (!this.parent || !this.parent.getWorldMatrix) {
  7014. this._currentRenderId = this.getScene().getRenderId();
  7015. }
  7016. return this._computedViewMatrix;
  7017. };
  7018. Camera.prototype.getProjectionMatrix = function (force) {
  7019. if (!force && this._isSynchronizedProjectionMatrix()) {
  7020. return this._projectionMatrix;
  7021. }
  7022. var engine = this.getEngine();
  7023. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7024. if (this.minZ <= 0) {
  7025. this.minZ = 0.1;
  7026. }
  7027. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  7028. return this._projectionMatrix;
  7029. }
  7030. var halfWidth = engine.getRenderWidth() / 2.0;
  7031. var halfHeight = engine.getRenderHeight() / 2.0;
  7032. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  7033. return this._projectionMatrix;
  7034. };
  7035. Camera.prototype.dispose = function () {
  7036. // Remove from scene
  7037. this.getScene().removeCamera(this);
  7038. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7039. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  7040. }
  7041. };
  7042. // Statics
  7043. Camera._PERSPECTIVE_CAMERA = 0;
  7044. Camera._ORTHOGRAPHIC_CAMERA = 1;
  7045. Camera._FOVMODE_VERTICAL_FIXED = 0;
  7046. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  7047. return Camera;
  7048. })(BABYLON.Node);
  7049. BABYLON.Camera = Camera;
  7050. })(BABYLON || (BABYLON = {}));
  7051. //# sourceMappingURL=babylon.camera.js.map
  7052. var BABYLON;
  7053. (function (BABYLON) {
  7054. var TargetCamera = (function (_super) {
  7055. __extends(TargetCamera, _super);
  7056. function TargetCamera(name, position, scene) {
  7057. _super.call(this, name, position, scene);
  7058. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7059. this.cameraRotation = new BABYLON.Vector2(0, 0);
  7060. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7061. this.speed = 2.0;
  7062. this.noRotationConstraint = false;
  7063. this.lockedTarget = null;
  7064. this._currentTarget = BABYLON.Vector3.Zero();
  7065. this._viewMatrix = BABYLON.Matrix.Zero();
  7066. this._camMatrix = BABYLON.Matrix.Zero();
  7067. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  7068. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  7069. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  7070. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  7071. this._lookAtTemp = BABYLON.Matrix.Zero();
  7072. this._tempMatrix = BABYLON.Matrix.Zero();
  7073. }
  7074. TargetCamera.prototype._getLockedTargetPosition = function () {
  7075. if (!this.lockedTarget) {
  7076. return null;
  7077. }
  7078. return this.lockedTarget.position || this.lockedTarget;
  7079. };
  7080. // Cache
  7081. TargetCamera.prototype._initCache = function () {
  7082. _super.prototype._initCache.call(this);
  7083. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7084. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7085. };
  7086. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  7087. if (!ignoreParentClass) {
  7088. _super.prototype._updateCache.call(this);
  7089. }
  7090. var lockedTargetPosition = this._getLockedTargetPosition();
  7091. if (!lockedTargetPosition) {
  7092. this._cache.lockedTarget = null;
  7093. }
  7094. else {
  7095. if (!this._cache.lockedTarget) {
  7096. this._cache.lockedTarget = lockedTargetPosition.clone();
  7097. }
  7098. else {
  7099. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  7100. }
  7101. }
  7102. this._cache.rotation.copyFrom(this.rotation);
  7103. };
  7104. // Synchronized
  7105. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  7106. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  7107. return false;
  7108. }
  7109. var lockedTargetPosition = this._getLockedTargetPosition();
  7110. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  7111. };
  7112. // Methods
  7113. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  7114. var engine = this.getEngine();
  7115. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  7116. };
  7117. // Target
  7118. TargetCamera.prototype.setTarget = function (target) {
  7119. this.upVector.normalize();
  7120. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  7121. this._camMatrix.invert();
  7122. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  7123. var vDir = target.subtract(this.position);
  7124. if (vDir.x >= 0.0) {
  7125. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  7126. }
  7127. else {
  7128. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  7129. }
  7130. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  7131. if (isNaN(this.rotation.x)) {
  7132. this.rotation.x = 0;
  7133. }
  7134. if (isNaN(this.rotation.y)) {
  7135. this.rotation.y = 0;
  7136. }
  7137. if (isNaN(this.rotation.z)) {
  7138. this.rotation.z = 0;
  7139. }
  7140. };
  7141. TargetCamera.prototype.getTarget = function () {
  7142. return this._currentTarget;
  7143. };
  7144. TargetCamera.prototype._decideIfNeedsToMove = function () {
  7145. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7146. };
  7147. TargetCamera.prototype._updatePosition = function () {
  7148. this.position.addInPlace(this.cameraDirection);
  7149. };
  7150. TargetCamera.prototype._update = function () {
  7151. var needToMove = this._decideIfNeedsToMove();
  7152. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  7153. // Move
  7154. if (needToMove) {
  7155. this._updatePosition();
  7156. }
  7157. // Rotate
  7158. if (needToRotate) {
  7159. this.rotation.x += this.cameraRotation.x;
  7160. this.rotation.y += this.cameraRotation.y;
  7161. if (!this.noRotationConstraint) {
  7162. var limit = (Math.PI / 2) * 0.95;
  7163. if (this.rotation.x > limit)
  7164. this.rotation.x = limit;
  7165. if (this.rotation.x < -limit)
  7166. this.rotation.x = -limit;
  7167. }
  7168. }
  7169. // Inertia
  7170. if (needToMove) {
  7171. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  7172. this.cameraDirection.x = 0;
  7173. }
  7174. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  7175. this.cameraDirection.y = 0;
  7176. }
  7177. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  7178. this.cameraDirection.z = 0;
  7179. }
  7180. this.cameraDirection.scaleInPlace(this.inertia);
  7181. }
  7182. if (needToRotate) {
  7183. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  7184. this.cameraRotation.x = 0;
  7185. }
  7186. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  7187. this.cameraRotation.y = 0;
  7188. }
  7189. this.cameraRotation.scaleInPlace(this.inertia);
  7190. }
  7191. };
  7192. TargetCamera.prototype._getViewMatrix = function () {
  7193. if (!this.lockedTarget) {
  7194. // Compute
  7195. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  7196. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  7197. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7198. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  7199. this._lookAtTemp.invert();
  7200. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  7201. }
  7202. else {
  7203. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7204. }
  7205. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  7206. // Computing target and final matrix
  7207. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  7208. }
  7209. else {
  7210. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  7211. }
  7212. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  7213. return this._viewMatrix;
  7214. };
  7215. return TargetCamera;
  7216. })(BABYLON.Camera);
  7217. BABYLON.TargetCamera = TargetCamera;
  7218. })(BABYLON || (BABYLON = {}));
  7219. //# sourceMappingURL=babylon.targetCamera.js.map
  7220. var BABYLON;
  7221. (function (BABYLON) {
  7222. var FollowCamera = (function (_super) {
  7223. __extends(FollowCamera, _super);
  7224. function FollowCamera(name, position, scene) {
  7225. _super.call(this, name, position, scene);
  7226. this.radius = 12;
  7227. this.rotationOffset = 0;
  7228. this.heightOffset = 4;
  7229. this.cameraAcceleration = 0.05;
  7230. this.maxCameraSpeed = 20;
  7231. }
  7232. FollowCamera.prototype.getRadians = function (degrees) {
  7233. return degrees * Math.PI / 180;
  7234. };
  7235. FollowCamera.prototype.follow = function (cameraTarget) {
  7236. if (!cameraTarget)
  7237. return;
  7238. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  7239. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  7240. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  7241. var dx = targetX - this.position.x;
  7242. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  7243. var dz = (targetZ) - this.position.z;
  7244. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  7245. var vy = dy * this.cameraAcceleration;
  7246. var vz = dz * this.cameraAcceleration * 2;
  7247. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  7248. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7249. }
  7250. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  7251. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7252. }
  7253. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  7254. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7255. }
  7256. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  7257. this.setTarget(cameraTarget.position);
  7258. };
  7259. FollowCamera.prototype._update = function () {
  7260. _super.prototype._update.call(this);
  7261. this.follow(this.target);
  7262. };
  7263. return FollowCamera;
  7264. })(BABYLON.TargetCamera);
  7265. BABYLON.FollowCamera = FollowCamera;
  7266. })(BABYLON || (BABYLON = {}));
  7267. //# sourceMappingURL=babylon.followCamera.js.map
  7268. var BABYLON;
  7269. (function (BABYLON) {
  7270. var FreeCamera = (function (_super) {
  7271. __extends(FreeCamera, _super);
  7272. function FreeCamera(name, position, scene) {
  7273. _super.call(this, name, position, scene);
  7274. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7275. this.keysUp = [38];
  7276. this.keysDown = [40];
  7277. this.keysLeft = [37];
  7278. this.keysRight = [39];
  7279. this.checkCollisions = false;
  7280. this.applyGravity = false;
  7281. this.angularSensibility = 2000.0;
  7282. this._keys = [];
  7283. this._collider = new BABYLON.Collider();
  7284. this._needMoveForGravity = true;
  7285. this._oldPosition = BABYLON.Vector3.Zero();
  7286. this._diffPosition = BABYLON.Vector3.Zero();
  7287. this._newPosition = BABYLON.Vector3.Zero();
  7288. }
  7289. // Controls
  7290. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  7291. var _this = this;
  7292. var previousPosition;
  7293. var engine = this.getEngine();
  7294. if (this._attachedElement) {
  7295. return;
  7296. }
  7297. this._attachedElement = element;
  7298. if (this._onMouseDown === undefined) {
  7299. this._onMouseDown = function (evt) {
  7300. previousPosition = {
  7301. x: evt.clientX,
  7302. y: evt.clientY
  7303. };
  7304. if (!noPreventDefault) {
  7305. evt.preventDefault();
  7306. }
  7307. };
  7308. this._onMouseUp = function (evt) {
  7309. previousPosition = null;
  7310. if (!noPreventDefault) {
  7311. evt.preventDefault();
  7312. }
  7313. };
  7314. this._onMouseOut = function (evt) {
  7315. previousPosition = null;
  7316. _this._keys = [];
  7317. if (!noPreventDefault) {
  7318. evt.preventDefault();
  7319. }
  7320. };
  7321. this._onMouseMove = function (evt) {
  7322. if (!previousPosition && !engine.isPointerLock) {
  7323. return;
  7324. }
  7325. var offsetX;
  7326. var offsetY;
  7327. if (!engine.isPointerLock) {
  7328. offsetX = evt.clientX - previousPosition.x;
  7329. offsetY = evt.clientY - previousPosition.y;
  7330. }
  7331. else {
  7332. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7333. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7334. }
  7335. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  7336. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  7337. previousPosition = {
  7338. x: evt.clientX,
  7339. y: evt.clientY
  7340. };
  7341. if (!noPreventDefault) {
  7342. evt.preventDefault();
  7343. }
  7344. };
  7345. this._onKeyDown = function (evt) {
  7346. 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) {
  7347. var index = _this._keys.indexOf(evt.keyCode);
  7348. if (index === -1) {
  7349. _this._keys.push(evt.keyCode);
  7350. }
  7351. if (!noPreventDefault) {
  7352. evt.preventDefault();
  7353. }
  7354. }
  7355. };
  7356. this._onKeyUp = function (evt) {
  7357. 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) {
  7358. var index = _this._keys.indexOf(evt.keyCode);
  7359. if (index >= 0) {
  7360. _this._keys.splice(index, 1);
  7361. }
  7362. if (!noPreventDefault) {
  7363. evt.preventDefault();
  7364. }
  7365. }
  7366. };
  7367. this._onLostFocus = function () {
  7368. _this._keys = [];
  7369. };
  7370. this._reset = function () {
  7371. _this._keys = [];
  7372. previousPosition = null;
  7373. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7374. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  7375. };
  7376. }
  7377. element.addEventListener("mousedown", this._onMouseDown, false);
  7378. element.addEventListener("mouseup", this._onMouseUp, false);
  7379. element.addEventListener("mouseout", this._onMouseOut, false);
  7380. element.addEventListener("mousemove", this._onMouseMove, false);
  7381. BABYLON.Tools.RegisterTopRootEvents([
  7382. { name: "keydown", handler: this._onKeyDown },
  7383. { name: "keyup", handler: this._onKeyUp },
  7384. { name: "blur", handler: this._onLostFocus }
  7385. ]);
  7386. };
  7387. FreeCamera.prototype.detachControl = function (element) {
  7388. if (this._attachedElement != element) {
  7389. return;
  7390. }
  7391. element.removeEventListener("mousedown", this._onMouseDown);
  7392. element.removeEventListener("mouseup", this._onMouseUp);
  7393. element.removeEventListener("mouseout", this._onMouseOut);
  7394. element.removeEventListener("mousemove", this._onMouseMove);
  7395. BABYLON.Tools.UnregisterTopRootEvents([
  7396. { name: "keydown", handler: this._onKeyDown },
  7397. { name: "keyup", handler: this._onKeyUp },
  7398. { name: "blur", handler: this._onLostFocus }
  7399. ]);
  7400. this._attachedElement = null;
  7401. if (this._reset) {
  7402. this._reset();
  7403. }
  7404. };
  7405. FreeCamera.prototype._collideWithWorld = function (velocity) {
  7406. var globalPosition;
  7407. if (this.parent) {
  7408. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  7409. }
  7410. else {
  7411. globalPosition = this.position;
  7412. }
  7413. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  7414. this._collider.radius = this.ellipsoid;
  7415. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7416. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7417. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7418. this.position.addInPlace(this._diffPosition);
  7419. if (this.onCollide) {
  7420. this.onCollide(this._collider.collidedMesh);
  7421. }
  7422. }
  7423. };
  7424. FreeCamera.prototype._checkInputs = function () {
  7425. if (!this._localDirection) {
  7426. this._localDirection = BABYLON.Vector3.Zero();
  7427. this._transformedDirection = BABYLON.Vector3.Zero();
  7428. }
  7429. for (var index = 0; index < this._keys.length; index++) {
  7430. var keyCode = this._keys[index];
  7431. var speed = this._computeLocalCameraSpeed();
  7432. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7433. this._localDirection.copyFromFloats(-speed, 0, 0);
  7434. }
  7435. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7436. this._localDirection.copyFromFloats(0, 0, speed);
  7437. }
  7438. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7439. this._localDirection.copyFromFloats(speed, 0, 0);
  7440. }
  7441. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7442. this._localDirection.copyFromFloats(0, 0, -speed);
  7443. }
  7444. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7445. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7446. this.cameraDirection.addInPlace(this._transformedDirection);
  7447. }
  7448. };
  7449. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7450. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7451. };
  7452. FreeCamera.prototype._updatePosition = function () {
  7453. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7454. this._collideWithWorld(this.cameraDirection);
  7455. if (this.applyGravity) {
  7456. var oldPosition = this.position;
  7457. this._collideWithWorld(this.getScene().gravity);
  7458. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7459. }
  7460. }
  7461. else {
  7462. this.position.addInPlace(this.cameraDirection);
  7463. }
  7464. };
  7465. FreeCamera.prototype._update = function () {
  7466. this._checkInputs();
  7467. _super.prototype._update.call(this);
  7468. };
  7469. return FreeCamera;
  7470. })(BABYLON.TargetCamera);
  7471. BABYLON.FreeCamera = FreeCamera;
  7472. })(BABYLON || (BABYLON = {}));
  7473. //# sourceMappingURL=babylon.freeCamera.js.map
  7474. var BABYLON;
  7475. (function (BABYLON) {
  7476. // We're mainly based on the logic defined into the FreeCamera code
  7477. var TouchCamera = (function (_super) {
  7478. __extends(TouchCamera, _super);
  7479. function TouchCamera(name, position, scene) {
  7480. _super.call(this, name, position, scene);
  7481. this._offsetX = null;
  7482. this._offsetY = null;
  7483. this._pointerCount = 0;
  7484. this._pointerPressed = [];
  7485. this.angularSensibility = 200000.0;
  7486. this.moveSensibility = 500.0;
  7487. }
  7488. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7489. var _this = this;
  7490. var previousPosition;
  7491. if (this._attachedCanvas) {
  7492. return;
  7493. }
  7494. this._attachedCanvas = canvas;
  7495. if (this._onPointerDown === undefined) {
  7496. this._onPointerDown = function (evt) {
  7497. if (!noPreventDefault) {
  7498. evt.preventDefault();
  7499. }
  7500. _this._pointerPressed.push(evt.pointerId);
  7501. if (_this._pointerPressed.length !== 1) {
  7502. return;
  7503. }
  7504. previousPosition = {
  7505. x: evt.clientX,
  7506. y: evt.clientY
  7507. };
  7508. };
  7509. this._onPointerUp = function (evt) {
  7510. if (!noPreventDefault) {
  7511. evt.preventDefault();
  7512. }
  7513. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7514. if (index === -1) {
  7515. return;
  7516. }
  7517. _this._pointerPressed.splice(index, 1);
  7518. if (index != 0) {
  7519. return;
  7520. }
  7521. previousPosition = null;
  7522. _this._offsetX = null;
  7523. _this._offsetY = null;
  7524. };
  7525. this._onPointerMove = function (evt) {
  7526. if (!noPreventDefault) {
  7527. evt.preventDefault();
  7528. }
  7529. if (!previousPosition) {
  7530. return;
  7531. }
  7532. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7533. if (index != 0) {
  7534. return;
  7535. }
  7536. _this._offsetX = evt.clientX - previousPosition.x;
  7537. _this._offsetY = -(evt.clientY - previousPosition.y);
  7538. };
  7539. this._onLostFocus = function () {
  7540. _this._offsetX = null;
  7541. _this._offsetY = null;
  7542. };
  7543. }
  7544. canvas.addEventListener("pointerdown", this._onPointerDown);
  7545. canvas.addEventListener("pointerup", this._onPointerUp);
  7546. canvas.addEventListener("pointerout", this._onPointerUp);
  7547. canvas.addEventListener("pointermove", this._onPointerMove);
  7548. BABYLON.Tools.RegisterTopRootEvents([
  7549. { name: "blur", handler: this._onLostFocus }
  7550. ]);
  7551. };
  7552. TouchCamera.prototype.detachControl = function (canvas) {
  7553. if (this._attachedCanvas != canvas) {
  7554. return;
  7555. }
  7556. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7557. canvas.removeEventListener("pointerup", this._onPointerUp);
  7558. canvas.removeEventListener("pointerout", this._onPointerUp);
  7559. canvas.removeEventListener("pointermove", this._onPointerMove);
  7560. BABYLON.Tools.UnregisterTopRootEvents([
  7561. { name: "blur", handler: this._onLostFocus }
  7562. ]);
  7563. this._attachedCanvas = null;
  7564. };
  7565. TouchCamera.prototype._checkInputs = function () {
  7566. if (!this._offsetX) {
  7567. return;
  7568. }
  7569. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7570. if (this._pointerPressed.length > 1) {
  7571. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7572. }
  7573. else {
  7574. var speed = this._computeLocalCameraSpeed();
  7575. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7576. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7577. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7578. }
  7579. };
  7580. return TouchCamera;
  7581. })(BABYLON.FreeCamera);
  7582. BABYLON.TouchCamera = TouchCamera;
  7583. })(BABYLON || (BABYLON = {}));
  7584. //# sourceMappingURL=babylon.touchCamera.js.map
  7585. var BABYLON;
  7586. (function (BABYLON) {
  7587. // We're mainly based on the logic defined into the FreeCamera code
  7588. var DeviceOrientationCamera = (function (_super) {
  7589. __extends(DeviceOrientationCamera, _super);
  7590. function DeviceOrientationCamera(name, position, scene) {
  7591. var _this = this;
  7592. _super.call(this, name, position, scene);
  7593. this._offsetX = null;
  7594. this._offsetY = null;
  7595. this._orientationGamma = 0;
  7596. this._orientationBeta = 0;
  7597. this._initialOrientationGamma = 0;
  7598. this._initialOrientationBeta = 0;
  7599. this.angularSensibility = 10000.0;
  7600. this.moveSensibility = 50.0;
  7601. window.addEventListener("resize", function () {
  7602. _this._initialOrientationGamma = null;
  7603. }, false);
  7604. }
  7605. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7606. var _this = this;
  7607. if (this._attachedCanvas) {
  7608. return;
  7609. }
  7610. this._attachedCanvas = canvas;
  7611. if (!this._orientationChanged) {
  7612. this._orientationChanged = function (evt) {
  7613. if (!_this._initialOrientationGamma) {
  7614. _this._initialOrientationGamma = evt.gamma;
  7615. _this._initialOrientationBeta = evt.beta;
  7616. }
  7617. _this._orientationGamma = evt.gamma;
  7618. _this._orientationBeta = evt.beta;
  7619. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7620. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7621. };
  7622. }
  7623. window.addEventListener("deviceorientation", this._orientationChanged);
  7624. };
  7625. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7626. if (this._attachedCanvas != canvas) {
  7627. return;
  7628. }
  7629. window.removeEventListener("deviceorientation", this._orientationChanged);
  7630. this._attachedCanvas = null;
  7631. this._orientationGamma = 0;
  7632. this._orientationBeta = 0;
  7633. this._initialOrientationGamma = 0;
  7634. this._initialOrientationBeta = 0;
  7635. };
  7636. DeviceOrientationCamera.prototype._checkInputs = function () {
  7637. if (!this._offsetX) {
  7638. return;
  7639. }
  7640. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7641. var speed = this._computeLocalCameraSpeed();
  7642. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7643. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7644. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7645. };
  7646. return DeviceOrientationCamera;
  7647. })(BABYLON.FreeCamera);
  7648. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7649. })(BABYLON || (BABYLON = {}));
  7650. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7651. var BABYLON;
  7652. (function (BABYLON) {
  7653. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7654. var ArcRotateCamera = (function (_super) {
  7655. __extends(ArcRotateCamera, _super);
  7656. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7657. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7658. this.alpha = alpha;
  7659. this.beta = beta;
  7660. this.radius = radius;
  7661. this.target = target;
  7662. this.inertialAlphaOffset = 0;
  7663. this.inertialBetaOffset = 0;
  7664. this.inertialRadiusOffset = 0;
  7665. this.lowerAlphaLimit = null;
  7666. this.upperAlphaLimit = null;
  7667. this.lowerBetaLimit = 0.01;
  7668. this.upperBetaLimit = Math.PI;
  7669. this.lowerRadiusLimit = null;
  7670. this.upperRadiusLimit = null;
  7671. this.angularSensibility = 1000.0;
  7672. this.wheelPrecision = 3.0;
  7673. this.pinchPrecision = 2.0;
  7674. this.keysUp = [38];
  7675. this.keysDown = [40];
  7676. this.keysLeft = [37];
  7677. this.keysRight = [39];
  7678. this.zoomOnFactor = 1;
  7679. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7680. this._keys = [];
  7681. this._viewMatrix = new BABYLON.Matrix();
  7682. this.checkCollisions = false;
  7683. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7684. this._collider = new BABYLON.Collider();
  7685. this._previousPosition = BABYLON.Vector3.Zero();
  7686. this._collisionVelocity = BABYLON.Vector3.Zero();
  7687. this._newPosition = BABYLON.Vector3.Zero();
  7688. this.getViewMatrix();
  7689. }
  7690. ArcRotateCamera.prototype._getTargetPosition = function () {
  7691. return this.target.position || this.target;
  7692. };
  7693. // Cache
  7694. ArcRotateCamera.prototype._initCache = function () {
  7695. _super.prototype._initCache.call(this);
  7696. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7697. this._cache.alpha = undefined;
  7698. this._cache.beta = undefined;
  7699. this._cache.radius = undefined;
  7700. this._cache.targetScreenOffset = undefined;
  7701. };
  7702. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7703. if (!ignoreParentClass) {
  7704. _super.prototype._updateCache.call(this);
  7705. }
  7706. this._cache.target.copyFrom(this._getTargetPosition());
  7707. this._cache.alpha = this.alpha;
  7708. this._cache.beta = this.beta;
  7709. this._cache.radius = this.radius;
  7710. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7711. };
  7712. // Synchronized
  7713. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7714. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7715. return false;
  7716. 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);
  7717. };
  7718. // Methods
  7719. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7720. var _this = this;
  7721. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  7722. var previousPinchDistance = 0;
  7723. var pointers = new BABYLON.SmartCollection();
  7724. if (this._attachedElement) {
  7725. return;
  7726. }
  7727. this._attachedElement = element;
  7728. var engine = this.getEngine();
  7729. if (this._onPointerDown === undefined) {
  7730. this._onPointerDown = function (evt) {
  7731. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  7732. cacheSoloPointer = pointers.item(evt.pointerId);
  7733. if (!noPreventDefault) {
  7734. evt.preventDefault();
  7735. }
  7736. };
  7737. this._onPointerUp = function (evt) {
  7738. cacheSoloPointer = null;
  7739. previousPinchDistance = 0;
  7740. pointers.remove(evt.pointerId);
  7741. if (!noPreventDefault) {
  7742. evt.preventDefault();
  7743. }
  7744. };
  7745. this._onPointerMove = function (evt) {
  7746. if (!noPreventDefault) {
  7747. evt.preventDefault();
  7748. }
  7749. switch (pointers.count) {
  7750. case 1:
  7751. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  7752. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  7753. var offsetX = evt.clientX - cacheSoloPointer.x;
  7754. var offsetY = evt.clientY - cacheSoloPointer.y;
  7755. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7756. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7757. //pointers.item(evt.pointerId).x = evt.clientX;
  7758. //pointers.item(evt.pointerId).y = evt.clientY;
  7759. cacheSoloPointer.x = evt.clientX;
  7760. cacheSoloPointer.y = evt.clientY;
  7761. break;
  7762. case 2:
  7763. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  7764. pointers.item(evt.pointerId).x = evt.clientX;
  7765. pointers.item(evt.pointerId).y = evt.clientY;
  7766. var direction = 1;
  7767. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  7768. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  7769. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  7770. if (previousPinchDistance === 0) {
  7771. previousPinchDistance = pinchSquaredDistance;
  7772. return;
  7773. }
  7774. if (pinchSquaredDistance != previousPinchDistance) {
  7775. if (pinchSquaredDistance > previousPinchDistance) {
  7776. direction = -1;
  7777. }
  7778. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility);
  7779. previousPinchDistance = pinchSquaredDistance;
  7780. }
  7781. break;
  7782. default:
  7783. if (pointers.item(evt.pointerId)) {
  7784. pointers.item(evt.pointerId).x = evt.clientX;
  7785. pointers.item(evt.pointerId).y = evt.clientY;
  7786. }
  7787. }
  7788. };
  7789. this._onMouseMove = function (evt) {
  7790. if (!engine.isPointerLock) {
  7791. return;
  7792. }
  7793. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7794. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7795. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7796. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7797. if (!noPreventDefault) {
  7798. evt.preventDefault();
  7799. }
  7800. };
  7801. this._wheel = function (event) {
  7802. var delta = 0;
  7803. if (event.wheelDelta) {
  7804. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7805. }
  7806. else if (event.detail) {
  7807. delta = -event.detail / _this.wheelPrecision;
  7808. }
  7809. if (delta)
  7810. _this.inertialRadiusOffset += delta;
  7811. if (event.preventDefault) {
  7812. if (!noPreventDefault) {
  7813. event.preventDefault();
  7814. }
  7815. }
  7816. };
  7817. this._onKeyDown = function (evt) {
  7818. 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) {
  7819. var index = _this._keys.indexOf(evt.keyCode);
  7820. if (index === -1) {
  7821. _this._keys.push(evt.keyCode);
  7822. }
  7823. if (evt.preventDefault) {
  7824. if (!noPreventDefault) {
  7825. evt.preventDefault();
  7826. }
  7827. }
  7828. }
  7829. };
  7830. this._onKeyUp = function (evt) {
  7831. 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) {
  7832. var index = _this._keys.indexOf(evt.keyCode);
  7833. if (index >= 0) {
  7834. _this._keys.splice(index, 1);
  7835. }
  7836. if (evt.preventDefault) {
  7837. if (!noPreventDefault) {
  7838. evt.preventDefault();
  7839. }
  7840. }
  7841. }
  7842. };
  7843. this._onLostFocus = function () {
  7844. _this._keys = [];
  7845. pointers.empty();
  7846. previousPinchDistance = 0;
  7847. cacheSoloPointer = null;
  7848. };
  7849. this._onGestureStart = function (e) {
  7850. if (window.MSGesture === undefined) {
  7851. return;
  7852. }
  7853. if (!_this._MSGestureHandler) {
  7854. _this._MSGestureHandler = new MSGesture();
  7855. _this._MSGestureHandler.target = element;
  7856. }
  7857. _this._MSGestureHandler.addPointer(e.pointerId);
  7858. };
  7859. this._onGesture = function (e) {
  7860. _this.radius *= e.scale;
  7861. if (e.preventDefault) {
  7862. if (!noPreventDefault) {
  7863. e.stopPropagation();
  7864. e.preventDefault();
  7865. }
  7866. }
  7867. };
  7868. this._reset = function () {
  7869. _this._keys = [];
  7870. _this.inertialAlphaOffset = 0;
  7871. _this.inertialBetaOffset = 0;
  7872. _this.inertialRadiusOffset = 0;
  7873. pointers.empty();
  7874. previousPinchDistance = 0;
  7875. cacheSoloPointer = null;
  7876. };
  7877. }
  7878. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7879. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7880. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7881. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7882. element.addEventListener("mousemove", this._onMouseMove, false);
  7883. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7884. element.addEventListener("MSGestureChange", this._onGesture, false);
  7885. element.addEventListener('mousewheel', this._wheel, false);
  7886. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7887. BABYLON.Tools.RegisterTopRootEvents([
  7888. { name: "keydown", handler: this._onKeyDown },
  7889. { name: "keyup", handler: this._onKeyUp },
  7890. { name: "blur", handler: this._onLostFocus }
  7891. ]);
  7892. };
  7893. ArcRotateCamera.prototype.detachControl = function (element) {
  7894. if (this._attachedElement != element) {
  7895. return;
  7896. }
  7897. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7898. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7899. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7900. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7901. element.removeEventListener("mousemove", this._onMouseMove);
  7902. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7903. element.removeEventListener("MSGestureChange", this._onGesture);
  7904. element.removeEventListener('mousewheel', this._wheel);
  7905. element.removeEventListener('DOMMouseScroll', this._wheel);
  7906. BABYLON.Tools.UnregisterTopRootEvents([
  7907. { name: "keydown", handler: this._onKeyDown },
  7908. { name: "keyup", handler: this._onKeyUp },
  7909. { name: "blur", handler: this._onLostFocus }
  7910. ]);
  7911. this._MSGestureHandler = null;
  7912. this._attachedElement = null;
  7913. if (this._reset) {
  7914. this._reset();
  7915. }
  7916. };
  7917. ArcRotateCamera.prototype._update = function () {
  7918. for (var index = 0; index < this._keys.length; index++) {
  7919. var keyCode = this._keys[index];
  7920. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7921. this.inertialAlphaOffset -= 0.01;
  7922. }
  7923. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7924. this.inertialBetaOffset -= 0.01;
  7925. }
  7926. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7927. this.inertialAlphaOffset += 0.01;
  7928. }
  7929. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7930. this.inertialBetaOffset += 0.01;
  7931. }
  7932. }
  7933. // Inertia
  7934. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7935. this.alpha += this.inertialAlphaOffset;
  7936. this.beta += this.inertialBetaOffset;
  7937. this.radius -= this.inertialRadiusOffset;
  7938. this.inertialAlphaOffset *= this.inertia;
  7939. this.inertialBetaOffset *= this.inertia;
  7940. this.inertialRadiusOffset *= this.inertia;
  7941. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7942. this.inertialAlphaOffset = 0;
  7943. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7944. this.inertialBetaOffset = 0;
  7945. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7946. this.inertialRadiusOffset = 0;
  7947. }
  7948. // Limits
  7949. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7950. this.alpha = this.lowerAlphaLimit;
  7951. }
  7952. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7953. this.alpha = this.upperAlphaLimit;
  7954. }
  7955. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7956. this.beta = this.lowerBetaLimit;
  7957. }
  7958. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7959. this.beta = this.upperBetaLimit;
  7960. }
  7961. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7962. this.radius = this.lowerRadiusLimit;
  7963. }
  7964. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7965. this.radius = this.upperRadiusLimit;
  7966. }
  7967. };
  7968. ArcRotateCamera.prototype.setPosition = function (position) {
  7969. var radiusv3 = position.subtract(this._getTargetPosition());
  7970. this.radius = radiusv3.length();
  7971. // Alpha
  7972. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7973. if (radiusv3.z < 0) {
  7974. this.alpha = 2 * Math.PI - this.alpha;
  7975. }
  7976. // Beta
  7977. this.beta = Math.acos(radiusv3.y / this.radius);
  7978. };
  7979. ArcRotateCamera.prototype._getViewMatrix = function () {
  7980. // Compute
  7981. var cosa = Math.cos(this.alpha);
  7982. var sina = Math.sin(this.alpha);
  7983. var cosb = Math.cos(this.beta);
  7984. var sinb = Math.sin(this.beta);
  7985. var target = this._getTargetPosition();
  7986. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7987. if (this.checkCollisions) {
  7988. this._collider.radius = this.collisionRadius;
  7989. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7990. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7991. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7992. this.position.copyFrom(this._previousPosition);
  7993. this.alpha = this._previousAlpha;
  7994. this.beta = this._previousBeta;
  7995. this.radius = this._previousRadius;
  7996. if (this.onCollide) {
  7997. this.onCollide(this._collider.collidedMesh);
  7998. }
  7999. }
  8000. }
  8001. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  8002. this._previousAlpha = this.alpha;
  8003. this._previousBeta = this.beta;
  8004. this._previousRadius = this.radius;
  8005. this._previousPosition.copyFrom(this.position);
  8006. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  8007. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  8008. return this._viewMatrix;
  8009. };
  8010. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  8011. meshes = meshes || this.getScene().meshes;
  8012. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  8013. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  8014. this.radius = distance * this.zoomOnFactor;
  8015. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  8016. };
  8017. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  8018. var meshesOrMinMaxVector;
  8019. var distance;
  8020. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  8021. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  8022. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8023. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  8024. }
  8025. else {
  8026. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  8027. distance = meshesOrMinMaxVectorAndDistance.distance;
  8028. }
  8029. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  8030. this.maxZ = distance * 2;
  8031. };
  8032. return ArcRotateCamera;
  8033. })(BABYLON.Camera);
  8034. BABYLON.ArcRotateCamera = ArcRotateCamera;
  8035. })(BABYLON || (BABYLON = {}));
  8036. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  8037. (function (BABYLON) {
  8038. /**
  8039. * Represents a scene to be rendered by the engine.
  8040. * @see http://doc.babylonjs.com/page.php?p=21911
  8041. */
  8042. var Scene = (function () {
  8043. /**
  8044. * @constructor
  8045. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  8046. */
  8047. function Scene(engine) {
  8048. // Members
  8049. this.autoClear = true;
  8050. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8051. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  8052. this.forceWireframe = false;
  8053. this.forcePointsCloud = false;
  8054. this.forceShowBoundingBoxes = false;
  8055. this.animationsEnabled = true;
  8056. 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
  8057. // Fog
  8058. /**
  8059. * is fog enabled on this scene.
  8060. * @type {boolean}
  8061. */
  8062. this.fogEnabled = true;
  8063. this.fogMode = Scene.FOGMODE_NONE;
  8064. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8065. this.fogDensity = 0.1;
  8066. this.fogStart = 0;
  8067. this.fogEnd = 1000.0;
  8068. // Lights
  8069. /**
  8070. * is shadow enabled on this scene.
  8071. * @type {boolean}
  8072. */
  8073. this.shadowsEnabled = true;
  8074. /**
  8075. * is light enabled on this scene.
  8076. * @type {boolean}
  8077. */
  8078. this.lightsEnabled = true;
  8079. /**
  8080. * All of the lights added to this scene.
  8081. * @see BABYLON.Light
  8082. * @type {BABYLON.Light[]}
  8083. */
  8084. this.lights = new Array();
  8085. // Cameras
  8086. /**
  8087. * All of the cameras added to this scene.
  8088. * @see BABYLON.Camera
  8089. * @type {BABYLON.Camera[]}
  8090. */
  8091. this.cameras = new Array();
  8092. this.activeCameras = new Array();
  8093. // Meshes
  8094. /**
  8095. * All of the (abstract) meshes added to this scene.
  8096. * @see BABYLON.AbstractMesh
  8097. * @type {BABYLON.AbstractMesh[]}
  8098. */
  8099. this.meshes = new Array();
  8100. // Geometries
  8101. this._geometries = new Array();
  8102. this.materials = new Array();
  8103. this.multiMaterials = new Array();
  8104. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  8105. // Textures
  8106. this.texturesEnabled = true;
  8107. this.textures = new Array();
  8108. // Particles
  8109. this.particlesEnabled = true;
  8110. this.particleSystems = new Array();
  8111. // Sprites
  8112. this.spritesEnabled = true;
  8113. this.spriteManagers = new Array();
  8114. // Layers
  8115. this.layers = new Array();
  8116. // Skeletons
  8117. this.skeletonsEnabled = true;
  8118. this.skeletons = new Array();
  8119. // Lens flares
  8120. this.lensFlaresEnabled = true;
  8121. this.lensFlareSystems = new Array();
  8122. // Collisions
  8123. this.collisionsEnabled = true;
  8124. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  8125. // Postprocesses
  8126. this.postProcessesEnabled = true;
  8127. // Customs render targets
  8128. this.renderTargetsEnabled = true;
  8129. this.dumpNextRenderTargets = false;
  8130. this.customRenderTargets = new Array();
  8131. // Imported meshes
  8132. this.importedMeshesFiles = new Array();
  8133. this._actionManagers = new Array();
  8134. this._meshesForIntersections = new BABYLON.SmartArray(256);
  8135. // Procedural textures
  8136. this.proceduralTexturesEnabled = true;
  8137. this._proceduralTextures = new Array();
  8138. this.soundTracks = new Array();
  8139. this._audioEnabled = true;
  8140. this._headphone = false;
  8141. this._totalVertices = 0;
  8142. this._activeVertices = 0;
  8143. this._activeParticles = 0;
  8144. this._lastFrameDuration = 0;
  8145. this._evaluateActiveMeshesDuration = 0;
  8146. this._renderTargetsDuration = 0;
  8147. this._particlesDuration = 0;
  8148. this._renderDuration = 0;
  8149. this._spritesDuration = 0;
  8150. this._animationRatio = 0;
  8151. this._renderId = 0;
  8152. this._executeWhenReadyTimeoutId = -1;
  8153. this._toBeDisposed = new BABYLON.SmartArray(256);
  8154. this._onReadyCallbacks = new Array();
  8155. this._pendingData = []; //ANY
  8156. this._onBeforeRenderCallbacks = new Array();
  8157. this._onAfterRenderCallbacks = new Array();
  8158. this._activeMeshes = new BABYLON.SmartArray(256);
  8159. this._processedMaterials = new BABYLON.SmartArray(256);
  8160. this._renderTargets = new BABYLON.SmartArray(256);
  8161. this._activeParticleSystems = new BABYLON.SmartArray(256);
  8162. this._activeSkeletons = new BABYLON.SmartArray(32);
  8163. this._activeBones = 0;
  8164. this._activeAnimatables = new Array();
  8165. this._transformMatrix = BABYLON.Matrix.Zero();
  8166. this._scaledPosition = BABYLON.Vector3.Zero();
  8167. this._scaledVelocity = BABYLON.Vector3.Zero();
  8168. this._engine = engine;
  8169. engine.scenes.push(this);
  8170. this._renderingManager = new BABYLON.RenderingManager(this);
  8171. this.postProcessManager = new BABYLON.PostProcessManager(this);
  8172. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  8173. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  8174. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  8175. this.attachControl();
  8176. this._debugLayer = new BABYLON.DebugLayer(this);
  8177. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  8178. //simplification queue
  8179. this.simplificationQueue = new BABYLON.SimplificationQueue();
  8180. }
  8181. Object.defineProperty(Scene, "FOGMODE_NONE", {
  8182. get: function () {
  8183. return Scene._FOGMODE_NONE;
  8184. },
  8185. enumerable: true,
  8186. configurable: true
  8187. });
  8188. Object.defineProperty(Scene, "FOGMODE_EXP", {
  8189. get: function () {
  8190. return Scene._FOGMODE_EXP;
  8191. },
  8192. enumerable: true,
  8193. configurable: true
  8194. });
  8195. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  8196. get: function () {
  8197. return Scene._FOGMODE_EXP2;
  8198. },
  8199. enumerable: true,
  8200. configurable: true
  8201. });
  8202. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  8203. get: function () {
  8204. return Scene._FOGMODE_LINEAR;
  8205. },
  8206. enumerable: true,
  8207. configurable: true
  8208. });
  8209. Object.defineProperty(Scene.prototype, "debugLayer", {
  8210. // Properties
  8211. get: function () {
  8212. return this._debugLayer;
  8213. },
  8214. enumerable: true,
  8215. configurable: true
  8216. });
  8217. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  8218. /**
  8219. * The mesh that is currently under the pointer.
  8220. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  8221. */
  8222. get: function () {
  8223. return this._meshUnderPointer;
  8224. },
  8225. enumerable: true,
  8226. configurable: true
  8227. });
  8228. Object.defineProperty(Scene.prototype, "pointerX", {
  8229. /**
  8230. * Current on-screen X position of the pointer
  8231. * @return {number} X position of the pointer
  8232. */
  8233. get: function () {
  8234. return this._pointerX;
  8235. },
  8236. enumerable: true,
  8237. configurable: true
  8238. });
  8239. Object.defineProperty(Scene.prototype, "pointerY", {
  8240. /**
  8241. * Current on-screen Y position of the pointer
  8242. * @return {number} Y position of the pointer
  8243. */
  8244. get: function () {
  8245. return this._pointerY;
  8246. },
  8247. enumerable: true,
  8248. configurable: true
  8249. });
  8250. Scene.prototype.getCachedMaterial = function () {
  8251. return this._cachedMaterial;
  8252. };
  8253. Scene.prototype.getBoundingBoxRenderer = function () {
  8254. return this._boundingBoxRenderer;
  8255. };
  8256. Scene.prototype.getOutlineRenderer = function () {
  8257. return this._outlineRenderer;
  8258. };
  8259. Scene.prototype.getEngine = function () {
  8260. return this._engine;
  8261. };
  8262. Scene.prototype.getTotalVertices = function () {
  8263. return this._totalVertices;
  8264. };
  8265. Scene.prototype.getActiveVertices = function () {
  8266. return this._activeVertices;
  8267. };
  8268. Scene.prototype.getActiveParticles = function () {
  8269. return this._activeParticles;
  8270. };
  8271. Scene.prototype.getActiveBones = function () {
  8272. return this._activeBones;
  8273. };
  8274. // Stats
  8275. Scene.prototype.getLastFrameDuration = function () {
  8276. return this._lastFrameDuration;
  8277. };
  8278. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  8279. return this._evaluateActiveMeshesDuration;
  8280. };
  8281. Scene.prototype.getActiveMeshes = function () {
  8282. return this._activeMeshes;
  8283. };
  8284. Scene.prototype.getRenderTargetsDuration = function () {
  8285. return this._renderTargetsDuration;
  8286. };
  8287. Scene.prototype.getRenderDuration = function () {
  8288. return this._renderDuration;
  8289. };
  8290. Scene.prototype.getParticlesDuration = function () {
  8291. return this._particlesDuration;
  8292. };
  8293. Scene.prototype.getSpritesDuration = function () {
  8294. return this._spritesDuration;
  8295. };
  8296. Scene.prototype.getAnimationRatio = function () {
  8297. return this._animationRatio;
  8298. };
  8299. Scene.prototype.getRenderId = function () {
  8300. return this._renderId;
  8301. };
  8302. Scene.prototype.incrementRenderId = function () {
  8303. this._renderId++;
  8304. };
  8305. Scene.prototype._updatePointerPosition = function (evt) {
  8306. var canvasRect = this._engine.getRenderingCanvasClientRect();
  8307. this._pointerX = evt.clientX - canvasRect.left;
  8308. this._pointerY = evt.clientY - canvasRect.top;
  8309. if (this.cameraToUseForPointers) {
  8310. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  8311. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  8312. }
  8313. };
  8314. // Pointers handling
  8315. Scene.prototype.attachControl = function () {
  8316. var _this = this;
  8317. this._onPointerMove = function (evt) {
  8318. var canvas = _this._engine.getRenderingCanvas();
  8319. _this._updatePointerPosition(evt);
  8320. 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);
  8321. if (pickResult.hit) {
  8322. _this._meshUnderPointer = pickResult.pickedMesh;
  8323. _this.setPointerOverMesh(pickResult.pickedMesh);
  8324. canvas.style.cursor = "pointer";
  8325. }
  8326. else {
  8327. _this.setPointerOverMesh(null);
  8328. canvas.style.cursor = "";
  8329. _this._meshUnderPointer = null;
  8330. }
  8331. };
  8332. this._onPointerDown = function (evt) {
  8333. var predicate = null;
  8334. if (!_this.onPointerDown) {
  8335. predicate = function (mesh) {
  8336. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  8337. };
  8338. }
  8339. _this._updatePointerPosition(evt);
  8340. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8341. if (pickResult.hit) {
  8342. if (pickResult.pickedMesh.actionManager) {
  8343. switch (evt.button) {
  8344. case 0:
  8345. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8346. break;
  8347. case 1:
  8348. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8349. break;
  8350. case 2:
  8351. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8352. break;
  8353. }
  8354. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8355. }
  8356. }
  8357. if (_this.onPointerDown) {
  8358. _this.onPointerDown(evt, pickResult);
  8359. }
  8360. };
  8361. this._onKeyDown = function (evt) {
  8362. if (_this.actionManager) {
  8363. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8364. }
  8365. };
  8366. this._onKeyUp = function (evt) {
  8367. if (_this.actionManager) {
  8368. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8369. }
  8370. };
  8371. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8372. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8373. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8374. BABYLON.Tools.RegisterTopRootEvents([
  8375. { name: "keydown", handler: this._onKeyDown },
  8376. { name: "keyup", handler: this._onKeyUp }
  8377. ]);
  8378. };
  8379. Scene.prototype.detachControl = function () {
  8380. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8381. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8382. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8383. BABYLON.Tools.UnregisterTopRootEvents([
  8384. { name: "keydown", handler: this._onKeyDown },
  8385. { name: "keyup", handler: this._onKeyUp }
  8386. ]);
  8387. };
  8388. // Ready
  8389. Scene.prototype.isReady = function () {
  8390. if (this._pendingData.length > 0) {
  8391. return false;
  8392. }
  8393. for (var index = 0; index < this._geometries.length; index++) {
  8394. var geometry = this._geometries[index];
  8395. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8396. return false;
  8397. }
  8398. }
  8399. for (index = 0; index < this.meshes.length; index++) {
  8400. var mesh = this.meshes[index];
  8401. if (!mesh.isReady()) {
  8402. return false;
  8403. }
  8404. var mat = mesh.material;
  8405. if (mat) {
  8406. if (!mat.isReady(mesh)) {
  8407. return false;
  8408. }
  8409. }
  8410. }
  8411. return true;
  8412. };
  8413. Scene.prototype.resetCachedMaterial = function () {
  8414. this._cachedMaterial = null;
  8415. };
  8416. Scene.prototype.registerBeforeRender = function (func) {
  8417. this._onBeforeRenderCallbacks.push(func);
  8418. };
  8419. Scene.prototype.unregisterBeforeRender = function (func) {
  8420. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8421. if (index > -1) {
  8422. this._onBeforeRenderCallbacks.splice(index, 1);
  8423. }
  8424. };
  8425. Scene.prototype.registerAfterRender = function (func) {
  8426. this._onAfterRenderCallbacks.push(func);
  8427. };
  8428. Scene.prototype.unregisterAfterRender = function (func) {
  8429. var index = this._onAfterRenderCallbacks.indexOf(func);
  8430. if (index > -1) {
  8431. this._onAfterRenderCallbacks.splice(index, 1);
  8432. }
  8433. };
  8434. Scene.prototype._addPendingData = function (data) {
  8435. this._pendingData.push(data);
  8436. };
  8437. Scene.prototype._removePendingData = function (data) {
  8438. var index = this._pendingData.indexOf(data);
  8439. if (index !== -1) {
  8440. this._pendingData.splice(index, 1);
  8441. }
  8442. };
  8443. Scene.prototype.getWaitingItemsCount = function () {
  8444. return this._pendingData.length;
  8445. };
  8446. /**
  8447. * Registers a function to be executed when the scene is ready.
  8448. * @param {Function} func - the function to be executed.
  8449. */
  8450. Scene.prototype.executeWhenReady = function (func) {
  8451. var _this = this;
  8452. this._onReadyCallbacks.push(func);
  8453. if (this._executeWhenReadyTimeoutId !== -1) {
  8454. return;
  8455. }
  8456. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8457. _this._checkIsReady();
  8458. }, 150);
  8459. };
  8460. Scene.prototype._checkIsReady = function () {
  8461. var _this = this;
  8462. if (this.isReady()) {
  8463. this._onReadyCallbacks.forEach(function (func) {
  8464. func();
  8465. });
  8466. this._onReadyCallbacks = [];
  8467. this._executeWhenReadyTimeoutId = -1;
  8468. return;
  8469. }
  8470. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8471. _this._checkIsReady();
  8472. }, 150);
  8473. };
  8474. // Animations
  8475. /**
  8476. * Will start the animation sequence of a given target
  8477. * @param target - the target
  8478. * @param {number} from - from which frame should animation start
  8479. * @param {number} to - till which frame should animation run.
  8480. * @param {boolean} [loop] - should the animation loop
  8481. * @param {number} [speedRatio] - the speed in which to run the animation
  8482. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8483. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8484. * @return {BABYLON.Animatable} the animatable object created for this animation
  8485. * @see BABYLON.Animatable
  8486. * @see http://doc.babylonjs.com/page.php?p=22081
  8487. */
  8488. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8489. if (speedRatio === undefined) {
  8490. speedRatio = 1.0;
  8491. }
  8492. this.stopAnimation(target);
  8493. if (!animatable) {
  8494. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8495. }
  8496. // Local animations
  8497. if (target.animations) {
  8498. animatable.appendAnimations(target, target.animations);
  8499. }
  8500. // Children animations
  8501. if (target.getAnimatables) {
  8502. var animatables = target.getAnimatables();
  8503. for (var index = 0; index < animatables.length; index++) {
  8504. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8505. }
  8506. }
  8507. return animatable;
  8508. };
  8509. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8510. if (speedRatio === undefined) {
  8511. speedRatio = 1.0;
  8512. }
  8513. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8514. return animatable;
  8515. };
  8516. Scene.prototype.getAnimatableByTarget = function (target) {
  8517. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8518. if (this._activeAnimatables[index].target === target) {
  8519. return this._activeAnimatables[index];
  8520. }
  8521. }
  8522. return null;
  8523. };
  8524. /**
  8525. * Will stop the animation of the given target
  8526. * @param target - the target
  8527. * @see beginAnimation
  8528. */
  8529. Scene.prototype.stopAnimation = function (target) {
  8530. var animatable = this.getAnimatableByTarget(target);
  8531. if (animatable) {
  8532. animatable.stop();
  8533. }
  8534. };
  8535. Scene.prototype._animate = function () {
  8536. if (!this.animationsEnabled) {
  8537. return;
  8538. }
  8539. if (!this._animationStartDate) {
  8540. this._animationStartDate = BABYLON.Tools.Now;
  8541. }
  8542. // Getting time
  8543. var now = BABYLON.Tools.Now;
  8544. var delay = now - this._animationStartDate;
  8545. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8546. this._activeAnimatables[index]._animate(delay);
  8547. }
  8548. };
  8549. // Matrix
  8550. Scene.prototype.getViewMatrix = function () {
  8551. return this._viewMatrix;
  8552. };
  8553. Scene.prototype.getProjectionMatrix = function () {
  8554. return this._projectionMatrix;
  8555. };
  8556. Scene.prototype.getTransformMatrix = function () {
  8557. return this._transformMatrix;
  8558. };
  8559. Scene.prototype.setTransformMatrix = function (view, projection) {
  8560. this._viewMatrix = view;
  8561. this._projectionMatrix = projection;
  8562. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8563. };
  8564. // Methods
  8565. Scene.prototype.addMesh = function (newMesh) {
  8566. var position = this.meshes.push(newMesh);
  8567. if (this.onNewMeshAdded) {
  8568. this.onNewMeshAdded(newMesh, position, this);
  8569. }
  8570. };
  8571. Scene.prototype.removeMesh = function (toRemove) {
  8572. var index = this.meshes.indexOf(toRemove);
  8573. if (index !== -1) {
  8574. // Remove from the scene if mesh found
  8575. this.meshes.splice(index, 1);
  8576. }
  8577. if (this.onMeshRemoved) {
  8578. this.onMeshRemoved(toRemove);
  8579. }
  8580. return index;
  8581. };
  8582. Scene.prototype.removeLight = function (toRemove) {
  8583. var index = this.lights.indexOf(toRemove);
  8584. if (index !== -1) {
  8585. // Remove from the scene if mesh found
  8586. this.lights.splice(index, 1);
  8587. }
  8588. if (this.onLightRemoved) {
  8589. this.onLightRemoved(toRemove);
  8590. }
  8591. return index;
  8592. };
  8593. Scene.prototype.removeCamera = function (toRemove) {
  8594. var index = this.cameras.indexOf(toRemove);
  8595. if (index !== -1) {
  8596. // Remove from the scene if mesh found
  8597. this.cameras.splice(index, 1);
  8598. }
  8599. if (this.onCameraRemoved) {
  8600. this.onCameraRemoved(toRemove);
  8601. }
  8602. return index;
  8603. };
  8604. Scene.prototype.addLight = function (newLight) {
  8605. var position = this.lights.push(newLight);
  8606. if (this.onNewLightAdded) {
  8607. this.onNewLightAdded(newLight, position, this);
  8608. }
  8609. };
  8610. Scene.prototype.addCamera = function (newCamera) {
  8611. var position = this.cameras.push(newCamera);
  8612. if (this.onNewCameraAdded) {
  8613. this.onNewCameraAdded(newCamera, position, this);
  8614. }
  8615. };
  8616. /**
  8617. * sets the active camera of the scene using its ID
  8618. * @param {string} id - the camera's ID
  8619. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8620. * @see activeCamera
  8621. */
  8622. Scene.prototype.setActiveCameraByID = function (id) {
  8623. var camera = this.getCameraByID(id);
  8624. if (camera) {
  8625. this.activeCamera = camera;
  8626. return camera;
  8627. }
  8628. return null;
  8629. };
  8630. /**
  8631. * sets the active camera of the scene using its name
  8632. * @param {string} name - the camera's name
  8633. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8634. * @see activeCamera
  8635. */
  8636. Scene.prototype.setActiveCameraByName = function (name) {
  8637. var camera = this.getCameraByName(name);
  8638. if (camera) {
  8639. this.activeCamera = camera;
  8640. return camera;
  8641. }
  8642. return null;
  8643. };
  8644. /**
  8645. * get a material using its id
  8646. * @param {string} the material's ID
  8647. * @return {BABYLON.Material|null} the material or null if none found.
  8648. */
  8649. Scene.prototype.getMaterialByID = function (id) {
  8650. for (var index = 0; index < this.materials.length; index++) {
  8651. if (this.materials[index].id === id) {
  8652. return this.materials[index];
  8653. }
  8654. }
  8655. return null;
  8656. };
  8657. /**
  8658. * get a material using its name
  8659. * @param {string} the material's name
  8660. * @return {BABYLON.Material|null} the material or null if none found.
  8661. */
  8662. Scene.prototype.getMaterialByName = function (name) {
  8663. for (var index = 0; index < this.materials.length; index++) {
  8664. if (this.materials[index].name === name) {
  8665. return this.materials[index];
  8666. }
  8667. }
  8668. return null;
  8669. };
  8670. Scene.prototype.getCameraByID = function (id) {
  8671. for (var index = 0; index < this.cameras.length; index++) {
  8672. if (this.cameras[index].id === id) {
  8673. return this.cameras[index];
  8674. }
  8675. }
  8676. return null;
  8677. };
  8678. /**
  8679. * get a camera using its name
  8680. * @param {string} the camera's name
  8681. * @return {BABYLON.Camera|null} the camera or null if none found.
  8682. */
  8683. Scene.prototype.getCameraByName = function (name) {
  8684. for (var index = 0; index < this.cameras.length; index++) {
  8685. if (this.cameras[index].name === name) {
  8686. return this.cameras[index];
  8687. }
  8688. }
  8689. return null;
  8690. };
  8691. /**
  8692. * get a light node using its name
  8693. * @param {string} the light's name
  8694. * @return {BABYLON.Light|null} the light or null if none found.
  8695. */
  8696. Scene.prototype.getLightByName = function (name) {
  8697. for (var index = 0; index < this.lights.length; index++) {
  8698. if (this.lights[index].name === name) {
  8699. return this.lights[index];
  8700. }
  8701. }
  8702. return null;
  8703. };
  8704. /**
  8705. * get a light node using its ID
  8706. * @param {string} the light's id
  8707. * @return {BABYLON.Light|null} the light or null if none found.
  8708. */
  8709. Scene.prototype.getLightByID = function (id) {
  8710. for (var index = 0; index < this.lights.length; index++) {
  8711. if (this.lights[index].id === id) {
  8712. return this.lights[index];
  8713. }
  8714. }
  8715. return null;
  8716. };
  8717. /**
  8718. * get a geometry using its ID
  8719. * @param {string} the geometry's id
  8720. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8721. */
  8722. Scene.prototype.getGeometryByID = function (id) {
  8723. for (var index = 0; index < this._geometries.length; index++) {
  8724. if (this._geometries[index].id === id) {
  8725. return this._geometries[index];
  8726. }
  8727. }
  8728. return null;
  8729. };
  8730. /**
  8731. * add a new geometry to this scene.
  8732. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8733. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8734. * @return {boolean} was the geometry added or not
  8735. */
  8736. Scene.prototype.pushGeometry = function (geometry, force) {
  8737. if (!force && this.getGeometryByID(geometry.id)) {
  8738. return false;
  8739. }
  8740. this._geometries.push(geometry);
  8741. return true;
  8742. };
  8743. Scene.prototype.getGeometries = function () {
  8744. return this._geometries;
  8745. };
  8746. /**
  8747. * Get a the first added mesh found of a given ID
  8748. * @param {string} id - the id to search for
  8749. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8750. */
  8751. Scene.prototype.getMeshByID = function (id) {
  8752. for (var index = 0; index < this.meshes.length; index++) {
  8753. if (this.meshes[index].id === id) {
  8754. return this.meshes[index];
  8755. }
  8756. }
  8757. return null;
  8758. };
  8759. /**
  8760. * Get a the last added mesh found of a given ID
  8761. * @param {string} id - the id to search for
  8762. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8763. */
  8764. Scene.prototype.getLastMeshByID = function (id) {
  8765. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8766. if (this.meshes[index].id === id) {
  8767. return this.meshes[index];
  8768. }
  8769. }
  8770. return null;
  8771. };
  8772. /**
  8773. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8774. * @param {string} id - the id to search for
  8775. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8776. */
  8777. Scene.prototype.getLastEntryByID = function (id) {
  8778. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8779. if (this.meshes[index].id === id) {
  8780. return this.meshes[index];
  8781. }
  8782. }
  8783. for (index = this.cameras.length - 1; index >= 0; index--) {
  8784. if (this.cameras[index].id === id) {
  8785. return this.cameras[index];
  8786. }
  8787. }
  8788. for (index = this.lights.length - 1; index >= 0; index--) {
  8789. if (this.lights[index].id === id) {
  8790. return this.lights[index];
  8791. }
  8792. }
  8793. return null;
  8794. };
  8795. Scene.prototype.getNodeByName = function (name) {
  8796. var mesh = this.getMeshByName(name);
  8797. if (mesh) {
  8798. return mesh;
  8799. }
  8800. var light = this.getLightByName(name);
  8801. if (light) {
  8802. return light;
  8803. }
  8804. return this.getCameraByName(name);
  8805. };
  8806. Scene.prototype.getMeshByName = function (name) {
  8807. for (var index = 0; index < this.meshes.length; index++) {
  8808. if (this.meshes[index].name === name) {
  8809. return this.meshes[index];
  8810. }
  8811. }
  8812. return null;
  8813. };
  8814. Scene.prototype.getSoundByName = function (name) {
  8815. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8816. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8817. return this.mainSoundTrack.soundCollection[index];
  8818. }
  8819. }
  8820. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8821. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8822. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8823. return this.soundTracks[sdIndex].soundCollection[index];
  8824. }
  8825. }
  8826. }
  8827. return null;
  8828. };
  8829. Scene.prototype.getLastSkeletonByID = function (id) {
  8830. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8831. if (this.skeletons[index].id === id) {
  8832. return this.skeletons[index];
  8833. }
  8834. }
  8835. return null;
  8836. };
  8837. Scene.prototype.getSkeletonById = function (id) {
  8838. for (var index = 0; index < this.skeletons.length; index++) {
  8839. if (this.skeletons[index].id === id) {
  8840. return this.skeletons[index];
  8841. }
  8842. }
  8843. return null;
  8844. };
  8845. Scene.prototype.getSkeletonByName = function (name) {
  8846. for (var index = 0; index < this.skeletons.length; index++) {
  8847. if (this.skeletons[index].name === name) {
  8848. return this.skeletons[index];
  8849. }
  8850. }
  8851. return null;
  8852. };
  8853. Scene.prototype.isActiveMesh = function (mesh) {
  8854. return (this._activeMeshes.indexOf(mesh) !== -1);
  8855. };
  8856. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8857. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8858. var material = subMesh.getMaterial();
  8859. if (mesh.showSubMeshesBoundingBox) {
  8860. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8861. }
  8862. if (material) {
  8863. // Render targets
  8864. if (material.getRenderTargetTextures) {
  8865. if (this._processedMaterials.indexOf(material) === -1) {
  8866. this._processedMaterials.push(material);
  8867. this._renderTargets.concat(material.getRenderTargetTextures());
  8868. }
  8869. }
  8870. // Dispatch
  8871. this._activeVertices += subMesh.indexCount;
  8872. this._renderingManager.dispatch(subMesh);
  8873. }
  8874. }
  8875. };
  8876. Scene.prototype._evaluateActiveMeshes = function () {
  8877. this.activeCamera._activeMeshes.reset();
  8878. this._activeMeshes.reset();
  8879. this._renderingManager.reset();
  8880. this._processedMaterials.reset();
  8881. this._activeParticleSystems.reset();
  8882. this._activeSkeletons.reset();
  8883. this._boundingBoxRenderer.reset();
  8884. if (!this._frustumPlanes) {
  8885. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8886. }
  8887. else {
  8888. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8889. }
  8890. // Meshes
  8891. var meshes;
  8892. var len;
  8893. if (this._selectionOctree) {
  8894. var selection = this._selectionOctree.select(this._frustumPlanes);
  8895. meshes = selection.data;
  8896. len = selection.length;
  8897. }
  8898. else {
  8899. len = this.meshes.length;
  8900. meshes = this.meshes;
  8901. }
  8902. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8903. var mesh = meshes[meshIndex];
  8904. if (mesh.isBlocked) {
  8905. continue;
  8906. }
  8907. this._totalVertices += mesh.getTotalVertices();
  8908. if (!mesh.isReady()) {
  8909. continue;
  8910. }
  8911. mesh.computeWorldMatrix();
  8912. // Intersections
  8913. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8914. this._meshesForIntersections.pushNoDuplicate(mesh);
  8915. }
  8916. // Switch to current LOD
  8917. var meshLOD = mesh.getLOD(this.activeCamera);
  8918. if (!meshLOD) {
  8919. continue;
  8920. }
  8921. mesh._preActivate();
  8922. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8923. this._activeMeshes.push(mesh);
  8924. this.activeCamera._activeMeshes.push(mesh);
  8925. mesh._activate(this._renderId);
  8926. this._activeMesh(meshLOD);
  8927. }
  8928. }
  8929. // Particle systems
  8930. var beforeParticlesDate = BABYLON.Tools.Now;
  8931. if (this.particlesEnabled) {
  8932. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8933. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8934. var particleSystem = this.particleSystems[particleIndex];
  8935. if (!particleSystem.isStarted()) {
  8936. continue;
  8937. }
  8938. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8939. this._activeParticleSystems.push(particleSystem);
  8940. particleSystem.animate();
  8941. }
  8942. }
  8943. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8944. }
  8945. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8946. };
  8947. Scene.prototype._activeMesh = function (mesh) {
  8948. if (mesh.skeleton && this.skeletonsEnabled) {
  8949. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8950. }
  8951. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8952. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8953. }
  8954. if (mesh && mesh.subMeshes) {
  8955. // Submeshes Octrees
  8956. var len;
  8957. var subMeshes;
  8958. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8959. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8960. len = intersections.length;
  8961. subMeshes = intersections.data;
  8962. }
  8963. else {
  8964. subMeshes = mesh.subMeshes;
  8965. len = subMeshes.length;
  8966. }
  8967. for (var subIndex = 0; subIndex < len; subIndex++) {
  8968. var subMesh = subMeshes[subIndex];
  8969. this._evaluateSubMesh(subMesh, mesh);
  8970. }
  8971. }
  8972. };
  8973. Scene.prototype.updateTransformMatrix = function (force) {
  8974. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8975. };
  8976. Scene.prototype._renderForCamera = function (camera) {
  8977. var engine = this._engine;
  8978. this.activeCamera = camera;
  8979. if (!this.activeCamera)
  8980. throw new Error("Active camera not set");
  8981. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8982. // Viewport
  8983. engine.setViewport(this.activeCamera.viewport);
  8984. // Camera
  8985. this._renderId++;
  8986. this.updateTransformMatrix();
  8987. if (this.beforeCameraRender) {
  8988. this.beforeCameraRender(this.activeCamera);
  8989. }
  8990. // Meshes
  8991. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8992. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8993. this._evaluateActiveMeshes();
  8994. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8995. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8996. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8997. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8998. skeleton.prepare();
  8999. }
  9000. // Render targets
  9001. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9002. if (this.renderTargetsEnabled) {
  9003. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9004. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  9005. var renderTarget = this._renderTargets.data[renderIndex];
  9006. if (renderTarget._shouldRender()) {
  9007. this._renderId++;
  9008. renderTarget.render(false, this.dumpNextRenderTargets);
  9009. }
  9010. }
  9011. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9012. this._renderId++;
  9013. }
  9014. if (this._renderTargets.length > 0) {
  9015. engine.restoreDefaultFramebuffer();
  9016. }
  9017. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9018. // Prepare Frame
  9019. this.postProcessManager._prepareFrame();
  9020. var beforeRenderDate = BABYLON.Tools.Now;
  9021. // Backgrounds
  9022. if (this.layers.length) {
  9023. engine.setDepthBuffer(false);
  9024. var layerIndex;
  9025. var layer;
  9026. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9027. layer = this.layers[layerIndex];
  9028. if (layer.isBackground) {
  9029. layer.render();
  9030. }
  9031. }
  9032. engine.setDepthBuffer(true);
  9033. }
  9034. // Render
  9035. BABYLON.Tools.StartPerformanceCounter("Main render");
  9036. this._renderingManager.render(null, null, true, true);
  9037. BABYLON.Tools.EndPerformanceCounter("Main render");
  9038. // Bounding boxes
  9039. this._boundingBoxRenderer.render();
  9040. // Lens flares
  9041. if (this.lensFlaresEnabled) {
  9042. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9043. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  9044. this.lensFlareSystems[lensFlareSystemIndex].render();
  9045. }
  9046. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9047. }
  9048. // Foregrounds
  9049. if (this.layers.length) {
  9050. engine.setDepthBuffer(false);
  9051. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9052. layer = this.layers[layerIndex];
  9053. if (!layer.isBackground) {
  9054. layer.render();
  9055. }
  9056. }
  9057. engine.setDepthBuffer(true);
  9058. }
  9059. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  9060. // Finalize frame
  9061. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  9062. // Update camera
  9063. this.activeCamera._updateFromScene();
  9064. // Reset some special arrays
  9065. this._renderTargets.reset();
  9066. if (this.afterCameraRender) {
  9067. this.afterCameraRender(this.activeCamera);
  9068. }
  9069. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9070. };
  9071. Scene.prototype._processSubCameras = function (camera) {
  9072. if (camera.subCameras.length === 0) {
  9073. this._renderForCamera(camera);
  9074. return;
  9075. }
  9076. for (var index = 0; index < camera.subCameras.length; index++) {
  9077. this._renderForCamera(camera.subCameras[index]);
  9078. }
  9079. this.activeCamera = camera;
  9080. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  9081. // Update camera
  9082. this.activeCamera._updateFromScene();
  9083. };
  9084. Scene.prototype._checkIntersections = function () {
  9085. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  9086. var sourceMesh = this._meshesForIntersections.data[index];
  9087. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  9088. var action = sourceMesh.actionManager.actions[actionIndex];
  9089. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9090. var parameters = action.getTriggerParameter();
  9091. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  9092. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  9093. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9094. if (areIntersecting && currentIntersectionInProgress === -1) {
  9095. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  9096. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9097. sourceMesh._intersectionsInProgress.push(otherMesh);
  9098. }
  9099. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9100. sourceMesh._intersectionsInProgress.push(otherMesh);
  9101. }
  9102. }
  9103. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9104. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9105. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9106. if (indexOfOther > -1) {
  9107. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  9108. }
  9109. }
  9110. }
  9111. }
  9112. }
  9113. };
  9114. Scene.prototype.render = function () {
  9115. var startDate = BABYLON.Tools.Now;
  9116. this._particlesDuration = 0;
  9117. this._spritesDuration = 0;
  9118. this._activeParticles = 0;
  9119. this._renderDuration = 0;
  9120. this._renderTargetsDuration = 0;
  9121. this._evaluateActiveMeshesDuration = 0;
  9122. this._totalVertices = 0;
  9123. this._activeVertices = 0;
  9124. this._activeBones = 0;
  9125. this.getEngine().resetDrawCalls();
  9126. this._meshesForIntersections.reset();
  9127. this.resetCachedMaterial();
  9128. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  9129. // Actions
  9130. if (this.actionManager) {
  9131. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  9132. }
  9133. //Simplification Queue
  9134. if (!this.simplificationQueue.running) {
  9135. this.simplificationQueue.executeNext();
  9136. }
  9137. // Before render
  9138. if (this.beforeRender) {
  9139. this.beforeRender();
  9140. }
  9141. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9142. this._onBeforeRenderCallbacks[callbackIndex]();
  9143. }
  9144. // Animations
  9145. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  9146. this._animationRatio = deltaTime * (60.0 / 1000.0);
  9147. this._animate();
  9148. // Physics
  9149. if (this._physicsEngine) {
  9150. BABYLON.Tools.StartPerformanceCounter("Physics");
  9151. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  9152. BABYLON.Tools.EndPerformanceCounter("Physics");
  9153. }
  9154. // Customs render targets
  9155. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9156. var engine = this.getEngine();
  9157. var currentActiveCamera = this.activeCamera;
  9158. if (this.renderTargetsEnabled) {
  9159. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9160. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  9161. var renderTarget = this.customRenderTargets[customIndex];
  9162. if (renderTarget._shouldRender()) {
  9163. this._renderId++;
  9164. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  9165. if (!this.activeCamera)
  9166. throw new Error("Active camera not set");
  9167. // Viewport
  9168. engine.setViewport(this.activeCamera.viewport);
  9169. // Camera
  9170. this.updateTransformMatrix();
  9171. renderTarget.render(false, this.dumpNextRenderTargets);
  9172. }
  9173. }
  9174. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9175. this._renderId++;
  9176. }
  9177. if (this.customRenderTargets.length > 0) {
  9178. engine.restoreDefaultFramebuffer();
  9179. }
  9180. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9181. this.activeCamera = currentActiveCamera;
  9182. // Procedural textures
  9183. if (this.proceduralTexturesEnabled) {
  9184. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9185. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  9186. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  9187. if (proceduralTexture._shouldRender()) {
  9188. proceduralTexture.render();
  9189. }
  9190. }
  9191. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9192. }
  9193. // Clear
  9194. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  9195. // Shadows
  9196. if (this.shadowsEnabled) {
  9197. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  9198. var light = this.lights[lightIndex];
  9199. var shadowGenerator = light.getShadowGenerator();
  9200. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  9201. this._renderTargets.push(shadowGenerator.getShadowMap());
  9202. }
  9203. }
  9204. }
  9205. // Depth renderer
  9206. if (this._depthRenderer) {
  9207. this._renderTargets.push(this._depthRenderer.getDepthMap());
  9208. }
  9209. // RenderPipeline
  9210. this.postProcessRenderPipelineManager.update();
  9211. // Multi-cameras?
  9212. if (this.activeCameras.length > 0) {
  9213. var currentRenderId = this._renderId;
  9214. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  9215. this._renderId = currentRenderId;
  9216. this._processSubCameras(this.activeCameras[cameraIndex]);
  9217. }
  9218. }
  9219. else {
  9220. if (!this.activeCamera) {
  9221. throw new Error("No camera defined");
  9222. }
  9223. this._processSubCameras(this.activeCamera);
  9224. }
  9225. // Intersection checks
  9226. this._checkIntersections();
  9227. // Update the audio listener attached to the camera
  9228. this._updateAudioParameters();
  9229. // After render
  9230. if (this.afterRender) {
  9231. this.afterRender();
  9232. }
  9233. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9234. this._onAfterRenderCallbacks[callbackIndex]();
  9235. }
  9236. for (var index = 0; index < this._toBeDisposed.length; index++) {
  9237. this._toBeDisposed.data[index].dispose();
  9238. this._toBeDisposed[index] = null;
  9239. }
  9240. this._toBeDisposed.reset();
  9241. if (this.dumpNextRenderTargets) {
  9242. this.dumpNextRenderTargets = false;
  9243. }
  9244. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  9245. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  9246. };
  9247. Scene.prototype._updateAudioParameters = function () {
  9248. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  9249. return;
  9250. }
  9251. var listeningCamera;
  9252. var audioEngine = BABYLON.Engine.audioEngine;
  9253. if (this.activeCameras.length > 0) {
  9254. listeningCamera = this.activeCameras[0];
  9255. }
  9256. else {
  9257. listeningCamera = this.activeCamera;
  9258. }
  9259. if (listeningCamera && audioEngine.canUseWebAudio) {
  9260. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  9261. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  9262. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  9263. cameraDirection.normalize();
  9264. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  9265. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9266. var sound = this.mainSoundTrack.soundCollection[i];
  9267. if (sound.useCustomAttenuation) {
  9268. sound.updateDistanceFromListener();
  9269. }
  9270. }
  9271. for (i = 0; i < this.soundTracks.length; i++) {
  9272. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9273. sound = this.soundTracks[i].soundCollection[j];
  9274. if (sound.useCustomAttenuation) {
  9275. sound.updateDistanceFromListener();
  9276. }
  9277. }
  9278. }
  9279. }
  9280. };
  9281. Object.defineProperty(Scene.prototype, "audioEnabled", {
  9282. // Audio
  9283. get: function () {
  9284. return this._audioEnabled;
  9285. },
  9286. set: function (value) {
  9287. this._audioEnabled = value;
  9288. if (this._audioEnabled) {
  9289. this._enableAudio();
  9290. }
  9291. else {
  9292. this._disableAudio();
  9293. }
  9294. },
  9295. enumerable: true,
  9296. configurable: true
  9297. });
  9298. Scene.prototype._disableAudio = function () {
  9299. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9300. this.mainSoundTrack.soundCollection[i].pause();
  9301. }
  9302. for (i = 0; i < this.soundTracks.length; i++) {
  9303. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9304. this.soundTracks[i].soundCollection[j].pause();
  9305. }
  9306. }
  9307. };
  9308. Scene.prototype._enableAudio = function () {
  9309. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9310. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  9311. this.mainSoundTrack.soundCollection[i].play();
  9312. }
  9313. }
  9314. for (i = 0; i < this.soundTracks.length; i++) {
  9315. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9316. if (this.soundTracks[i].soundCollection[j].isPaused) {
  9317. this.soundTracks[i].soundCollection[j].play();
  9318. }
  9319. }
  9320. }
  9321. };
  9322. Object.defineProperty(Scene.prototype, "headphone", {
  9323. get: function () {
  9324. return this._headphone;
  9325. },
  9326. set: function (value) {
  9327. this._headphone = value;
  9328. if (this._headphone) {
  9329. this._switchAudioModeForHeadphones();
  9330. }
  9331. else {
  9332. this._switchAudioModeForNormalSpeakers();
  9333. }
  9334. },
  9335. enumerable: true,
  9336. configurable: true
  9337. });
  9338. Scene.prototype._switchAudioModeForHeadphones = function () {
  9339. this.mainSoundTrack.switchPanningModelToHRTF();
  9340. for (var i = 0; i < this.soundTracks.length; i++) {
  9341. this.soundTracks[i].switchPanningModelToHRTF();
  9342. }
  9343. };
  9344. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  9345. this.mainSoundTrack.switchPanningModelToEqualPower();
  9346. for (var i = 0; i < this.soundTracks.length; i++) {
  9347. this.soundTracks[i].switchPanningModelToEqualPower();
  9348. }
  9349. };
  9350. Scene.prototype.enableDepthRenderer = function () {
  9351. if (this._depthRenderer) {
  9352. return this._depthRenderer;
  9353. }
  9354. this._depthRenderer = new BABYLON.DepthRenderer(this);
  9355. return this._depthRenderer;
  9356. };
  9357. Scene.prototype.disableDepthRenderer = function () {
  9358. if (!this._depthRenderer) {
  9359. return;
  9360. }
  9361. this._depthRenderer.dispose();
  9362. this._depthRenderer = null;
  9363. };
  9364. Scene.prototype.dispose = function () {
  9365. this.beforeRender = null;
  9366. this.afterRender = null;
  9367. this.skeletons = [];
  9368. this._boundingBoxRenderer.dispose();
  9369. if (this._depthRenderer) {
  9370. this._depthRenderer.dispose();
  9371. }
  9372. // Debug layer
  9373. this.debugLayer.hide();
  9374. // Events
  9375. if (this.onDispose) {
  9376. this.onDispose();
  9377. }
  9378. this._onBeforeRenderCallbacks = [];
  9379. this._onAfterRenderCallbacks = [];
  9380. this.detachControl();
  9381. // Release sounds & sounds tracks
  9382. this.disposeSounds();
  9383. // Detach cameras
  9384. var canvas = this._engine.getRenderingCanvas();
  9385. var index;
  9386. for (index = 0; index < this.cameras.length; index++) {
  9387. this.cameras[index].detachControl(canvas);
  9388. }
  9389. while (this.lights.length) {
  9390. this.lights[0].dispose();
  9391. }
  9392. while (this.meshes.length) {
  9393. this.meshes[0].dispose(true);
  9394. }
  9395. while (this.cameras.length) {
  9396. this.cameras[0].dispose();
  9397. }
  9398. while (this.materials.length) {
  9399. this.materials[0].dispose();
  9400. }
  9401. while (this.particleSystems.length) {
  9402. this.particleSystems[0].dispose();
  9403. }
  9404. while (this.spriteManagers.length) {
  9405. this.spriteManagers[0].dispose();
  9406. }
  9407. while (this.layers.length) {
  9408. this.layers[0].dispose();
  9409. }
  9410. while (this.textures.length) {
  9411. this.textures[0].dispose();
  9412. }
  9413. // Post-processes
  9414. this.postProcessManager.dispose();
  9415. // Physics
  9416. if (this._physicsEngine) {
  9417. this.disablePhysicsEngine();
  9418. }
  9419. // Remove from engine
  9420. index = this._engine.scenes.indexOf(this);
  9421. if (index > -1) {
  9422. this._engine.scenes.splice(index, 1);
  9423. }
  9424. this._engine.wipeCaches();
  9425. };
  9426. // Release sounds & sounds tracks
  9427. Scene.prototype.disposeSounds = function () {
  9428. this.mainSoundTrack.dispose();
  9429. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  9430. this.soundTracks[scIndex].dispose();
  9431. }
  9432. };
  9433. // Collisions
  9434. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9435. if (excludedMesh === void 0) { excludedMesh = null; }
  9436. position.divideToRef(collider.radius, this._scaledPosition);
  9437. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9438. collider.retry = 0;
  9439. collider.initialVelocity = this._scaledVelocity;
  9440. collider.initialPosition = this._scaledPosition;
  9441. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  9442. finalPosition.multiplyInPlace(collider.radius);
  9443. };
  9444. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9445. if (excludedMesh === void 0) { excludedMesh = null; }
  9446. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9447. if (collider.retry >= maximumRetry) {
  9448. finalPosition.copyFrom(position);
  9449. return;
  9450. }
  9451. collider._initialize(position, velocity, closeDistance);
  9452. for (var index = 0; index < this.meshes.length; index++) {
  9453. var mesh = this.meshes[index];
  9454. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9455. mesh._checkCollision(collider);
  9456. }
  9457. }
  9458. if (!collider.collisionFound) {
  9459. position.addToRef(velocity, finalPosition);
  9460. return;
  9461. }
  9462. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9463. collider._getResponse(position, velocity);
  9464. }
  9465. if (velocity.length() <= closeDistance) {
  9466. finalPosition.copyFrom(position);
  9467. return;
  9468. }
  9469. collider.retry++;
  9470. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9471. };
  9472. // Octrees
  9473. Scene.prototype.getWorldExtends = function () {
  9474. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9475. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9476. for (var index = 0; index < this.meshes.length; index++) {
  9477. var mesh = this.meshes[index];
  9478. mesh.computeWorldMatrix(true);
  9479. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  9480. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  9481. BABYLON.Tools.CheckExtends(minBox, min, max);
  9482. BABYLON.Tools.CheckExtends(maxBox, min, max);
  9483. }
  9484. return {
  9485. min: min,
  9486. max: max
  9487. };
  9488. };
  9489. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  9490. if (maxCapacity === void 0) { maxCapacity = 64; }
  9491. if (maxDepth === void 0) { maxDepth = 2; }
  9492. if (!this._selectionOctree) {
  9493. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  9494. }
  9495. var worldExtends = this.getWorldExtends();
  9496. // Update octree
  9497. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  9498. return this._selectionOctree;
  9499. };
  9500. // Picking
  9501. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  9502. var engine = this._engine;
  9503. if (!camera) {
  9504. if (!this.activeCamera)
  9505. throw new Error("Active camera not set");
  9506. camera = this.activeCamera;
  9507. }
  9508. var cameraViewport = camera.viewport;
  9509. var viewport = cameraViewport.toGlobal(engine);
  9510. // Moving coordinates to local viewport world
  9511. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  9512. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  9513. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9514. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9515. };
  9516. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  9517. var pickingInfo = null;
  9518. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  9519. var mesh = this.meshes[meshIndex];
  9520. if (predicate) {
  9521. if (!predicate(mesh)) {
  9522. continue;
  9523. }
  9524. }
  9525. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  9526. continue;
  9527. }
  9528. var world = mesh.getWorldMatrix();
  9529. var ray = rayFunction(world);
  9530. var result = mesh.intersects(ray, fastCheck);
  9531. if (!result || !result.hit)
  9532. continue;
  9533. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  9534. continue;
  9535. pickingInfo = result;
  9536. if (fastCheck) {
  9537. break;
  9538. }
  9539. }
  9540. return pickingInfo || new BABYLON.PickingInfo();
  9541. };
  9542. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  9543. var _this = this;
  9544. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  9545. /// <param name="x">X position on screen</param>
  9546. /// <param name="y">Y position on screen</param>
  9547. /// <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>
  9548. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  9549. /// <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>
  9550. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  9551. };
  9552. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  9553. var _this = this;
  9554. return this._internalPick(function (world) {
  9555. if (!_this._pickWithRayInverseMatrix) {
  9556. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  9557. }
  9558. world.invertToRef(_this._pickWithRayInverseMatrix);
  9559. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9560. }, predicate, fastCheck);
  9561. };
  9562. Scene.prototype.setPointerOverMesh = function (mesh) {
  9563. if (this._pointerOverMesh === mesh) {
  9564. return;
  9565. }
  9566. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9567. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9568. }
  9569. this._pointerOverMesh = mesh;
  9570. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9571. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9572. }
  9573. };
  9574. Scene.prototype.getPointerOverMesh = function () {
  9575. return this._pointerOverMesh;
  9576. };
  9577. // Physics
  9578. Scene.prototype.getPhysicsEngine = function () {
  9579. return this._physicsEngine;
  9580. };
  9581. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9582. if (this._physicsEngine) {
  9583. return true;
  9584. }
  9585. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9586. if (!this._physicsEngine.isSupported()) {
  9587. this._physicsEngine = null;
  9588. return false;
  9589. }
  9590. this._physicsEngine._initialize(gravity);
  9591. return true;
  9592. };
  9593. Scene.prototype.disablePhysicsEngine = function () {
  9594. if (!this._physicsEngine) {
  9595. return;
  9596. }
  9597. this._physicsEngine.dispose();
  9598. this._physicsEngine = undefined;
  9599. };
  9600. Scene.prototype.isPhysicsEnabled = function () {
  9601. return this._physicsEngine !== undefined;
  9602. };
  9603. Scene.prototype.setGravity = function (gravity) {
  9604. if (!this._physicsEngine) {
  9605. return;
  9606. }
  9607. this._physicsEngine._setGravity(gravity);
  9608. };
  9609. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9610. if (parts.parts) {
  9611. options = parts;
  9612. parts = parts.parts;
  9613. }
  9614. if (!this._physicsEngine) {
  9615. return null;
  9616. }
  9617. for (var index = 0; index < parts.length; index++) {
  9618. var mesh = parts[index].mesh;
  9619. mesh._physicImpostor = parts[index].impostor;
  9620. mesh._physicsMass = options.mass / parts.length;
  9621. mesh._physicsFriction = options.friction;
  9622. mesh._physicRestitution = options.restitution;
  9623. }
  9624. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9625. };
  9626. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9627. for (var index = 0; index < compound.parts.length; index++) {
  9628. var mesh = compound.parts[index].mesh;
  9629. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9630. this._physicsEngine._unregisterMesh(mesh);
  9631. }
  9632. };
  9633. // Misc.
  9634. Scene.prototype.createDefaultCameraOrLight = function () {
  9635. // Light
  9636. if (this.lights.length === 0) {
  9637. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9638. }
  9639. // Camera
  9640. if (!this.activeCamera) {
  9641. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9642. // Compute position
  9643. var worldExtends = this.getWorldExtends();
  9644. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9645. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9646. camera.setTarget(worldCenter);
  9647. this.activeCamera = camera;
  9648. }
  9649. };
  9650. // Tags
  9651. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9652. if (tagsQuery === undefined) {
  9653. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9654. return list;
  9655. }
  9656. var listByTags = [];
  9657. forEach = forEach || (function (item) {
  9658. return;
  9659. });
  9660. for (var i in list) {
  9661. var item = list[i];
  9662. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9663. listByTags.push(item);
  9664. forEach(item);
  9665. }
  9666. }
  9667. return listByTags;
  9668. };
  9669. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9670. return this._getByTags(this.meshes, tagsQuery, forEach);
  9671. };
  9672. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9673. return this._getByTags(this.cameras, tagsQuery, forEach);
  9674. };
  9675. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9676. return this._getByTags(this.lights, tagsQuery, forEach);
  9677. };
  9678. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9679. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9680. };
  9681. // Statics
  9682. Scene._FOGMODE_NONE = 0;
  9683. Scene._FOGMODE_EXP = 1;
  9684. Scene._FOGMODE_EXP2 = 2;
  9685. Scene._FOGMODE_LINEAR = 3;
  9686. Scene.MinDeltaTime = 1.0;
  9687. Scene.MaxDeltaTime = 1000.0;
  9688. return Scene;
  9689. })();
  9690. BABYLON.Scene = Scene;
  9691. })(BABYLON || (BABYLON = {}));
  9692. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9693. (function (BABYLON) {
  9694. var VertexBuffer = (function () {
  9695. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9696. if (engine instanceof BABYLON.Mesh) {
  9697. this._engine = engine.getScene().getEngine();
  9698. }
  9699. else {
  9700. this._engine = engine;
  9701. }
  9702. this._updatable = updatable;
  9703. this._data = data;
  9704. if (!postponeInternalCreation) {
  9705. this.create();
  9706. }
  9707. this._kind = kind;
  9708. if (stride) {
  9709. this._strideSize = stride;
  9710. return;
  9711. }
  9712. switch (kind) {
  9713. case VertexBuffer.PositionKind:
  9714. this._strideSize = 3;
  9715. break;
  9716. case VertexBuffer.NormalKind:
  9717. this._strideSize = 3;
  9718. break;
  9719. case VertexBuffer.UVKind:
  9720. this._strideSize = 2;
  9721. break;
  9722. case VertexBuffer.UV2Kind:
  9723. this._strideSize = 2;
  9724. break;
  9725. case VertexBuffer.ColorKind:
  9726. this._strideSize = 4;
  9727. break;
  9728. case VertexBuffer.MatricesIndicesKind:
  9729. this._strideSize = 4;
  9730. break;
  9731. case VertexBuffer.MatricesWeightsKind:
  9732. this._strideSize = 4;
  9733. break;
  9734. }
  9735. }
  9736. // Properties
  9737. VertexBuffer.prototype.isUpdatable = function () {
  9738. return this._updatable;
  9739. };
  9740. VertexBuffer.prototype.getData = function () {
  9741. return this._data;
  9742. };
  9743. VertexBuffer.prototype.getBuffer = function () {
  9744. return this._buffer;
  9745. };
  9746. VertexBuffer.prototype.getStrideSize = function () {
  9747. return this._strideSize;
  9748. };
  9749. // Methods
  9750. VertexBuffer.prototype.create = function (data) {
  9751. if (!data && this._buffer) {
  9752. return; // nothing to do
  9753. }
  9754. data = data || this._data;
  9755. if (!this._buffer) {
  9756. if (this._updatable) {
  9757. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9758. }
  9759. else {
  9760. this._buffer = this._engine.createVertexBuffer(data);
  9761. }
  9762. }
  9763. if (this._updatable) {
  9764. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9765. this._data = data;
  9766. }
  9767. };
  9768. VertexBuffer.prototype.update = function (data) {
  9769. this.create(data);
  9770. };
  9771. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9772. if (!this._buffer) {
  9773. return;
  9774. }
  9775. if (this._updatable) {
  9776. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9777. this._data = null;
  9778. }
  9779. };
  9780. VertexBuffer.prototype.dispose = function () {
  9781. if (!this._buffer) {
  9782. return;
  9783. }
  9784. if (this._engine._releaseBuffer(this._buffer)) {
  9785. this._buffer = null;
  9786. }
  9787. };
  9788. Object.defineProperty(VertexBuffer, "PositionKind", {
  9789. get: function () {
  9790. return VertexBuffer._PositionKind;
  9791. },
  9792. enumerable: true,
  9793. configurable: true
  9794. });
  9795. Object.defineProperty(VertexBuffer, "NormalKind", {
  9796. get: function () {
  9797. return VertexBuffer._NormalKind;
  9798. },
  9799. enumerable: true,
  9800. configurable: true
  9801. });
  9802. Object.defineProperty(VertexBuffer, "UVKind", {
  9803. get: function () {
  9804. return VertexBuffer._UVKind;
  9805. },
  9806. enumerable: true,
  9807. configurable: true
  9808. });
  9809. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9810. get: function () {
  9811. return VertexBuffer._UV2Kind;
  9812. },
  9813. enumerable: true,
  9814. configurable: true
  9815. });
  9816. Object.defineProperty(VertexBuffer, "ColorKind", {
  9817. get: function () {
  9818. return VertexBuffer._ColorKind;
  9819. },
  9820. enumerable: true,
  9821. configurable: true
  9822. });
  9823. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9824. get: function () {
  9825. return VertexBuffer._MatricesIndicesKind;
  9826. },
  9827. enumerable: true,
  9828. configurable: true
  9829. });
  9830. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9831. get: function () {
  9832. return VertexBuffer._MatricesWeightsKind;
  9833. },
  9834. enumerable: true,
  9835. configurable: true
  9836. });
  9837. // Enums
  9838. VertexBuffer._PositionKind = "position";
  9839. VertexBuffer._NormalKind = "normal";
  9840. VertexBuffer._UVKind = "uv";
  9841. VertexBuffer._UV2Kind = "uv2";
  9842. VertexBuffer._ColorKind = "color";
  9843. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9844. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9845. return VertexBuffer;
  9846. })();
  9847. BABYLON.VertexBuffer = VertexBuffer;
  9848. })(BABYLON || (BABYLON = {}));
  9849. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9850. var BABYLON;
  9851. (function (BABYLON) {
  9852. var AbstractMesh = (function (_super) {
  9853. __extends(AbstractMesh, _super);
  9854. function AbstractMesh(name, scene) {
  9855. _super.call(this, name, scene);
  9856. // Properties
  9857. this.definedFacingForward = true; // orientation for POV movement & rotation
  9858. this.position = new BABYLON.Vector3(0, 0, 0);
  9859. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9860. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9861. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9862. this.visibility = 1.0;
  9863. this.alphaIndex = Number.MAX_VALUE;
  9864. this.infiniteDistance = false;
  9865. this.isVisible = true;
  9866. this.isPickable = true;
  9867. this.showBoundingBox = false;
  9868. this.showSubMeshesBoundingBox = false;
  9869. this.onDispose = null;
  9870. this.checkCollisions = false;
  9871. this.isBlocker = false;
  9872. this.renderingGroupId = 0;
  9873. this.receiveShadows = false;
  9874. this.renderOutline = false;
  9875. this.outlineColor = BABYLON.Color3.Red();
  9876. this.outlineWidth = 0.02;
  9877. this.renderOverlay = false;
  9878. this.overlayColor = BABYLON.Color3.Red();
  9879. this.overlayAlpha = 0.5;
  9880. this.hasVertexAlpha = false;
  9881. this.useVertexColors = true;
  9882. this.applyFog = true;
  9883. this.useOctreeForRenderingSelection = true;
  9884. this.useOctreeForPicking = true;
  9885. this.useOctreeForCollisions = true;
  9886. this.layerMask = 0xFFFFFFFF;
  9887. // Physics
  9888. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9889. // Collisions
  9890. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9891. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9892. this._collider = new BABYLON.Collider();
  9893. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9894. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9895. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9896. // Cache
  9897. this._localScaling = BABYLON.Matrix.Zero();
  9898. this._localRotation = BABYLON.Matrix.Zero();
  9899. this._localTranslation = BABYLON.Matrix.Zero();
  9900. this._localBillboard = BABYLON.Matrix.Zero();
  9901. this._localPivotScaling = BABYLON.Matrix.Zero();
  9902. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9903. this._localWorld = BABYLON.Matrix.Zero();
  9904. this._worldMatrix = BABYLON.Matrix.Zero();
  9905. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9906. this._absolutePosition = BABYLON.Vector3.Zero();
  9907. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9908. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9909. this._isDirty = false;
  9910. this._pivotMatrix = BABYLON.Matrix.Identity();
  9911. this._isDisposed = false;
  9912. this._renderId = 0;
  9913. this._intersectionsInProgress = new Array();
  9914. this._onAfterWorldMatrixUpdate = new Array();
  9915. scene.addMesh(this);
  9916. }
  9917. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9918. get: function () {
  9919. return AbstractMesh._BILLBOARDMODE_NONE;
  9920. },
  9921. enumerable: true,
  9922. configurable: true
  9923. });
  9924. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9925. get: function () {
  9926. return AbstractMesh._BILLBOARDMODE_X;
  9927. },
  9928. enumerable: true,
  9929. configurable: true
  9930. });
  9931. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9932. get: function () {
  9933. return AbstractMesh._BILLBOARDMODE_Y;
  9934. },
  9935. enumerable: true,
  9936. configurable: true
  9937. });
  9938. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9939. get: function () {
  9940. return AbstractMesh._BILLBOARDMODE_Z;
  9941. },
  9942. enumerable: true,
  9943. configurable: true
  9944. });
  9945. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9946. get: function () {
  9947. return AbstractMesh._BILLBOARDMODE_ALL;
  9948. },
  9949. enumerable: true,
  9950. configurable: true
  9951. });
  9952. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9953. // Methods
  9954. get: function () {
  9955. return false;
  9956. },
  9957. enumerable: true,
  9958. configurable: true
  9959. });
  9960. AbstractMesh.prototype.getLOD = function (camera) {
  9961. return this;
  9962. };
  9963. AbstractMesh.prototype.getTotalVertices = function () {
  9964. return 0;
  9965. };
  9966. AbstractMesh.prototype.getIndices = function () {
  9967. return null;
  9968. };
  9969. AbstractMesh.prototype.getVerticesData = function (kind) {
  9970. return null;
  9971. };
  9972. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9973. return false;
  9974. };
  9975. AbstractMesh.prototype.getBoundingInfo = function () {
  9976. if (this._masterMesh) {
  9977. return this._masterMesh.getBoundingInfo();
  9978. }
  9979. if (!this._boundingInfo) {
  9980. this._updateBoundingInfo();
  9981. }
  9982. return this._boundingInfo;
  9983. };
  9984. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9985. get: function () {
  9986. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9987. },
  9988. enumerable: true,
  9989. configurable: true
  9990. });
  9991. AbstractMesh.prototype._preActivate = function () {
  9992. };
  9993. AbstractMesh.prototype._activate = function (renderId) {
  9994. this._renderId = renderId;
  9995. };
  9996. AbstractMesh.prototype.getWorldMatrix = function () {
  9997. if (this._masterMesh) {
  9998. return this._masterMesh.getWorldMatrix();
  9999. }
  10000. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10001. this.computeWorldMatrix();
  10002. }
  10003. return this._worldMatrix;
  10004. };
  10005. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10006. get: function () {
  10007. return this._worldMatrix;
  10008. },
  10009. enumerable: true,
  10010. configurable: true
  10011. });
  10012. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10013. get: function () {
  10014. return this._absolutePosition;
  10015. },
  10016. enumerable: true,
  10017. configurable: true
  10018. });
  10019. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10020. if (!this.rotationQuaternion) {
  10021. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10022. this.rotation = BABYLON.Vector3.Zero();
  10023. }
  10024. if (!space || space === 0 /* LOCAL */) {
  10025. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10026. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  10027. }
  10028. else {
  10029. if (this.parent) {
  10030. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10031. invertParentWorldMatrix.invert();
  10032. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10033. }
  10034. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10035. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  10036. }
  10037. };
  10038. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10039. var displacementVector = axis.scale(distance);
  10040. if (!space || space === 0 /* LOCAL */) {
  10041. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10042. this.setPositionWithLocalVector(tempV3);
  10043. }
  10044. else {
  10045. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10046. }
  10047. };
  10048. AbstractMesh.prototype.getAbsolutePosition = function () {
  10049. this.computeWorldMatrix();
  10050. return this._absolutePosition;
  10051. };
  10052. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10053. if (!absolutePosition) {
  10054. return;
  10055. }
  10056. var absolutePositionX;
  10057. var absolutePositionY;
  10058. var absolutePositionZ;
  10059. if (absolutePosition.x === undefined) {
  10060. if (arguments.length < 3) {
  10061. return;
  10062. }
  10063. absolutePositionX = arguments[0];
  10064. absolutePositionY = arguments[1];
  10065. absolutePositionZ = arguments[2];
  10066. }
  10067. else {
  10068. absolutePositionX = absolutePosition.x;
  10069. absolutePositionY = absolutePosition.y;
  10070. absolutePositionZ = absolutePosition.z;
  10071. }
  10072. if (this.parent) {
  10073. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10074. invertParentWorldMatrix.invert();
  10075. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10076. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10077. }
  10078. else {
  10079. this.position.x = absolutePositionX;
  10080. this.position.y = absolutePositionY;
  10081. this.position.z = absolutePositionZ;
  10082. }
  10083. };
  10084. // ================================== Point of View Movement =================================
  10085. /**
  10086. * Perform relative position change from the point of view of behind the front of the mesh.
  10087. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10088. * Supports definition of mesh facing forward or backward.
  10089. * @param {number} amountRight
  10090. * @param {number} amountUp
  10091. * @param {number} amountForward
  10092. */
  10093. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10094. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10095. };
  10096. /**
  10097. * Calculate relative position change from the point of view of behind the front of the mesh.
  10098. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10099. * Supports definition of mesh facing forward or backward.
  10100. * @param {number} amountRight
  10101. * @param {number} amountUp
  10102. * @param {number} amountForward
  10103. */
  10104. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10105. var rotMatrix = new BABYLON.Matrix();
  10106. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10107. rotQuaternion.toRotationMatrix(rotMatrix);
  10108. var translationDelta = BABYLON.Vector3.Zero();
  10109. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10110. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10111. return translationDelta;
  10112. };
  10113. // ================================== Point of View Rotation =================================
  10114. /**
  10115. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10116. * Supports definition of mesh facing forward or backward.
  10117. * @param {number} flipBack
  10118. * @param {number} twirlClockwise
  10119. * @param {number} tiltRight
  10120. */
  10121. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10122. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10123. };
  10124. /**
  10125. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10126. * Supports definition of mesh facing forward or backward.
  10127. * @param {number} flipBack
  10128. * @param {number} twirlClockwise
  10129. * @param {number} tiltRight
  10130. */
  10131. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10132. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10133. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10134. };
  10135. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10136. this._pivotMatrix = matrix;
  10137. this._cache.pivotMatrixUpdated = true;
  10138. };
  10139. AbstractMesh.prototype.getPivotMatrix = function () {
  10140. return this._pivotMatrix;
  10141. };
  10142. AbstractMesh.prototype._isSynchronized = function () {
  10143. if (this._isDirty) {
  10144. return false;
  10145. }
  10146. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10147. return false;
  10148. if (this._cache.pivotMatrixUpdated) {
  10149. return false;
  10150. }
  10151. if (this.infiniteDistance) {
  10152. return false;
  10153. }
  10154. if (!this._cache.position.equals(this.position))
  10155. return false;
  10156. if (this.rotationQuaternion) {
  10157. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10158. return false;
  10159. }
  10160. else {
  10161. if (!this._cache.rotation.equals(this.rotation))
  10162. return false;
  10163. }
  10164. if (!this._cache.scaling.equals(this.scaling))
  10165. return false;
  10166. return true;
  10167. };
  10168. AbstractMesh.prototype._initCache = function () {
  10169. _super.prototype._initCache.call(this);
  10170. this._cache.localMatrixUpdated = false;
  10171. this._cache.position = BABYLON.Vector3.Zero();
  10172. this._cache.scaling = BABYLON.Vector3.Zero();
  10173. this._cache.rotation = BABYLON.Vector3.Zero();
  10174. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10175. };
  10176. AbstractMesh.prototype.markAsDirty = function (property) {
  10177. if (property === "rotation") {
  10178. this.rotationQuaternion = null;
  10179. }
  10180. this._currentRenderId = Number.MAX_VALUE;
  10181. this._isDirty = true;
  10182. };
  10183. AbstractMesh.prototype._updateBoundingInfo = function () {
  10184. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10185. this._boundingInfo._update(this.worldMatrixFromCache);
  10186. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10187. };
  10188. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10189. if (!this.subMeshes) {
  10190. return;
  10191. }
  10192. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10193. var subMesh = this.subMeshes[subIndex];
  10194. subMesh.updateBoundingInfo(matrix);
  10195. }
  10196. };
  10197. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10198. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10199. return this._worldMatrix;
  10200. }
  10201. this._cache.position.copyFrom(this.position);
  10202. this._cache.scaling.copyFrom(this.scaling);
  10203. this._cache.pivotMatrixUpdated = false;
  10204. this._currentRenderId = this.getScene().getRenderId();
  10205. this._isDirty = false;
  10206. // Scaling
  10207. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  10208. // Rotation
  10209. if (this.rotationQuaternion) {
  10210. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  10211. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10212. }
  10213. else {
  10214. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  10215. this._cache.rotation.copyFrom(this.rotation);
  10216. }
  10217. // Translation
  10218. if (this.infiniteDistance && !this.parent) {
  10219. var camera = this.getScene().activeCamera;
  10220. var cameraWorldMatrix = camera.getWorldMatrix();
  10221. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10222. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  10223. }
  10224. else {
  10225. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  10226. }
  10227. // Composing transformations
  10228. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  10229. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  10230. // Billboarding
  10231. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10232. var localPosition = this.position.clone();
  10233. var zero = this.getScene().activeCamera.position.clone();
  10234. if (this.parent && this.parent.position) {
  10235. localPosition.addInPlace(this.parent.position);
  10236. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  10237. }
  10238. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  10239. zero = this.getScene().activeCamera.position;
  10240. }
  10241. else {
  10242. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10243. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  10244. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10245. zero.y = localPosition.y + 0.001;
  10246. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10247. zero.z = localPosition.z + 0.001;
  10248. }
  10249. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  10250. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  10251. this._localBillboard.invert();
  10252. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  10253. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  10254. }
  10255. // Local world
  10256. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  10257. // Parent
  10258. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10259. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10260. }
  10261. else {
  10262. this._worldMatrix.copyFrom(this._localWorld);
  10263. }
  10264. // Bounding info
  10265. this._updateBoundingInfo();
  10266. // Absolute position
  10267. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10268. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  10269. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  10270. }
  10271. return this._worldMatrix;
  10272. };
  10273. /**
  10274. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10275. * @param func: callback function to add
  10276. */
  10277. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10278. this._onAfterWorldMatrixUpdate.push(func);
  10279. };
  10280. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10281. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  10282. if (index > -1) {
  10283. this._onAfterWorldMatrixUpdate.splice(index, 1);
  10284. }
  10285. };
  10286. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10287. this.computeWorldMatrix();
  10288. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10289. };
  10290. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10291. this.computeWorldMatrix();
  10292. var invLocalWorldMatrix = this._localWorld.clone();
  10293. invLocalWorldMatrix.invert();
  10294. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10295. };
  10296. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10297. this.computeWorldMatrix();
  10298. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10299. };
  10300. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  10301. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10302. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10303. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10304. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10305. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10306. /// <returns>Mesh oriented towards targetMesh</returns>
  10307. yawCor = yawCor || 0; // default to zero if undefined
  10308. pitchCor = pitchCor || 0;
  10309. rollCor = rollCor || 0;
  10310. var dv = targetPoint.subtract(this.position);
  10311. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10312. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10313. var pitch = Math.atan2(dv.y, len);
  10314. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  10315. };
  10316. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10317. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  10318. return false;
  10319. }
  10320. return true;
  10321. };
  10322. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  10323. if (!camera) {
  10324. camera = this.getScene().activeCamera;
  10325. }
  10326. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  10327. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  10328. return false;
  10329. }
  10330. return true;
  10331. };
  10332. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10333. if (!this._boundingInfo || !mesh._boundingInfo) {
  10334. return false;
  10335. }
  10336. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10337. };
  10338. AbstractMesh.prototype.intersectsPoint = function (point) {
  10339. if (!this._boundingInfo) {
  10340. return false;
  10341. }
  10342. return this._boundingInfo.intersectsPoint(point);
  10343. };
  10344. // Physics
  10345. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10346. var physicsEngine = this.getScene().getPhysicsEngine();
  10347. if (!physicsEngine) {
  10348. return;
  10349. }
  10350. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  10351. if (impostor.impostor) {
  10352. // Old API
  10353. options = impostor;
  10354. impostor = impostor.impostor;
  10355. }
  10356. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  10357. physicsEngine._unregisterMesh(this);
  10358. return;
  10359. }
  10360. if (!options) {
  10361. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  10362. }
  10363. else {
  10364. if (!options.mass && options.mass !== 0)
  10365. options.mass = 0;
  10366. if (!options.friction && options.friction !== 0)
  10367. options.friction = 0.2;
  10368. if (!options.restitution && options.restitution !== 0)
  10369. options.restitution = 0.2;
  10370. }
  10371. this._physicImpostor = impostor;
  10372. this._physicsMass = options.mass;
  10373. this._physicsFriction = options.friction;
  10374. this._physicRestitution = options.restitution;
  10375. return physicsEngine._registerMesh(this, impostor, options);
  10376. };
  10377. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10378. if (!this._physicImpostor) {
  10379. return BABYLON.PhysicsEngine.NoImpostor;
  10380. }
  10381. return this._physicImpostor;
  10382. };
  10383. AbstractMesh.prototype.getPhysicsMass = function () {
  10384. if (!this._physicsMass) {
  10385. return 0;
  10386. }
  10387. return this._physicsMass;
  10388. };
  10389. AbstractMesh.prototype.getPhysicsFriction = function () {
  10390. if (!this._physicsFriction) {
  10391. return 0;
  10392. }
  10393. return this._physicsFriction;
  10394. };
  10395. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10396. if (!this._physicRestitution) {
  10397. return 0;
  10398. }
  10399. return this._physicRestitution;
  10400. };
  10401. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10402. if (!camera) {
  10403. camera = this.getScene().activeCamera;
  10404. }
  10405. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10406. };
  10407. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10408. if (!camera) {
  10409. camera = this.getScene().activeCamera;
  10410. }
  10411. return this.absolutePosition.subtract(camera.position).length();
  10412. };
  10413. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10414. if (!this._physicImpostor) {
  10415. return;
  10416. }
  10417. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  10418. };
  10419. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10420. if (!this._physicImpostor) {
  10421. return;
  10422. }
  10423. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  10424. };
  10425. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10426. if (!this._physicImpostor) {
  10427. return;
  10428. }
  10429. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  10430. };
  10431. // Collisions
  10432. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10433. var globalPosition = this.getAbsolutePosition();
  10434. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10435. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10436. this._collider.radius = this.ellipsoid;
  10437. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  10438. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  10439. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10440. this.position.addInPlace(this._diffPositionForCollisions);
  10441. }
  10442. };
  10443. // Submeshes octree
  10444. /**
  10445. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10446. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10447. */
  10448. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10449. if (maxCapacity === void 0) { maxCapacity = 64; }
  10450. if (maxDepth === void 0) { maxDepth = 2; }
  10451. if (!this._submeshesOctree) {
  10452. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10453. }
  10454. this.computeWorldMatrix(true);
  10455. // Update octree
  10456. var bbox = this.getBoundingInfo().boundingBox;
  10457. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10458. return this._submeshesOctree;
  10459. };
  10460. // Collisions
  10461. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10462. this._generatePointsArray();
  10463. // Transformation
  10464. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10465. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10466. subMesh._lastColliderWorldVertices = [];
  10467. subMesh._trianglePlanes = [];
  10468. var start = subMesh.verticesStart;
  10469. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10470. for (var i = start; i < end; i++) {
  10471. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10472. }
  10473. }
  10474. // Collide
  10475. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  10476. };
  10477. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10478. var subMeshes;
  10479. var len;
  10480. // Octrees
  10481. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10482. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10483. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10484. len = intersections.length;
  10485. subMeshes = intersections.data;
  10486. }
  10487. else {
  10488. subMeshes = this.subMeshes;
  10489. len = subMeshes.length;
  10490. }
  10491. for (var index = 0; index < len; index++) {
  10492. var subMesh = subMeshes[index];
  10493. // Bounding test
  10494. if (len > 1 && !subMesh._checkCollision(collider))
  10495. continue;
  10496. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10497. }
  10498. };
  10499. AbstractMesh.prototype._checkCollision = function (collider) {
  10500. // Bounding box test
  10501. if (!this._boundingInfo._checkCollision(collider))
  10502. return;
  10503. // Transformation matrix
  10504. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10505. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10506. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10507. };
  10508. // Picking
  10509. AbstractMesh.prototype._generatePointsArray = function () {
  10510. return false;
  10511. };
  10512. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10513. var pickingInfo = new BABYLON.PickingInfo();
  10514. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10515. return pickingInfo;
  10516. }
  10517. if (!this._generatePointsArray()) {
  10518. return pickingInfo;
  10519. }
  10520. var intersectInfo = null;
  10521. // Octrees
  10522. var subMeshes;
  10523. var len;
  10524. if (this._submeshesOctree && this.useOctreeForPicking) {
  10525. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10526. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10527. len = intersections.length;
  10528. subMeshes = intersections.data;
  10529. }
  10530. else {
  10531. subMeshes = this.subMeshes;
  10532. len = subMeshes.length;
  10533. }
  10534. for (var index = 0; index < len; index++) {
  10535. var subMesh = subMeshes[index];
  10536. // Bounding test
  10537. if (len > 1 && !subMesh.canIntersects(ray))
  10538. continue;
  10539. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10540. if (currentIntersectInfo) {
  10541. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10542. intersectInfo = currentIntersectInfo;
  10543. intersectInfo.subMeshId = index;
  10544. if (fastCheck) {
  10545. break;
  10546. }
  10547. }
  10548. }
  10549. }
  10550. if (intersectInfo) {
  10551. // Get picked point
  10552. var world = this.getWorldMatrix();
  10553. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10554. var direction = ray.direction.clone();
  10555. direction = direction.scale(intersectInfo.distance);
  10556. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10557. var pickedPoint = worldOrigin.add(worldDirection);
  10558. // Return result
  10559. pickingInfo.hit = true;
  10560. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10561. pickingInfo.pickedPoint = pickedPoint;
  10562. pickingInfo.pickedMesh = this;
  10563. pickingInfo.bu = intersectInfo.bu;
  10564. pickingInfo.bv = intersectInfo.bv;
  10565. pickingInfo.faceId = intersectInfo.faceId;
  10566. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10567. return pickingInfo;
  10568. }
  10569. return pickingInfo;
  10570. };
  10571. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10572. return null;
  10573. };
  10574. AbstractMesh.prototype.releaseSubMeshes = function () {
  10575. if (this.subMeshes) {
  10576. while (this.subMeshes.length) {
  10577. this.subMeshes[0].dispose();
  10578. }
  10579. }
  10580. else {
  10581. this.subMeshes = new Array();
  10582. }
  10583. };
  10584. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10585. var index;
  10586. // Physics
  10587. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  10588. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10589. }
  10590. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10591. var other = this._intersectionsInProgress[index];
  10592. var pos = other._intersectionsInProgress.indexOf(this);
  10593. other._intersectionsInProgress.splice(pos, 1);
  10594. }
  10595. this._intersectionsInProgress = [];
  10596. // SubMeshes
  10597. this.releaseSubMeshes();
  10598. // Remove from scene
  10599. this.getScene().removeMesh(this);
  10600. if (!doNotRecurse) {
  10601. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10602. if (this.getScene().particleSystems[index].emitter === this) {
  10603. this.getScene().particleSystems[index].dispose();
  10604. index--;
  10605. }
  10606. }
  10607. // Children
  10608. var objects = this.getScene().meshes.slice(0);
  10609. for (index = 0; index < objects.length; index++) {
  10610. if (objects[index].parent === this) {
  10611. objects[index].dispose();
  10612. }
  10613. }
  10614. }
  10615. else {
  10616. for (index = 0; index < this.getScene().meshes.length; index++) {
  10617. var obj = this.getScene().meshes[index];
  10618. if (obj.parent === this) {
  10619. obj.parent = null;
  10620. obj.computeWorldMatrix(true);
  10621. }
  10622. }
  10623. }
  10624. this._onAfterWorldMatrixUpdate = [];
  10625. this._isDisposed = true;
  10626. // Callback
  10627. if (this.onDispose) {
  10628. this.onDispose();
  10629. }
  10630. };
  10631. // Statics
  10632. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10633. AbstractMesh._BILLBOARDMODE_X = 1;
  10634. AbstractMesh._BILLBOARDMODE_Y = 2;
  10635. AbstractMesh._BILLBOARDMODE_Z = 4;
  10636. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10637. return AbstractMesh;
  10638. })(BABYLON.Node);
  10639. BABYLON.AbstractMesh = AbstractMesh;
  10640. })(BABYLON || (BABYLON = {}));
  10641. //# sourceMappingURL=babylon.abstractMesh.js.map
  10642. var BABYLON;
  10643. (function (BABYLON) {
  10644. var _InstancesBatch = (function () {
  10645. function _InstancesBatch() {
  10646. this.mustReturn = false;
  10647. this.visibleInstances = new Array();
  10648. this.renderSelf = new Array();
  10649. }
  10650. return _InstancesBatch;
  10651. })();
  10652. BABYLON._InstancesBatch = _InstancesBatch;
  10653. var Mesh = (function (_super) {
  10654. __extends(Mesh, _super);
  10655. /**
  10656. * @constructor
  10657. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10658. * @param {Scene} scene - The scene to add this mesh to.
  10659. * @param {Node} parent - The parent of this mesh, if it has one
  10660. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10661. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10662. * When false, achieved by calling a clone(), also passing False.
  10663. * This will make creation of children, recursive.
  10664. */
  10665. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10666. if (parent === void 0) { parent = null; }
  10667. _super.call(this, name, scene);
  10668. // Members
  10669. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10670. this.instances = new Array();
  10671. this._LODLevels = new Array();
  10672. this._onBeforeRenderCallbacks = new Array();
  10673. this._onAfterRenderCallbacks = new Array();
  10674. this._visibleInstances = {};
  10675. this._renderIdForInstances = new Array();
  10676. this._batchCache = new _InstancesBatch();
  10677. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10678. if (source) {
  10679. // Geometry
  10680. if (source._geometry) {
  10681. source._geometry.applyToMesh(this);
  10682. }
  10683. // Deep copy
  10684. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10685. // Material
  10686. this.material = source.material;
  10687. if (!doNotCloneChildren) {
  10688. for (var index = 0; index < scene.meshes.length; index++) {
  10689. var mesh = scene.meshes[index];
  10690. if (mesh.parent === source) {
  10691. // doNotCloneChildren is always going to be False
  10692. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10693. }
  10694. }
  10695. }
  10696. for (index = 0; index < scene.particleSystems.length; index++) {
  10697. var system = scene.particleSystems[index];
  10698. if (system.emitter === source) {
  10699. system.clone(system.name, this);
  10700. }
  10701. }
  10702. this.computeWorldMatrix(true);
  10703. }
  10704. // Parent
  10705. if (parent !== null) {
  10706. this.parent = parent;
  10707. }
  10708. }
  10709. Object.defineProperty(Mesh, "FRONTSIDE", {
  10710. get: function () {
  10711. return Mesh._FRONTSIDE;
  10712. },
  10713. enumerable: true,
  10714. configurable: true
  10715. });
  10716. Object.defineProperty(Mesh, "BACKSIDE", {
  10717. get: function () {
  10718. return Mesh._BACKSIDE;
  10719. },
  10720. enumerable: true,
  10721. configurable: true
  10722. });
  10723. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10724. get: function () {
  10725. return Mesh._DOUBLESIDE;
  10726. },
  10727. enumerable: true,
  10728. configurable: true
  10729. });
  10730. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  10731. get: function () {
  10732. return Mesh._DEFAULTSIDE;
  10733. },
  10734. enumerable: true,
  10735. configurable: true
  10736. });
  10737. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10738. // Methods
  10739. get: function () {
  10740. return this._LODLevels.length > 0;
  10741. },
  10742. enumerable: true,
  10743. configurable: true
  10744. });
  10745. Mesh.prototype._sortLODLevels = function () {
  10746. this._LODLevels.sort(function (a, b) {
  10747. if (a.distance < b.distance) {
  10748. return 1;
  10749. }
  10750. if (a.distance > b.distance) {
  10751. return -1;
  10752. }
  10753. return 0;
  10754. });
  10755. };
  10756. /**
  10757. * Add a mesh as LOD level triggered at the given distance.
  10758. * @param {number} distance - the distance from the center of the object to show this level
  10759. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10760. * @return {BABYLON.Mesh} this mesh (for chaining)
  10761. */
  10762. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10763. if (mesh && mesh._masterMesh) {
  10764. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10765. return this;
  10766. }
  10767. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10768. this._LODLevels.push(level);
  10769. if (mesh) {
  10770. mesh._masterMesh = this;
  10771. }
  10772. this._sortLODLevels();
  10773. return this;
  10774. };
  10775. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  10776. for (var index = 0; index < this._LODLevels.length; index++) {
  10777. var level = this._LODLevels[index];
  10778. if (level.distance === distance) {
  10779. return level.mesh;
  10780. }
  10781. }
  10782. return null;
  10783. };
  10784. /**
  10785. * Remove a mesh from the LOD array
  10786. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10787. * @return {BABYLON.Mesh} this mesh (for chaining)
  10788. */
  10789. Mesh.prototype.removeLODLevel = function (mesh) {
  10790. for (var index = 0; index < this._LODLevels.length; index++) {
  10791. if (this._LODLevels[index].mesh === mesh) {
  10792. this._LODLevels.splice(index, 1);
  10793. if (mesh) {
  10794. mesh._masterMesh = null;
  10795. }
  10796. }
  10797. }
  10798. this._sortLODLevels();
  10799. return this;
  10800. };
  10801. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  10802. if (!this._LODLevels || this._LODLevels.length === 0) {
  10803. return this;
  10804. }
  10805. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  10806. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  10807. return this;
  10808. }
  10809. for (var index = 0; index < this._LODLevels.length; index++) {
  10810. var level = this._LODLevels[index];
  10811. if (level.distance < distanceToCamera) {
  10812. if (level.mesh) {
  10813. level.mesh._preActivate();
  10814. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10815. }
  10816. return level.mesh;
  10817. }
  10818. }
  10819. return this;
  10820. };
  10821. Object.defineProperty(Mesh.prototype, "geometry", {
  10822. get: function () {
  10823. return this._geometry;
  10824. },
  10825. enumerable: true,
  10826. configurable: true
  10827. });
  10828. Mesh.prototype.getTotalVertices = function () {
  10829. if (!this._geometry) {
  10830. return 0;
  10831. }
  10832. return this._geometry.getTotalVertices();
  10833. };
  10834. Mesh.prototype.getVerticesData = function (kind) {
  10835. if (!this._geometry) {
  10836. return null;
  10837. }
  10838. return this._geometry.getVerticesData(kind);
  10839. };
  10840. Mesh.prototype.getVertexBuffer = function (kind) {
  10841. if (!this._geometry) {
  10842. return undefined;
  10843. }
  10844. return this._geometry.getVertexBuffer(kind);
  10845. };
  10846. Mesh.prototype.isVerticesDataPresent = function (kind) {
  10847. if (!this._geometry) {
  10848. if (this._delayInfo) {
  10849. return this._delayInfo.indexOf(kind) !== -1;
  10850. }
  10851. return false;
  10852. }
  10853. return this._geometry.isVerticesDataPresent(kind);
  10854. };
  10855. Mesh.prototype.getVerticesDataKinds = function () {
  10856. if (!this._geometry) {
  10857. var result = [];
  10858. if (this._delayInfo) {
  10859. for (var kind in this._delayInfo) {
  10860. result.push(kind);
  10861. }
  10862. }
  10863. return result;
  10864. }
  10865. return this._geometry.getVerticesDataKinds();
  10866. };
  10867. Mesh.prototype.getTotalIndices = function () {
  10868. if (!this._geometry) {
  10869. return 0;
  10870. }
  10871. return this._geometry.getTotalIndices();
  10872. };
  10873. Mesh.prototype.getIndices = function () {
  10874. if (!this._geometry) {
  10875. return [];
  10876. }
  10877. return this._geometry.getIndices();
  10878. };
  10879. Object.defineProperty(Mesh.prototype, "isBlocked", {
  10880. get: function () {
  10881. return this._masterMesh !== null && this._masterMesh !== undefined;
  10882. },
  10883. enumerable: true,
  10884. configurable: true
  10885. });
  10886. Mesh.prototype.isReady = function () {
  10887. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10888. return false;
  10889. }
  10890. return _super.prototype.isReady.call(this);
  10891. };
  10892. Mesh.prototype.isDisposed = function () {
  10893. return this._isDisposed;
  10894. };
  10895. // Methods
  10896. Mesh.prototype._preActivate = function () {
  10897. var sceneRenderId = this.getScene().getRenderId();
  10898. if (this._preActivateId === sceneRenderId) {
  10899. return;
  10900. }
  10901. this._preActivateId = sceneRenderId;
  10902. this._visibleInstances = null;
  10903. };
  10904. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  10905. if (!this._visibleInstances) {
  10906. this._visibleInstances = {};
  10907. this._visibleInstances.defaultRenderId = renderId;
  10908. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10909. }
  10910. if (!this._visibleInstances[renderId]) {
  10911. this._visibleInstances[renderId] = new Array();
  10912. }
  10913. this._visibleInstances[renderId].push(instance);
  10914. };
  10915. Mesh.prototype.refreshBoundingInfo = function () {
  10916. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10917. if (data) {
  10918. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10919. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10920. }
  10921. if (this.subMeshes) {
  10922. for (var index = 0; index < this.subMeshes.length; index++) {
  10923. this.subMeshes[index].refreshBoundingInfo();
  10924. }
  10925. }
  10926. this._updateBoundingInfo();
  10927. };
  10928. Mesh.prototype._createGlobalSubMesh = function () {
  10929. var totalVertices = this.getTotalVertices();
  10930. if (!totalVertices || !this.getIndices()) {
  10931. return null;
  10932. }
  10933. this.releaseSubMeshes();
  10934. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10935. };
  10936. Mesh.prototype.subdivide = function (count) {
  10937. if (count < 1) {
  10938. return;
  10939. }
  10940. var totalIndices = this.getTotalIndices();
  10941. var subdivisionSize = (totalIndices / count) | 0;
  10942. var offset = 0;
  10943. while (subdivisionSize % 3 !== 0) {
  10944. subdivisionSize++;
  10945. }
  10946. this.releaseSubMeshes();
  10947. for (var index = 0; index < count; index++) {
  10948. if (offset >= totalIndices) {
  10949. break;
  10950. }
  10951. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10952. offset += subdivisionSize;
  10953. }
  10954. this.synchronizeInstances();
  10955. };
  10956. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10957. if (kind instanceof Array) {
  10958. var temp = data;
  10959. data = kind;
  10960. kind = temp;
  10961. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10962. }
  10963. if (!this._geometry) {
  10964. var vertexData = new BABYLON.VertexData();
  10965. vertexData.set(data, kind);
  10966. var scene = this.getScene();
  10967. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10968. }
  10969. else {
  10970. this._geometry.setVerticesData(kind, data, updatable, stride);
  10971. }
  10972. };
  10973. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10974. if (!this._geometry) {
  10975. return;
  10976. }
  10977. if (!makeItUnique) {
  10978. this._geometry.updateVerticesData(kind, data, updateExtends);
  10979. }
  10980. else {
  10981. this.makeGeometryUnique();
  10982. this.updateVerticesData(kind, data, updateExtends, false);
  10983. }
  10984. };
  10985. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  10986. if (!this._geometry) {
  10987. return;
  10988. }
  10989. if (!makeItUnique) {
  10990. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  10991. }
  10992. else {
  10993. this.makeGeometryUnique();
  10994. this.updateVerticesDataDirectly(kind, data, offset, false);
  10995. }
  10996. };
  10997. Mesh.prototype.makeGeometryUnique = function () {
  10998. if (!this._geometry) {
  10999. return;
  11000. }
  11001. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  11002. geometry.applyToMesh(this);
  11003. };
  11004. Mesh.prototype.setIndices = function (indices, totalVertices) {
  11005. if (!this._geometry) {
  11006. var vertexData = new BABYLON.VertexData();
  11007. vertexData.indices = indices;
  11008. var scene = this.getScene();
  11009. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  11010. }
  11011. else {
  11012. this._geometry.setIndices(indices, totalVertices);
  11013. }
  11014. };
  11015. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  11016. var engine = this.getScene().getEngine();
  11017. // Wireframe
  11018. var indexToBind;
  11019. switch (fillMode) {
  11020. case BABYLON.Material.PointFillMode:
  11021. indexToBind = null;
  11022. break;
  11023. case BABYLON.Material.WireFrameFillMode:
  11024. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  11025. break;
  11026. default:
  11027. case BABYLON.Material.TriangleFillMode:
  11028. indexToBind = this._geometry.getIndexBuffer();
  11029. break;
  11030. }
  11031. // VBOs
  11032. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  11033. };
  11034. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  11035. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11036. return;
  11037. }
  11038. var engine = this.getScene().getEngine();
  11039. switch (fillMode) {
  11040. case BABYLON.Material.PointFillMode:
  11041. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  11042. break;
  11043. case BABYLON.Material.WireFrameFillMode:
  11044. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  11045. break;
  11046. default:
  11047. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  11048. }
  11049. };
  11050. Mesh.prototype.registerBeforeRender = function (func) {
  11051. this._onBeforeRenderCallbacks.push(func);
  11052. };
  11053. Mesh.prototype.unregisterBeforeRender = function (func) {
  11054. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11055. if (index > -1) {
  11056. this._onBeforeRenderCallbacks.splice(index, 1);
  11057. }
  11058. };
  11059. Mesh.prototype.registerAfterRender = function (func) {
  11060. this._onAfterRenderCallbacks.push(func);
  11061. };
  11062. Mesh.prototype.unregisterAfterRender = function (func) {
  11063. var index = this._onAfterRenderCallbacks.indexOf(func);
  11064. if (index > -1) {
  11065. this._onAfterRenderCallbacks.splice(index, 1);
  11066. }
  11067. };
  11068. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  11069. var scene = this.getScene();
  11070. this._batchCache.mustReturn = false;
  11071. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  11072. this._batchCache.visibleInstances[subMeshId] = null;
  11073. if (this._visibleInstances) {
  11074. var currentRenderId = scene.getRenderId();
  11075. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  11076. var selfRenderId = this._renderId;
  11077. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  11078. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  11079. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  11080. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  11081. }
  11082. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  11083. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  11084. this._batchCache.mustReturn = true;
  11085. return this._batchCache;
  11086. }
  11087. if (currentRenderId !== selfRenderId) {
  11088. this._batchCache.renderSelf[subMeshId] = false;
  11089. }
  11090. }
  11091. this._renderIdForInstances[subMeshId] = currentRenderId;
  11092. }
  11093. return this._batchCache;
  11094. };
  11095. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  11096. var visibleInstances = batch.visibleInstances[subMesh._id];
  11097. var matricesCount = visibleInstances.length + 1;
  11098. var bufferSize = matricesCount * 16 * 4;
  11099. while (this._instancesBufferSize < bufferSize) {
  11100. this._instancesBufferSize *= 2;
  11101. }
  11102. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  11103. if (this._worldMatricesInstancesBuffer) {
  11104. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11105. }
  11106. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  11107. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  11108. }
  11109. var offset = 0;
  11110. var instancesCount = 0;
  11111. var world = this.getWorldMatrix();
  11112. if (batch.renderSelf[subMesh._id]) {
  11113. world.copyToArray(this._worldMatricesInstancesArray, offset);
  11114. offset += 16;
  11115. instancesCount++;
  11116. }
  11117. if (visibleInstances) {
  11118. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  11119. var instance = visibleInstances[instanceIndex];
  11120. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  11121. offset += 16;
  11122. instancesCount++;
  11123. }
  11124. }
  11125. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  11126. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  11127. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  11128. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  11129. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  11130. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  11131. this._draw(subMesh, fillMode, instancesCount);
  11132. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  11133. };
  11134. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  11135. var scene = this.getScene();
  11136. var engine = scene.getEngine();
  11137. if (hardwareInstancedRendering) {
  11138. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  11139. }
  11140. else {
  11141. if (batch.renderSelf[subMesh._id]) {
  11142. // Draw
  11143. if (onBeforeDraw) {
  11144. onBeforeDraw(false, this.getWorldMatrix());
  11145. }
  11146. this._draw(subMesh, fillMode);
  11147. }
  11148. if (batch.visibleInstances[subMesh._id]) {
  11149. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  11150. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  11151. // World
  11152. var world = instance.getWorldMatrix();
  11153. if (onBeforeDraw) {
  11154. onBeforeDraw(true, world);
  11155. }
  11156. // Draw
  11157. this._draw(subMesh, fillMode);
  11158. }
  11159. }
  11160. }
  11161. };
  11162. Mesh.prototype.render = function (subMesh) {
  11163. var scene = this.getScene();
  11164. // Managing instances
  11165. var batch = this._getInstancesRenderList(subMesh._id);
  11166. if (batch.mustReturn) {
  11167. return;
  11168. }
  11169. // Checking geometry state
  11170. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11171. return;
  11172. }
  11173. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  11174. this._onBeforeRenderCallbacks[callbackIndex](this);
  11175. }
  11176. var engine = scene.getEngine();
  11177. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11178. // Material
  11179. var effectiveMaterial = subMesh.getMaterial();
  11180. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  11181. return;
  11182. }
  11183. // Outline - step 1
  11184. var savedDepthWrite = engine.getDepthWrite();
  11185. if (this.renderOutline) {
  11186. engine.setDepthWrite(false);
  11187. scene.getOutlineRenderer().render(subMesh, batch);
  11188. engine.setDepthWrite(savedDepthWrite);
  11189. }
  11190. effectiveMaterial._preBind();
  11191. var effect = effectiveMaterial.getEffect();
  11192. // Bind
  11193. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  11194. this._bind(subMesh, effect, fillMode);
  11195. var world = this.getWorldMatrix();
  11196. effectiveMaterial.bind(world, this);
  11197. // Draw
  11198. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  11199. if (isInstance) {
  11200. effectiveMaterial.bindOnlyWorldMatrix(world);
  11201. }
  11202. });
  11203. // Unbind
  11204. effectiveMaterial.unbind();
  11205. // Outline - step 2
  11206. if (this.renderOutline && savedDepthWrite) {
  11207. engine.setDepthWrite(true);
  11208. engine.setColorWrite(false);
  11209. scene.getOutlineRenderer().render(subMesh, batch);
  11210. engine.setColorWrite(true);
  11211. }
  11212. // Overlay
  11213. if (this.renderOverlay) {
  11214. var currentMode = engine.getAlphaMode();
  11215. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11216. scene.getOutlineRenderer().render(subMesh, batch, true);
  11217. engine.setAlphaMode(currentMode);
  11218. }
  11219. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  11220. this._onAfterRenderCallbacks[callbackIndex](this);
  11221. }
  11222. };
  11223. Mesh.prototype.getEmittedParticleSystems = function () {
  11224. var results = new Array();
  11225. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11226. var particleSystem = this.getScene().particleSystems[index];
  11227. if (particleSystem.emitter === this) {
  11228. results.push(particleSystem);
  11229. }
  11230. }
  11231. return results;
  11232. };
  11233. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  11234. var results = new Array();
  11235. var descendants = this.getDescendants();
  11236. descendants.push(this);
  11237. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11238. var particleSystem = this.getScene().particleSystems[index];
  11239. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  11240. results.push(particleSystem);
  11241. }
  11242. }
  11243. return results;
  11244. };
  11245. Mesh.prototype.getChildren = function () {
  11246. var results = [];
  11247. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11248. var mesh = this.getScene().meshes[index];
  11249. if (mesh.parent === this) {
  11250. results.push(mesh);
  11251. }
  11252. }
  11253. return results;
  11254. };
  11255. Mesh.prototype._checkDelayState = function () {
  11256. var _this = this;
  11257. var that = this;
  11258. var scene = this.getScene();
  11259. if (this._geometry) {
  11260. this._geometry.load(scene);
  11261. }
  11262. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11263. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  11264. scene._addPendingData(that);
  11265. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  11266. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  11267. if (data instanceof ArrayBuffer) {
  11268. _this._delayLoadingFunction(data, _this);
  11269. }
  11270. else {
  11271. _this._delayLoadingFunction(JSON.parse(data), _this);
  11272. }
  11273. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11274. scene._removePendingData(_this);
  11275. }, function () {
  11276. }, scene.database, getBinaryData);
  11277. }
  11278. };
  11279. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  11280. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11281. return false;
  11282. }
  11283. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  11284. return false;
  11285. }
  11286. this._checkDelayState();
  11287. return true;
  11288. };
  11289. Mesh.prototype.setMaterialByID = function (id) {
  11290. var materials = this.getScene().materials;
  11291. for (var index = 0; index < materials.length; index++) {
  11292. if (materials[index].id === id) {
  11293. this.material = materials[index];
  11294. return;
  11295. }
  11296. }
  11297. // Multi
  11298. var multiMaterials = this.getScene().multiMaterials;
  11299. for (index = 0; index < multiMaterials.length; index++) {
  11300. if (multiMaterials[index].id === id) {
  11301. this.material = multiMaterials[index];
  11302. return;
  11303. }
  11304. }
  11305. };
  11306. Mesh.prototype.getAnimatables = function () {
  11307. var results = [];
  11308. if (this.material) {
  11309. results.push(this.material);
  11310. }
  11311. if (this.skeleton) {
  11312. results.push(this.skeleton);
  11313. }
  11314. return results;
  11315. };
  11316. // Geometry
  11317. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  11318. // Position
  11319. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  11320. return;
  11321. }
  11322. this._resetPointsArrayCache();
  11323. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11324. var temp = [];
  11325. for (var index = 0; index < data.length; index += 3) {
  11326. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11327. }
  11328. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  11329. // Normals
  11330. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11331. return;
  11332. }
  11333. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11334. for (index = 0; index < data.length; index += 3) {
  11335. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11336. }
  11337. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  11338. };
  11339. // Cache
  11340. Mesh.prototype._resetPointsArrayCache = function () {
  11341. this._positions = null;
  11342. };
  11343. Mesh.prototype._generatePointsArray = function () {
  11344. if (this._positions)
  11345. return true;
  11346. this._positions = [];
  11347. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11348. if (!data) {
  11349. return false;
  11350. }
  11351. for (var index = 0; index < data.length; index += 3) {
  11352. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  11353. }
  11354. return true;
  11355. };
  11356. // Clone
  11357. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11358. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  11359. };
  11360. // Dispose
  11361. Mesh.prototype.dispose = function (doNotRecurse) {
  11362. if (this._geometry) {
  11363. this._geometry.releaseForMesh(this, true);
  11364. }
  11365. // Instances
  11366. if (this._worldMatricesInstancesBuffer) {
  11367. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11368. this._worldMatricesInstancesBuffer = null;
  11369. }
  11370. while (this.instances.length) {
  11371. this.instances[0].dispose();
  11372. }
  11373. _super.prototype.dispose.call(this, doNotRecurse);
  11374. };
  11375. // Geometric tools
  11376. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  11377. var _this = this;
  11378. var scene = this.getScene();
  11379. var onload = function (img) {
  11380. // Getting height map data
  11381. var canvas = document.createElement("canvas");
  11382. var context = canvas.getContext("2d");
  11383. var heightMapWidth = img.width;
  11384. var heightMapHeight = img.height;
  11385. canvas.width = heightMapWidth;
  11386. canvas.height = heightMapHeight;
  11387. context.drawImage(img, 0, 0);
  11388. // Create VertexData from map data
  11389. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11390. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11391. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  11392. //execute success callback, if set
  11393. if (onSuccess) {
  11394. onSuccess(_this);
  11395. }
  11396. };
  11397. BABYLON.Tools.LoadImage(url, onload, function () {
  11398. }, scene.database);
  11399. };
  11400. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  11401. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11402. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  11403. return;
  11404. }
  11405. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11406. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11407. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11408. var position = BABYLON.Vector3.Zero();
  11409. var normal = BABYLON.Vector3.Zero();
  11410. var uv = BABYLON.Vector2.Zero();
  11411. for (var index = 0; index < positions.length; index += 3) {
  11412. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  11413. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  11414. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  11415. // Compute height
  11416. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  11417. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  11418. var pos = (u + v * heightMapWidth) * 4;
  11419. var r = buffer[pos] / 255.0;
  11420. var g = buffer[pos + 1] / 255.0;
  11421. var b = buffer[pos + 2] / 255.0;
  11422. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  11423. normal.normalize();
  11424. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  11425. position = position.add(normal);
  11426. position.toArray(positions, index);
  11427. }
  11428. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  11429. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  11430. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  11431. };
  11432. Mesh.prototype.convertToFlatShadedMesh = function () {
  11433. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  11434. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  11435. var kinds = this.getVerticesDataKinds();
  11436. var vbs = [];
  11437. var data = [];
  11438. var newdata = [];
  11439. var updatableNormals = false;
  11440. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11441. var kind = kinds[kindIndex];
  11442. var vertexBuffer = this.getVertexBuffer(kind);
  11443. if (kind === BABYLON.VertexBuffer.NormalKind) {
  11444. updatableNormals = vertexBuffer.isUpdatable();
  11445. kinds.splice(kindIndex, 1);
  11446. kindIndex--;
  11447. continue;
  11448. }
  11449. vbs[kind] = vertexBuffer;
  11450. data[kind] = vbs[kind].getData();
  11451. newdata[kind] = [];
  11452. }
  11453. // Save previous submeshes
  11454. var previousSubmeshes = this.subMeshes.slice(0);
  11455. var indices = this.getIndices();
  11456. var totalIndices = this.getTotalIndices();
  11457. for (var index = 0; index < totalIndices; index++) {
  11458. var vertexIndex = indices[index];
  11459. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11460. kind = kinds[kindIndex];
  11461. var stride = vbs[kind].getStrideSize();
  11462. for (var offset = 0; offset < stride; offset++) {
  11463. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  11464. }
  11465. }
  11466. }
  11467. // Updating faces & normal
  11468. var normals = [];
  11469. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  11470. for (index = 0; index < totalIndices; index += 3) {
  11471. indices[index] = index;
  11472. indices[index + 1] = index + 1;
  11473. indices[index + 2] = index + 2;
  11474. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  11475. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  11476. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  11477. var p1p2 = p1.subtract(p2);
  11478. var p3p2 = p3.subtract(p2);
  11479. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  11480. for (var localIndex = 0; localIndex < 3; localIndex++) {
  11481. normals.push(normal.x);
  11482. normals.push(normal.y);
  11483. normals.push(normal.z);
  11484. }
  11485. }
  11486. this.setIndices(indices);
  11487. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  11488. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11489. kind = kinds[kindIndex];
  11490. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  11491. }
  11492. // Updating submeshes
  11493. this.releaseSubMeshes();
  11494. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  11495. var previousOne = previousSubmeshes[submeshIndex];
  11496. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  11497. }
  11498. this.synchronizeInstances();
  11499. };
  11500. // Instances
  11501. Mesh.prototype.createInstance = function (name) {
  11502. return new BABYLON.InstancedMesh(name, this);
  11503. };
  11504. Mesh.prototype.synchronizeInstances = function () {
  11505. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  11506. var instance = this.instances[instanceIndex];
  11507. instance._syncSubMeshes();
  11508. }
  11509. };
  11510. /**
  11511. * Simplify the mesh according to the given array of settings.
  11512. * Function will return immediately and will simplify async.
  11513. * @param settings a collection of simplification settings.
  11514. * @param parallelProcessing should all levels calculate parallel or one after the other.
  11515. * @param type the type of simplification to run.
  11516. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  11517. */
  11518. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  11519. if (parallelProcessing === void 0) { parallelProcessing = true; }
  11520. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  11521. this.getScene().simplificationQueue.addTask({
  11522. settings: settings,
  11523. parallelProcessing: parallelProcessing,
  11524. mesh: this,
  11525. simplificationType: simplificationType,
  11526. successCallback: successCallback
  11527. });
  11528. };
  11529. /**
  11530. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  11531. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  11532. * This should be used together with the simplification to avoid disappearing triangles.
  11533. * @param successCallback an optional success callback to be called after the optimization finished.
  11534. */
  11535. Mesh.prototype.optimizeIndices = function (successCallback) {
  11536. var _this = this;
  11537. var indices = this.getIndices();
  11538. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11539. var vectorPositions = [];
  11540. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  11541. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  11542. }
  11543. var dupes = [];
  11544. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  11545. var realPos = vectorPositions.length - 1 - iteration;
  11546. var testedPosition = vectorPositions[realPos];
  11547. for (var j = 0; j < realPos; ++j) {
  11548. var againstPosition = vectorPositions[j];
  11549. if (testedPosition.equals(againstPosition)) {
  11550. dupes[realPos] = j;
  11551. break;
  11552. }
  11553. }
  11554. }, function () {
  11555. for (var i = 0; i < indices.length; ++i) {
  11556. indices[i] = dupes[indices[i]] || indices[i];
  11557. }
  11558. //indices are now reordered
  11559. var originalSubMeshes = _this.subMeshes.slice(0);
  11560. _this.setIndices(indices);
  11561. _this.subMeshes = originalSubMeshes;
  11562. if (successCallback) {
  11563. successCallback(_this);
  11564. }
  11565. });
  11566. };
  11567. // Statics
  11568. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation) {
  11569. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11570. var ribbon = new Mesh(name, scene);
  11571. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11572. vertexData.applyToMesh(ribbon, updatable);
  11573. return ribbon;
  11574. };
  11575. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11576. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11577. var box = new Mesh(name, scene);
  11578. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11579. vertexData.applyToMesh(box, updatable);
  11580. return box;
  11581. };
  11582. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11583. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11584. var sphere = new Mesh(name, scene);
  11585. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11586. vertexData.applyToMesh(sphere, updatable);
  11587. return sphere;
  11588. };
  11589. // Cylinder and cone (Code inspired by SharpDX.org)
  11590. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11591. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11592. // subdivisions is a new parameter, we need to support old signature
  11593. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11594. if (scene !== undefined) {
  11595. updatable = scene;
  11596. }
  11597. scene = subdivisions;
  11598. subdivisions = 1;
  11599. }
  11600. var cylinder = new Mesh(name, scene);
  11601. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11602. vertexData.applyToMesh(cylinder, updatable);
  11603. return cylinder;
  11604. };
  11605. // Torus (Code from SharpDX.org)
  11606. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11607. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11608. var torus = new Mesh(name, scene);
  11609. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11610. vertexData.applyToMesh(torus, updatable);
  11611. return torus;
  11612. };
  11613. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11614. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11615. var torusKnot = new Mesh(name, scene);
  11616. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11617. vertexData.applyToMesh(torusKnot, updatable);
  11618. return torusKnot;
  11619. };
  11620. // Lines
  11621. Mesh.CreateLines = function (name, points, scene, updatable) {
  11622. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11623. var vertexData = BABYLON.VertexData.CreateLines(points);
  11624. vertexData.applyToMesh(lines, updatable);
  11625. return lines;
  11626. };
  11627. // Extrusion
  11628. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, scene, updatable, sideOrientation) {
  11629. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11630. scale = scale || 1;
  11631. rotation = rotation || 0;
  11632. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, false, scene, updatable, sideOrientation);
  11633. return extruded;
  11634. };
  11635. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, scene, updatable, sideOrientation) {
  11636. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11637. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, true, scene, updatable, sideOrientation);
  11638. return extrudedCustom;
  11639. };
  11640. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, custom, scene, updtbl, side) {
  11641. var path3D = new BABYLON.Path3D(curve);
  11642. var tangents = path3D.getTangents();
  11643. var normals = path3D.getNormals();
  11644. var binormals = path3D.getBinormals();
  11645. var distances = path3D.getDistances();
  11646. var shapePaths = new Array();
  11647. var angle = 0;
  11648. var returnScale = function (i, distance) {
  11649. return scale;
  11650. };
  11651. var returnRotation = function (i, distance) {
  11652. return rotation;
  11653. };
  11654. var rotate = custom ? rotateFunction : returnRotation;
  11655. var scl = custom ? scaleFunction : returnScale;
  11656. for (var i = 0; i < curve.length; i++) {
  11657. var shapePath = new Array();
  11658. var angleStep = rotate(i, distances[i]);
  11659. var scaleRatio = scl(i, distances[i]);
  11660. for (var p = 0; p < shape.length; p++) {
  11661. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  11662. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  11663. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  11664. shapePath.push(rotated);
  11665. }
  11666. shapePaths.push(shapePath);
  11667. angle += angleStep;
  11668. }
  11669. var extrudedGeneric = Mesh.CreateRibbon(name, shapePaths, rbCA, rbCP, 0, scene, updtbl, side);
  11670. return extrudedGeneric;
  11671. };
  11672. // Plane & ground
  11673. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  11674. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11675. var plane = new Mesh(name, scene);
  11676. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  11677. vertexData.applyToMesh(plane, updatable);
  11678. return plane;
  11679. };
  11680. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  11681. var ground = new BABYLON.GroundMesh(name, scene);
  11682. ground._setReady(false);
  11683. ground._subdivisions = subdivisions;
  11684. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  11685. vertexData.applyToMesh(ground, updatable);
  11686. ground._setReady(true);
  11687. return ground;
  11688. };
  11689. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  11690. var tiledGround = new Mesh(name, scene);
  11691. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  11692. vertexData.applyToMesh(tiledGround, updatable);
  11693. return tiledGround;
  11694. };
  11695. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  11696. var ground = new BABYLON.GroundMesh(name, scene);
  11697. ground._subdivisions = subdivisions;
  11698. ground._setReady(false);
  11699. var onload = function (img) {
  11700. // Getting height map data
  11701. var canvas = document.createElement("canvas");
  11702. var context = canvas.getContext("2d");
  11703. var heightMapWidth = img.width;
  11704. var heightMapHeight = img.height;
  11705. canvas.width = heightMapWidth;
  11706. canvas.height = heightMapHeight;
  11707. context.drawImage(img, 0, 0);
  11708. // Create VertexData from map data
  11709. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11710. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11711. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  11712. vertexData.applyToMesh(ground, updatable);
  11713. ground._setReady(true);
  11714. //execute ready callback, if set
  11715. if (onReady) {
  11716. onReady(ground);
  11717. }
  11718. };
  11719. BABYLON.Tools.LoadImage(url, onload, function () {
  11720. }, scene.database);
  11721. return ground;
  11722. };
  11723. Mesh.CreateTube = function (name, path, radius, tesselation, radiusFunction, scene, updatable, sideOrientation) {
  11724. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11725. var path3D = new BABYLON.Path3D(path);
  11726. var tangents = path3D.getTangents();
  11727. var normals = path3D.getNormals();
  11728. var distances = path3D.getDistances();
  11729. var pi2 = Math.PI * 2;
  11730. var step = pi2 / tesselation;
  11731. var returnRadius = function (i, distance) { return radius; };
  11732. var radiusFunctionFinal = radiusFunction || returnRadius;
  11733. var circlePaths = new Array();
  11734. var circlePath;
  11735. var rad;
  11736. var normal;
  11737. var rotated;
  11738. var rotationMatrix;
  11739. for (var i = 0; i < path.length; i++) {
  11740. rad = radiusFunctionFinal(i, distances[i]); // current radius
  11741. circlePath = Array(); // current circle array
  11742. normal = normals[i]; // current normal
  11743. for (var ang = 0; ang < pi2; ang += step) {
  11744. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  11745. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  11746. circlePath.push(rotated);
  11747. }
  11748. circlePaths.push(circlePath);
  11749. }
  11750. var tube = Mesh.CreateRibbon(name, circlePaths, false, true, 0, scene, updatable, sideOrientation);
  11751. return tube;
  11752. };
  11753. // Tools
  11754. Mesh.MinMax = function (meshes) {
  11755. var minVector = null;
  11756. var maxVector = null;
  11757. for (var i in meshes) {
  11758. var mesh = meshes[i];
  11759. var boundingBox = mesh.getBoundingInfo().boundingBox;
  11760. if (!minVector) {
  11761. minVector = boundingBox.minimumWorld;
  11762. maxVector = boundingBox.maximumWorld;
  11763. continue;
  11764. }
  11765. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  11766. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  11767. }
  11768. return {
  11769. min: minVector,
  11770. max: maxVector
  11771. };
  11772. };
  11773. Mesh.Center = function (meshesOrMinMaxVector) {
  11774. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  11775. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  11776. };
  11777. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  11778. if (disposeSource === void 0) { disposeSource = true; }
  11779. var source = meshes[0];
  11780. var material = source.material;
  11781. var scene = source.getScene();
  11782. if (!allow32BitsIndices) {
  11783. var totalVertices = 0;
  11784. for (var index = 0; index < meshes.length; index++) {
  11785. totalVertices += meshes[index].getTotalVertices();
  11786. if (totalVertices > 65536) {
  11787. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  11788. return null;
  11789. }
  11790. }
  11791. }
  11792. // Merge
  11793. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  11794. vertexData.transform(source.getWorldMatrix());
  11795. for (index = 1; index < meshes.length; index++) {
  11796. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  11797. otherVertexData.transform(meshes[index].getWorldMatrix());
  11798. vertexData.merge(otherVertexData);
  11799. }
  11800. var newMesh = new Mesh(source.name + "_merged", scene);
  11801. vertexData.applyToMesh(newMesh);
  11802. // Setting properties
  11803. newMesh.material = material;
  11804. newMesh.checkCollisions = source.checkCollisions;
  11805. // Cleaning
  11806. if (disposeSource) {
  11807. for (index = 0; index < meshes.length; index++) {
  11808. meshes[index].dispose();
  11809. }
  11810. }
  11811. return newMesh;
  11812. };
  11813. // Consts
  11814. Mesh._FRONTSIDE = 0;
  11815. Mesh._BACKSIDE = 1;
  11816. Mesh._DOUBLESIDE = 2;
  11817. Mesh._DEFAULTSIDE = 0;
  11818. return Mesh;
  11819. })(BABYLON.AbstractMesh);
  11820. BABYLON.Mesh = Mesh;
  11821. })(BABYLON || (BABYLON = {}));
  11822. //# sourceMappingURL=babylon.mesh.js.map
  11823. var BABYLON;
  11824. (function (BABYLON) {
  11825. var GroundMesh = (function (_super) {
  11826. __extends(GroundMesh, _super);
  11827. function GroundMesh(name, scene) {
  11828. _super.call(this, name, scene);
  11829. this.generateOctree = false;
  11830. this._worldInverse = new BABYLON.Matrix();
  11831. }
  11832. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  11833. get: function () {
  11834. return this._subdivisions;
  11835. },
  11836. enumerable: true,
  11837. configurable: true
  11838. });
  11839. GroundMesh.prototype.optimize = function (chunksCount) {
  11840. this.subdivide(this._subdivisions);
  11841. this.createOrUpdateSubmeshesOctree(32);
  11842. };
  11843. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  11844. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  11845. this.getWorldMatrix().invertToRef(this._worldInverse);
  11846. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  11847. var pickInfo = this.intersects(ray);
  11848. if (pickInfo.hit) {
  11849. return pickInfo.pickedPoint.y;
  11850. }
  11851. return 0;
  11852. };
  11853. return GroundMesh;
  11854. })(BABYLON.Mesh);
  11855. BABYLON.GroundMesh = GroundMesh;
  11856. })(BABYLON || (BABYLON = {}));
  11857. //# sourceMappingURL=babylon.groundMesh.js.map
  11858. var BABYLON;
  11859. (function (BABYLON) {
  11860. /**
  11861. * Creates an instance based on a source mesh.
  11862. */
  11863. var InstancedMesh = (function (_super) {
  11864. __extends(InstancedMesh, _super);
  11865. function InstancedMesh(name, source) {
  11866. _super.call(this, name, source.getScene());
  11867. source.instances.push(this);
  11868. this._sourceMesh = source;
  11869. this.position.copyFrom(source.position);
  11870. this.rotation.copyFrom(source.rotation);
  11871. this.scaling.copyFrom(source.scaling);
  11872. if (source.rotationQuaternion) {
  11873. this.rotationQuaternion = source.rotationQuaternion.clone();
  11874. }
  11875. this.infiniteDistance = source.infiniteDistance;
  11876. this.setPivotMatrix(source.getPivotMatrix());
  11877. this.refreshBoundingInfo();
  11878. this._syncSubMeshes();
  11879. }
  11880. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  11881. // Methods
  11882. get: function () {
  11883. return this._sourceMesh.receiveShadows;
  11884. },
  11885. enumerable: true,
  11886. configurable: true
  11887. });
  11888. Object.defineProperty(InstancedMesh.prototype, "material", {
  11889. get: function () {
  11890. return this._sourceMesh.material;
  11891. },
  11892. enumerable: true,
  11893. configurable: true
  11894. });
  11895. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  11896. get: function () {
  11897. return this._sourceMesh.visibility;
  11898. },
  11899. enumerable: true,
  11900. configurable: true
  11901. });
  11902. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  11903. get: function () {
  11904. return this._sourceMesh.skeleton;
  11905. },
  11906. enumerable: true,
  11907. configurable: true
  11908. });
  11909. InstancedMesh.prototype.getTotalVertices = function () {
  11910. return this._sourceMesh.getTotalVertices();
  11911. };
  11912. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  11913. get: function () {
  11914. return this._sourceMesh;
  11915. },
  11916. enumerable: true,
  11917. configurable: true
  11918. });
  11919. InstancedMesh.prototype.getVerticesData = function (kind) {
  11920. return this._sourceMesh.getVerticesData(kind);
  11921. };
  11922. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  11923. return this._sourceMesh.isVerticesDataPresent(kind);
  11924. };
  11925. InstancedMesh.prototype.getIndices = function () {
  11926. return this._sourceMesh.getIndices();
  11927. };
  11928. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  11929. get: function () {
  11930. return this._sourceMesh._positions;
  11931. },
  11932. enumerable: true,
  11933. configurable: true
  11934. });
  11935. InstancedMesh.prototype.refreshBoundingInfo = function () {
  11936. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11937. if (data) {
  11938. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  11939. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11940. }
  11941. this._updateBoundingInfo();
  11942. };
  11943. InstancedMesh.prototype._preActivate = function () {
  11944. if (this._currentLOD) {
  11945. this._currentLOD._preActivate();
  11946. }
  11947. };
  11948. InstancedMesh.prototype._activate = function (renderId) {
  11949. if (this._currentLOD) {
  11950. this._currentLOD._registerInstanceForRenderId(this, renderId);
  11951. }
  11952. };
  11953. InstancedMesh.prototype.getLOD = function (camera) {
  11954. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  11955. if (this._currentLOD === this.sourceMesh) {
  11956. return this;
  11957. }
  11958. return this._currentLOD;
  11959. };
  11960. InstancedMesh.prototype._syncSubMeshes = function () {
  11961. this.releaseSubMeshes();
  11962. if (this._sourceMesh.subMeshes) {
  11963. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  11964. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  11965. }
  11966. }
  11967. };
  11968. InstancedMesh.prototype._generatePointsArray = function () {
  11969. return this._sourceMesh._generatePointsArray();
  11970. };
  11971. // Clone
  11972. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11973. var result = this._sourceMesh.createInstance(name);
  11974. // Deep copy
  11975. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  11976. // Bounding info
  11977. this.refreshBoundingInfo();
  11978. // Parent
  11979. if (newParent) {
  11980. result.parent = newParent;
  11981. }
  11982. if (!doNotCloneChildren) {
  11983. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11984. var mesh = this.getScene().meshes[index];
  11985. if (mesh.parent === this) {
  11986. mesh.clone(mesh.name, result);
  11987. }
  11988. }
  11989. }
  11990. result.computeWorldMatrix(true);
  11991. return result;
  11992. };
  11993. // Dispoe
  11994. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  11995. // Remove from mesh
  11996. var index = this._sourceMesh.instances.indexOf(this);
  11997. this._sourceMesh.instances.splice(index, 1);
  11998. _super.prototype.dispose.call(this, doNotRecurse);
  11999. };
  12000. return InstancedMesh;
  12001. })(BABYLON.AbstractMesh);
  12002. BABYLON.InstancedMesh = InstancedMesh;
  12003. })(BABYLON || (BABYLON = {}));
  12004. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  12005. (function (BABYLON) {
  12006. var SubMesh = (function () {
  12007. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  12008. if (createBoundingBox === void 0) { createBoundingBox = true; }
  12009. this.materialIndex = materialIndex;
  12010. this.verticesStart = verticesStart;
  12011. this.verticesCount = verticesCount;
  12012. this.indexStart = indexStart;
  12013. this.indexCount = indexCount;
  12014. this._renderId = 0;
  12015. this._mesh = mesh;
  12016. this._renderingMesh = renderingMesh || mesh;
  12017. mesh.subMeshes.push(this);
  12018. this._id = mesh.subMeshes.length - 1;
  12019. if (createBoundingBox) {
  12020. this.refreshBoundingInfo();
  12021. mesh.computeWorldMatrix(true);
  12022. }
  12023. }
  12024. SubMesh.prototype.getBoundingInfo = function () {
  12025. return this._boundingInfo;
  12026. };
  12027. SubMesh.prototype.getMesh = function () {
  12028. return this._mesh;
  12029. };
  12030. SubMesh.prototype.getRenderingMesh = function () {
  12031. return this._renderingMesh;
  12032. };
  12033. SubMesh.prototype.getMaterial = function () {
  12034. var rootMaterial = this._renderingMesh.material;
  12035. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  12036. var multiMaterial = rootMaterial;
  12037. return multiMaterial.getSubMaterial(this.materialIndex);
  12038. }
  12039. if (!rootMaterial) {
  12040. return this._mesh.getScene().defaultMaterial;
  12041. }
  12042. return rootMaterial;
  12043. };
  12044. // Methods
  12045. SubMesh.prototype.refreshBoundingInfo = function () {
  12046. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12047. if (!data) {
  12048. this._boundingInfo = this._mesh._boundingInfo;
  12049. return;
  12050. }
  12051. var indices = this._renderingMesh.getIndices();
  12052. var extend;
  12053. if (this.indexStart === 0 && this.indexCount === indices.length) {
  12054. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  12055. }
  12056. else {
  12057. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  12058. }
  12059. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12060. };
  12061. SubMesh.prototype._checkCollision = function (collider) {
  12062. return this._boundingInfo._checkCollision(collider);
  12063. };
  12064. SubMesh.prototype.updateBoundingInfo = function (world) {
  12065. if (!this._boundingInfo) {
  12066. this.refreshBoundingInfo();
  12067. }
  12068. this._boundingInfo._update(world);
  12069. };
  12070. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  12071. return this._boundingInfo.isInFrustum(frustumPlanes);
  12072. };
  12073. SubMesh.prototype.render = function () {
  12074. this._renderingMesh.render(this);
  12075. };
  12076. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  12077. if (!this._linesIndexBuffer) {
  12078. var linesIndices = [];
  12079. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12080. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  12081. }
  12082. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  12083. this.linesIndexCount = linesIndices.length;
  12084. }
  12085. return this._linesIndexBuffer;
  12086. };
  12087. SubMesh.prototype.canIntersects = function (ray) {
  12088. return ray.intersectsBox(this._boundingInfo.boundingBox);
  12089. };
  12090. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  12091. var intersectInfo = null;
  12092. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12093. var p0 = positions[indices[index]];
  12094. var p1 = positions[indices[index + 1]];
  12095. var p2 = positions[indices[index + 2]];
  12096. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  12097. if (currentIntersectInfo) {
  12098. if (currentIntersectInfo.distance < 0) {
  12099. continue;
  12100. }
  12101. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12102. intersectInfo = currentIntersectInfo;
  12103. intersectInfo.faceId = index / 3;
  12104. if (fastCheck) {
  12105. break;
  12106. }
  12107. }
  12108. }
  12109. }
  12110. return intersectInfo;
  12111. };
  12112. // Clone
  12113. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  12114. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  12115. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  12116. return result;
  12117. };
  12118. // Dispose
  12119. SubMesh.prototype.dispose = function () {
  12120. if (this._linesIndexBuffer) {
  12121. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  12122. this._linesIndexBuffer = null;
  12123. }
  12124. // Remove from mesh
  12125. var index = this._mesh.subMeshes.indexOf(this);
  12126. this._mesh.subMeshes.splice(index, 1);
  12127. };
  12128. // Statics
  12129. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  12130. var minVertexIndex = Number.MAX_VALUE;
  12131. var maxVertexIndex = -Number.MAX_VALUE;
  12132. renderingMesh = renderingMesh || mesh;
  12133. var indices = renderingMesh.getIndices();
  12134. for (var index = startIndex; index < startIndex + indexCount; index++) {
  12135. var vertexIndex = indices[index];
  12136. if (vertexIndex < minVertexIndex)
  12137. minVertexIndex = vertexIndex;
  12138. if (vertexIndex > maxVertexIndex)
  12139. maxVertexIndex = vertexIndex;
  12140. }
  12141. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  12142. };
  12143. return SubMesh;
  12144. })();
  12145. BABYLON.SubMesh = SubMesh;
  12146. })(BABYLON || (BABYLON = {}));
  12147. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  12148. (function (BABYLON) {
  12149. var BaseTexture = (function () {
  12150. function BaseTexture(scene) {
  12151. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  12152. this.hasAlpha = false;
  12153. this.getAlphaFromRGB = false;
  12154. this.level = 1;
  12155. this.isCube = false;
  12156. this.isRenderTarget = false;
  12157. this.animations = new Array();
  12158. this.coordinatesIndex = 0;
  12159. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  12160. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12161. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12162. this.anisotropicFilteringLevel = 4;
  12163. this._scene = scene;
  12164. this._scene.textures.push(this);
  12165. }
  12166. BaseTexture.prototype.getScene = function () {
  12167. return this._scene;
  12168. };
  12169. BaseTexture.prototype.getTextureMatrix = function () {
  12170. return null;
  12171. };
  12172. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  12173. return null;
  12174. };
  12175. BaseTexture.prototype.getInternalTexture = function () {
  12176. return this._texture;
  12177. };
  12178. BaseTexture.prototype.isReady = function () {
  12179. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12180. return true;
  12181. }
  12182. if (this._texture) {
  12183. return this._texture.isReady;
  12184. }
  12185. return false;
  12186. };
  12187. BaseTexture.prototype.getSize = function () {
  12188. if (this._texture._width) {
  12189. return { width: this._texture._width, height: this._texture._height };
  12190. }
  12191. if (this._texture._size) {
  12192. return { width: this._texture._size, height: this._texture._size };
  12193. }
  12194. return { width: 0, height: 0 };
  12195. };
  12196. BaseTexture.prototype.getBaseSize = function () {
  12197. if (!this.isReady())
  12198. return { width: 0, height: 0 };
  12199. if (this._texture._size) {
  12200. return { width: this._texture._size, height: this._texture._size };
  12201. }
  12202. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  12203. };
  12204. BaseTexture.prototype.scale = function (ratio) {
  12205. };
  12206. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  12207. get: function () {
  12208. return false;
  12209. },
  12210. enumerable: true,
  12211. configurable: true
  12212. });
  12213. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  12214. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12215. for (var index = 0; index < texturesCache.length; index++) {
  12216. var texturesCacheEntry = texturesCache[index];
  12217. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12218. texturesCache.splice(index, 1);
  12219. return;
  12220. }
  12221. }
  12222. };
  12223. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  12224. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12225. for (var index = 0; index < texturesCache.length; index++) {
  12226. var texturesCacheEntry = texturesCache[index];
  12227. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12228. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  12229. texturesCacheEntry.references++;
  12230. return texturesCacheEntry;
  12231. }
  12232. }
  12233. }
  12234. return null;
  12235. };
  12236. BaseTexture.prototype.delayLoad = function () {
  12237. };
  12238. BaseTexture.prototype.releaseInternalTexture = function () {
  12239. if (!this._texture) {
  12240. return;
  12241. }
  12242. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12243. this._texture.references--;
  12244. // Final reference ?
  12245. if (this._texture.references === 0) {
  12246. var index = texturesCache.indexOf(this._texture);
  12247. texturesCache.splice(index, 1);
  12248. this._scene.getEngine()._releaseTexture(this._texture);
  12249. delete this._texture;
  12250. }
  12251. };
  12252. BaseTexture.prototype.clone = function () {
  12253. return null;
  12254. };
  12255. BaseTexture.prototype.dispose = function () {
  12256. // Remove from scene
  12257. var index = this._scene.textures.indexOf(this);
  12258. if (index >= 0) {
  12259. this._scene.textures.splice(index, 1);
  12260. }
  12261. if (this._texture === undefined) {
  12262. return;
  12263. }
  12264. this.releaseInternalTexture();
  12265. // Callback
  12266. if (this.onDispose) {
  12267. this.onDispose();
  12268. }
  12269. };
  12270. return BaseTexture;
  12271. })();
  12272. BABYLON.BaseTexture = BaseTexture;
  12273. })(BABYLON || (BABYLON = {}));
  12274. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  12275. (function (BABYLON) {
  12276. var RenderingGroup = (function () {
  12277. function RenderingGroup(index, scene) {
  12278. this.index = index;
  12279. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12280. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12281. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12282. this._scene = scene;
  12283. }
  12284. RenderingGroup.prototype.render = function (customRenderFunction) {
  12285. if (customRenderFunction) {
  12286. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12287. return true;
  12288. }
  12289. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12290. return false;
  12291. }
  12292. var engine = this._scene.getEngine();
  12293. // Opaque
  12294. var subIndex;
  12295. var submesh;
  12296. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12297. submesh = this._opaqueSubMeshes.data[subIndex];
  12298. submesh.render();
  12299. }
  12300. // Alpha test
  12301. engine.setAlphaTesting(true);
  12302. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12303. submesh = this._alphaTestSubMeshes.data[subIndex];
  12304. submesh.render();
  12305. }
  12306. engine.setAlphaTesting(false);
  12307. // Transparent
  12308. if (this._transparentSubMeshes.length) {
  12309. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12310. submesh = this._transparentSubMeshes.data[subIndex];
  12311. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12312. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  12313. }
  12314. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12315. sortedArray.sort(function (a, b) {
  12316. // Alpha index first
  12317. if (a._alphaIndex > b._alphaIndex) {
  12318. return 1;
  12319. }
  12320. if (a._alphaIndex < b._alphaIndex) {
  12321. return -1;
  12322. }
  12323. // Then distance to camera
  12324. if (a._distanceToCamera < b._distanceToCamera) {
  12325. return 1;
  12326. }
  12327. if (a._distanceToCamera > b._distanceToCamera) {
  12328. return -1;
  12329. }
  12330. return 0;
  12331. });
  12332. // Rendering
  12333. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12334. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12335. submesh = sortedArray[subIndex];
  12336. submesh.render();
  12337. }
  12338. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12339. }
  12340. return true;
  12341. };
  12342. RenderingGroup.prototype.prepare = function () {
  12343. this._opaqueSubMeshes.reset();
  12344. this._transparentSubMeshes.reset();
  12345. this._alphaTestSubMeshes.reset();
  12346. };
  12347. RenderingGroup.prototype.dispatch = function (subMesh) {
  12348. var material = subMesh.getMaterial();
  12349. var mesh = subMesh.getMesh();
  12350. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12351. this._transparentSubMeshes.push(subMesh);
  12352. }
  12353. else if (material.needAlphaTesting()) {
  12354. this._alphaTestSubMeshes.push(subMesh);
  12355. }
  12356. else {
  12357. this._opaqueSubMeshes.push(subMesh); // Opaque
  12358. }
  12359. };
  12360. return RenderingGroup;
  12361. })();
  12362. BABYLON.RenderingGroup = RenderingGroup;
  12363. })(BABYLON || (BABYLON = {}));
  12364. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  12365. (function (BABYLON) {
  12366. var RenderingManager = (function () {
  12367. function RenderingManager(scene) {
  12368. this._renderingGroups = new Array();
  12369. this._scene = scene;
  12370. }
  12371. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12372. if (this._scene._activeParticleSystems.length === 0) {
  12373. return;
  12374. }
  12375. // Particles
  12376. var beforeParticlesDate = BABYLON.Tools.Now;
  12377. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12378. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12379. if (particleSystem.renderingGroupId !== index) {
  12380. continue;
  12381. }
  12382. this._clearDepthBuffer();
  12383. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12384. this._scene._activeParticles += particleSystem.render();
  12385. }
  12386. }
  12387. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12388. };
  12389. RenderingManager.prototype._renderSprites = function (index) {
  12390. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12391. return;
  12392. }
  12393. // Sprites
  12394. var beforeSpritessDate = BABYLON.Tools.Now;
  12395. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12396. var spriteManager = this._scene.spriteManagers[id];
  12397. if (spriteManager.renderingGroupId === index) {
  12398. this._clearDepthBuffer();
  12399. spriteManager.render();
  12400. }
  12401. }
  12402. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12403. };
  12404. RenderingManager.prototype._clearDepthBuffer = function () {
  12405. if (this._depthBufferAlreadyCleaned) {
  12406. return;
  12407. }
  12408. this._scene.getEngine().clear(0, false, true);
  12409. this._depthBufferAlreadyCleaned = true;
  12410. };
  12411. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12412. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12413. this._depthBufferAlreadyCleaned = false;
  12414. var renderingGroup = this._renderingGroups[index];
  12415. var needToStepBack = false;
  12416. if (renderingGroup) {
  12417. this._clearDepthBuffer();
  12418. if (!renderingGroup.render(customRenderFunction)) {
  12419. this._renderingGroups.splice(index, 1);
  12420. needToStepBack = true;
  12421. }
  12422. }
  12423. if (renderSprites) {
  12424. this._renderSprites(index);
  12425. }
  12426. if (renderParticles) {
  12427. this._renderParticles(index, activeMeshes);
  12428. }
  12429. if (needToStepBack) {
  12430. index--;
  12431. }
  12432. }
  12433. };
  12434. RenderingManager.prototype.reset = function () {
  12435. for (var index in this._renderingGroups) {
  12436. var renderingGroup = this._renderingGroups[index];
  12437. renderingGroup.prepare();
  12438. }
  12439. };
  12440. RenderingManager.prototype.dispatch = function (subMesh) {
  12441. var mesh = subMesh.getMesh();
  12442. var renderingGroupId = mesh.renderingGroupId || 0;
  12443. if (!this._renderingGroups[renderingGroupId]) {
  12444. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12445. }
  12446. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12447. };
  12448. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12449. return RenderingManager;
  12450. })();
  12451. BABYLON.RenderingManager = RenderingManager;
  12452. })(BABYLON || (BABYLON = {}));
  12453. //# sourceMappingURL=babylon.renderingManager.js.map
  12454. var BABYLON;
  12455. (function (BABYLON) {
  12456. var Texture = (function (_super) {
  12457. __extends(Texture, _super);
  12458. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  12459. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12460. if (onLoad === void 0) { onLoad = null; }
  12461. if (onError === void 0) { onError = null; }
  12462. if (buffer === void 0) { buffer = null; }
  12463. if (deleteBuffer === void 0) { deleteBuffer = false; }
  12464. _super.call(this, scene);
  12465. this.uOffset = 0;
  12466. this.vOffset = 0;
  12467. this.uScale = 1.0;
  12468. this.vScale = 1.0;
  12469. this.uAng = 0;
  12470. this.vAng = 0;
  12471. this.wAng = 0;
  12472. this.name = url;
  12473. this.url = url;
  12474. this._noMipmap = noMipmap;
  12475. this._invertY = invertY;
  12476. this._samplingMode = samplingMode;
  12477. this._buffer = buffer;
  12478. this._deleteBuffer = deleteBuffer;
  12479. if (!url) {
  12480. return;
  12481. }
  12482. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  12483. if (!this._texture) {
  12484. if (!scene.useDelayedTextureLoading) {
  12485. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  12486. if (deleteBuffer) {
  12487. delete this._buffer;
  12488. }
  12489. }
  12490. else {
  12491. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12492. }
  12493. }
  12494. }
  12495. Texture.prototype.delayLoad = function () {
  12496. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12497. return;
  12498. }
  12499. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12500. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  12501. if (!this._texture) {
  12502. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  12503. if (this._deleteBuffer) {
  12504. delete this._buffer;
  12505. }
  12506. }
  12507. };
  12508. Texture.prototype.updateSamplingMode = function (samplingMode) {
  12509. if (!this._texture) {
  12510. return;
  12511. }
  12512. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  12513. };
  12514. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  12515. x -= this.uOffset + 0.5;
  12516. y -= this.vOffset + 0.5;
  12517. z -= 0.5;
  12518. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  12519. t.x *= this.uScale;
  12520. t.y *= this.vScale;
  12521. t.x += 0.5;
  12522. t.y += 0.5;
  12523. t.z += 0.5;
  12524. };
  12525. Texture.prototype.getTextureMatrix = function () {
  12526. 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) {
  12527. return this._cachedTextureMatrix;
  12528. }
  12529. this._cachedUOffset = this.uOffset;
  12530. this._cachedVOffset = this.vOffset;
  12531. this._cachedUScale = this.uScale;
  12532. this._cachedVScale = this.vScale;
  12533. this._cachedUAng = this.uAng;
  12534. this._cachedVAng = this.vAng;
  12535. this._cachedWAng = this.wAng;
  12536. if (!this._cachedTextureMatrix) {
  12537. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12538. this._rowGenerationMatrix = new BABYLON.Matrix();
  12539. this._t0 = BABYLON.Vector3.Zero();
  12540. this._t1 = BABYLON.Vector3.Zero();
  12541. this._t2 = BABYLON.Vector3.Zero();
  12542. }
  12543. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  12544. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  12545. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  12546. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  12547. this._t1.subtractInPlace(this._t0);
  12548. this._t2.subtractInPlace(this._t0);
  12549. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12550. this._cachedTextureMatrix.m[0] = this._t1.x;
  12551. this._cachedTextureMatrix.m[1] = this._t1.y;
  12552. this._cachedTextureMatrix.m[2] = this._t1.z;
  12553. this._cachedTextureMatrix.m[4] = this._t2.x;
  12554. this._cachedTextureMatrix.m[5] = this._t2.y;
  12555. this._cachedTextureMatrix.m[6] = this._t2.z;
  12556. this._cachedTextureMatrix.m[8] = this._t0.x;
  12557. this._cachedTextureMatrix.m[9] = this._t0.y;
  12558. this._cachedTextureMatrix.m[10] = this._t0.z;
  12559. return this._cachedTextureMatrix;
  12560. };
  12561. Texture.prototype.getReflectionTextureMatrix = function () {
  12562. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  12563. return this._cachedTextureMatrix;
  12564. }
  12565. if (!this._cachedTextureMatrix) {
  12566. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12567. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  12568. }
  12569. this._cachedCoordinatesMode = this.coordinatesMode;
  12570. switch (this.coordinatesMode) {
  12571. case Texture.SPHERICAL_MODE:
  12572. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12573. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  12574. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  12575. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  12576. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  12577. break;
  12578. case Texture.PLANAR_MODE:
  12579. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12580. this._cachedTextureMatrix[0] = this.uScale;
  12581. this._cachedTextureMatrix[5] = this.vScale;
  12582. this._cachedTextureMatrix[12] = this.uOffset;
  12583. this._cachedTextureMatrix[13] = this.vOffset;
  12584. break;
  12585. case Texture.PROJECTION_MODE:
  12586. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  12587. this._projectionModeMatrix.m[0] = 0.5;
  12588. this._projectionModeMatrix.m[5] = -0.5;
  12589. this._projectionModeMatrix.m[10] = 0.0;
  12590. this._projectionModeMatrix.m[12] = 0.5;
  12591. this._projectionModeMatrix.m[13] = 0.5;
  12592. this._projectionModeMatrix.m[14] = 1.0;
  12593. this._projectionModeMatrix.m[15] = 1.0;
  12594. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  12595. break;
  12596. default:
  12597. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12598. break;
  12599. }
  12600. return this._cachedTextureMatrix;
  12601. };
  12602. Texture.prototype.clone = function () {
  12603. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  12604. // Base texture
  12605. newTexture.hasAlpha = this.hasAlpha;
  12606. newTexture.level = this.level;
  12607. newTexture.wrapU = this.wrapU;
  12608. newTexture.wrapV = this.wrapV;
  12609. newTexture.coordinatesIndex = this.coordinatesIndex;
  12610. newTexture.coordinatesMode = this.coordinatesMode;
  12611. // Texture
  12612. newTexture.uOffset = this.uOffset;
  12613. newTexture.vOffset = this.vOffset;
  12614. newTexture.uScale = this.uScale;
  12615. newTexture.vScale = this.vScale;
  12616. newTexture.uAng = this.uAng;
  12617. newTexture.vAng = this.vAng;
  12618. newTexture.wAng = this.wAng;
  12619. return newTexture;
  12620. };
  12621. // Statics
  12622. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  12623. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12624. if (onLoad === void 0) { onLoad = null; }
  12625. if (onError === void 0) { onError = null; }
  12626. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  12627. };
  12628. // Constants
  12629. Texture.NEAREST_SAMPLINGMODE = 1;
  12630. Texture.BILINEAR_SAMPLINGMODE = 2;
  12631. Texture.TRILINEAR_SAMPLINGMODE = 3;
  12632. Texture.EXPLICIT_MODE = 0;
  12633. Texture.SPHERICAL_MODE = 1;
  12634. Texture.PLANAR_MODE = 2;
  12635. Texture.CUBIC_MODE = 3;
  12636. Texture.PROJECTION_MODE = 4;
  12637. Texture.SKYBOX_MODE = 5;
  12638. Texture.CLAMP_ADDRESSMODE = 0;
  12639. Texture.WRAP_ADDRESSMODE = 1;
  12640. Texture.MIRROR_ADDRESSMODE = 2;
  12641. return Texture;
  12642. })(BABYLON.BaseTexture);
  12643. BABYLON.Texture = Texture;
  12644. })(BABYLON || (BABYLON = {}));
  12645. //# sourceMappingURL=babylon.texture.js.map
  12646. var BABYLON;
  12647. (function (BABYLON) {
  12648. var CubeTexture = (function (_super) {
  12649. __extends(CubeTexture, _super);
  12650. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  12651. _super.call(this, scene);
  12652. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  12653. this.name = rootUrl;
  12654. this.url = rootUrl;
  12655. this._noMipmap = noMipmap;
  12656. this.hasAlpha = false;
  12657. this._texture = this._getFromCache(rootUrl, noMipmap);
  12658. if (!extensions) {
  12659. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  12660. }
  12661. this._extensions = extensions;
  12662. if (!this._texture) {
  12663. if (!scene.useDelayedTextureLoading) {
  12664. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  12665. }
  12666. else {
  12667. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12668. }
  12669. }
  12670. this.isCube = true;
  12671. this._textureMatrix = BABYLON.Matrix.Identity();
  12672. }
  12673. CubeTexture.prototype.clone = function () {
  12674. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  12675. // Base texture
  12676. newTexture.level = this.level;
  12677. newTexture.wrapU = this.wrapU;
  12678. newTexture.wrapV = this.wrapV;
  12679. newTexture.coordinatesIndex = this.coordinatesIndex;
  12680. newTexture.coordinatesMode = this.coordinatesMode;
  12681. return newTexture;
  12682. };
  12683. // Methods
  12684. CubeTexture.prototype.delayLoad = function () {
  12685. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12686. return;
  12687. }
  12688. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12689. this._texture = this._getFromCache(this.url, this._noMipmap);
  12690. if (!this._texture) {
  12691. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  12692. }
  12693. };
  12694. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  12695. return this._textureMatrix;
  12696. };
  12697. return CubeTexture;
  12698. })(BABYLON.BaseTexture);
  12699. BABYLON.CubeTexture = CubeTexture;
  12700. })(BABYLON || (BABYLON = {}));
  12701. //# sourceMappingURL=babylon.cubeTexture.js.map
  12702. var BABYLON;
  12703. (function (BABYLON) {
  12704. var RenderTargetTexture = (function (_super) {
  12705. __extends(RenderTargetTexture, _super);
  12706. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  12707. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  12708. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  12709. _super.call(this, null, scene, !generateMipMaps);
  12710. this.renderList = new Array();
  12711. this.renderParticles = true;
  12712. this.renderSprites = false;
  12713. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  12714. this._currentRefreshId = -1;
  12715. this._refreshRate = 1;
  12716. this.name = name;
  12717. this.isRenderTarget = true;
  12718. this._size = size;
  12719. this._generateMipMaps = generateMipMaps;
  12720. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  12721. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  12722. // Rendering groups
  12723. this._renderingManager = new BABYLON.RenderingManager(scene);
  12724. }
  12725. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  12726. this._currentRefreshId = -1;
  12727. };
  12728. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  12729. get: function () {
  12730. return this._refreshRate;
  12731. },
  12732. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12733. set: function (value) {
  12734. this._refreshRate = value;
  12735. this.resetRefreshCounter();
  12736. },
  12737. enumerable: true,
  12738. configurable: true
  12739. });
  12740. RenderTargetTexture.prototype._shouldRender = function () {
  12741. if (this._currentRefreshId === -1) {
  12742. this._currentRefreshId = 1;
  12743. return true;
  12744. }
  12745. if (this.refreshRate === this._currentRefreshId) {
  12746. this._currentRefreshId = 1;
  12747. return true;
  12748. }
  12749. this._currentRefreshId++;
  12750. return false;
  12751. };
  12752. RenderTargetTexture.prototype.isReady = function () {
  12753. if (!this.getScene().renderTargetsEnabled) {
  12754. return false;
  12755. }
  12756. return _super.prototype.isReady.call(this);
  12757. };
  12758. RenderTargetTexture.prototype.getRenderSize = function () {
  12759. return this._size;
  12760. };
  12761. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  12762. get: function () {
  12763. return true;
  12764. },
  12765. enumerable: true,
  12766. configurable: true
  12767. });
  12768. RenderTargetTexture.prototype.scale = function (ratio) {
  12769. var newSize = this._size * ratio;
  12770. this.resize(newSize, this._generateMipMaps);
  12771. };
  12772. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  12773. this.releaseInternalTexture();
  12774. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12775. };
  12776. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  12777. var scene = this.getScene();
  12778. var engine = scene.getEngine();
  12779. if (this._waitingRenderList) {
  12780. this.renderList = [];
  12781. for (var index = 0; index < this._waitingRenderList.length; index++) {
  12782. var id = this._waitingRenderList[index];
  12783. this.renderList.push(scene.getMeshByID(id));
  12784. }
  12785. delete this._waitingRenderList;
  12786. }
  12787. if (this.renderList && this.renderList.length === 0) {
  12788. return;
  12789. }
  12790. // Bind
  12791. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  12792. engine.bindFramebuffer(this._texture);
  12793. }
  12794. this._renderingManager.reset();
  12795. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  12796. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  12797. var mesh = currentRenderList[meshIndex];
  12798. if (mesh) {
  12799. if (!mesh.isReady()) {
  12800. // Reset _currentRefreshId
  12801. this.resetRefreshCounter();
  12802. continue;
  12803. }
  12804. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  12805. mesh._activate(scene.getRenderId());
  12806. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  12807. var subMesh = mesh.subMeshes[subIndex];
  12808. scene._activeVertices += subMesh.indexCount;
  12809. this._renderingManager.dispatch(subMesh);
  12810. }
  12811. }
  12812. }
  12813. }
  12814. if (this.onBeforeRender) {
  12815. this.onBeforeRender();
  12816. }
  12817. // Clear
  12818. if (this.onClear) {
  12819. this.onClear(engine);
  12820. }
  12821. else {
  12822. engine.clear(scene.clearColor, true, true);
  12823. }
  12824. if (!this._doNotChangeAspectRatio) {
  12825. scene.updateTransformMatrix(true);
  12826. }
  12827. // Render
  12828. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  12829. if (useCameraPostProcess) {
  12830. scene.postProcessManager._finalizeFrame(false, this._texture);
  12831. }
  12832. if (!this._doNotChangeAspectRatio) {
  12833. scene.updateTransformMatrix(true);
  12834. }
  12835. if (this.onAfterRender) {
  12836. this.onAfterRender();
  12837. }
  12838. // Dump ?
  12839. if (dumpForDebug) {
  12840. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  12841. }
  12842. // Unbind
  12843. engine.unBindFramebuffer(this._texture);
  12844. if (this.onAfterUnbind) {
  12845. this.onAfterUnbind();
  12846. }
  12847. };
  12848. RenderTargetTexture.prototype.clone = function () {
  12849. var textureSize = this.getSize();
  12850. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12851. // Base texture
  12852. newTexture.hasAlpha = this.hasAlpha;
  12853. newTexture.level = this.level;
  12854. // RenderTarget Texture
  12855. newTexture.coordinatesMode = this.coordinatesMode;
  12856. newTexture.renderList = this.renderList.slice(0);
  12857. return newTexture;
  12858. };
  12859. return RenderTargetTexture;
  12860. })(BABYLON.Texture);
  12861. BABYLON.RenderTargetTexture = RenderTargetTexture;
  12862. })(BABYLON || (BABYLON = {}));
  12863. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  12864. var BABYLON;
  12865. (function (BABYLON) {
  12866. var ProceduralTexture = (function (_super) {
  12867. __extends(ProceduralTexture, _super);
  12868. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  12869. if (generateMipMaps === void 0) { generateMipMaps = true; }
  12870. _super.call(this, null, scene, !generateMipMaps);
  12871. this._currentRefreshId = -1;
  12872. this._refreshRate = 1;
  12873. this._vertexDeclaration = [2];
  12874. this._vertexStrideSize = 2 * 4;
  12875. this._uniforms = new Array();
  12876. this._samplers = new Array();
  12877. this._textures = new Array();
  12878. this._floats = new Array();
  12879. this._floatsArrays = {};
  12880. this._colors3 = new Array();
  12881. this._colors4 = new Array();
  12882. this._vectors2 = new Array();
  12883. this._vectors3 = new Array();
  12884. this._matrices = new Array();
  12885. this._fallbackTextureUsed = false;
  12886. scene._proceduralTextures.push(this);
  12887. this.name = name;
  12888. this.isRenderTarget = true;
  12889. this._size = size;
  12890. this._generateMipMaps = generateMipMaps;
  12891. this.setFragment(fragment);
  12892. this._fallbackTexture = fallbackTexture;
  12893. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  12894. // VBO
  12895. var vertices = [];
  12896. vertices.push(1, 1);
  12897. vertices.push(-1, 1);
  12898. vertices.push(-1, -1);
  12899. vertices.push(1, -1);
  12900. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12901. // Indices
  12902. var indices = [];
  12903. indices.push(0);
  12904. indices.push(1);
  12905. indices.push(2);
  12906. indices.push(0);
  12907. indices.push(2);
  12908. indices.push(3);
  12909. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12910. }
  12911. ProceduralTexture.prototype.reset = function () {
  12912. if (this._effect === undefined) {
  12913. return;
  12914. }
  12915. var engine = this.getScene().getEngine();
  12916. engine._releaseEffect(this._effect);
  12917. };
  12918. ProceduralTexture.prototype.isReady = function () {
  12919. var _this = this;
  12920. var engine = this.getScene().getEngine();
  12921. var shaders;
  12922. if (!this._fragment) {
  12923. return false;
  12924. }
  12925. if (this._fallbackTextureUsed) {
  12926. return true;
  12927. }
  12928. if (this._fragment.fragmentElement !== undefined) {
  12929. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  12930. }
  12931. else {
  12932. shaders = { vertex: "procedural", fragment: this._fragment };
  12933. }
  12934. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  12935. _this.releaseInternalTexture();
  12936. if (_this._fallbackTexture) {
  12937. _this._texture = _this._fallbackTexture._texture;
  12938. _this._texture.references++;
  12939. }
  12940. _this._fallbackTextureUsed = true;
  12941. });
  12942. return this._effect.isReady();
  12943. };
  12944. ProceduralTexture.prototype.resetRefreshCounter = function () {
  12945. this._currentRefreshId = -1;
  12946. };
  12947. ProceduralTexture.prototype.setFragment = function (fragment) {
  12948. this._fragment = fragment;
  12949. };
  12950. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  12951. get: function () {
  12952. return this._refreshRate;
  12953. },
  12954. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12955. set: function (value) {
  12956. this._refreshRate = value;
  12957. this.resetRefreshCounter();
  12958. },
  12959. enumerable: true,
  12960. configurable: true
  12961. });
  12962. ProceduralTexture.prototype._shouldRender = function () {
  12963. if (!this.isReady() || !this._texture) {
  12964. return false;
  12965. }
  12966. if (this._fallbackTextureUsed) {
  12967. return false;
  12968. }
  12969. if (this._currentRefreshId === -1) {
  12970. this._currentRefreshId = 1;
  12971. return true;
  12972. }
  12973. if (this.refreshRate === this._currentRefreshId) {
  12974. this._currentRefreshId = 1;
  12975. return true;
  12976. }
  12977. this._currentRefreshId++;
  12978. return false;
  12979. };
  12980. ProceduralTexture.prototype.getRenderSize = function () {
  12981. return this._size;
  12982. };
  12983. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  12984. if (this._fallbackTextureUsed) {
  12985. return;
  12986. }
  12987. this.releaseInternalTexture();
  12988. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12989. };
  12990. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  12991. if (this._uniforms.indexOf(uniformName) === -1) {
  12992. this._uniforms.push(uniformName);
  12993. }
  12994. };
  12995. ProceduralTexture.prototype.setTexture = function (name, texture) {
  12996. if (this._samplers.indexOf(name) === -1) {
  12997. this._samplers.push(name);
  12998. }
  12999. this._textures[name] = texture;
  13000. return this;
  13001. };
  13002. ProceduralTexture.prototype.setFloat = function (name, value) {
  13003. this._checkUniform(name);
  13004. this._floats[name] = value;
  13005. return this;
  13006. };
  13007. ProceduralTexture.prototype.setFloats = function (name, value) {
  13008. this._checkUniform(name);
  13009. this._floatsArrays[name] = value;
  13010. return this;
  13011. };
  13012. ProceduralTexture.prototype.setColor3 = function (name, value) {
  13013. this._checkUniform(name);
  13014. this._colors3[name] = value;
  13015. return this;
  13016. };
  13017. ProceduralTexture.prototype.setColor4 = function (name, value) {
  13018. this._checkUniform(name);
  13019. this._colors4[name] = value;
  13020. return this;
  13021. };
  13022. ProceduralTexture.prototype.setVector2 = function (name, value) {
  13023. this._checkUniform(name);
  13024. this._vectors2[name] = value;
  13025. return this;
  13026. };
  13027. ProceduralTexture.prototype.setVector3 = function (name, value) {
  13028. this._checkUniform(name);
  13029. this._vectors3[name] = value;
  13030. return this;
  13031. };
  13032. ProceduralTexture.prototype.setMatrix = function (name, value) {
  13033. this._checkUniform(name);
  13034. this._matrices[name] = value;
  13035. return this;
  13036. };
  13037. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13038. var scene = this.getScene();
  13039. var engine = scene.getEngine();
  13040. engine.bindFramebuffer(this._texture);
  13041. // Clear
  13042. engine.clear(scene.clearColor, true, true);
  13043. // Render
  13044. engine.enableEffect(this._effect);
  13045. engine.setState(false);
  13046. for (var name in this._textures) {
  13047. this._effect.setTexture(name, this._textures[name]);
  13048. }
  13049. for (name in this._floats) {
  13050. this._effect.setFloat(name, this._floats[name]);
  13051. }
  13052. for (name in this._floatsArrays) {
  13053. this._effect.setArray(name, this._floatsArrays[name]);
  13054. }
  13055. for (name in this._colors3) {
  13056. this._effect.setColor3(name, this._colors3[name]);
  13057. }
  13058. for (name in this._colors4) {
  13059. var color = this._colors4[name];
  13060. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  13061. }
  13062. for (name in this._vectors2) {
  13063. this._effect.setVector2(name, this._vectors2[name]);
  13064. }
  13065. for (name in this._vectors3) {
  13066. this._effect.setVector3(name, this._vectors3[name]);
  13067. }
  13068. for (name in this._matrices) {
  13069. this._effect.setMatrix(name, this._matrices[name]);
  13070. }
  13071. // VBOs
  13072. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13073. // Draw order
  13074. engine.draw(true, 0, 6);
  13075. // Unbind
  13076. engine.unBindFramebuffer(this._texture);
  13077. };
  13078. ProceduralTexture.prototype.clone = function () {
  13079. var textureSize = this.getSize();
  13080. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  13081. // Base texture
  13082. newTexture.hasAlpha = this.hasAlpha;
  13083. newTexture.level = this.level;
  13084. // RenderTarget Texture
  13085. newTexture.coordinatesMode = this.coordinatesMode;
  13086. return newTexture;
  13087. };
  13088. ProceduralTexture.prototype.dispose = function () {
  13089. var index = this.getScene()._proceduralTextures.indexOf(this);
  13090. if (index >= 0) {
  13091. this.getScene()._proceduralTextures.splice(index, 1);
  13092. }
  13093. _super.prototype.dispose.call(this);
  13094. };
  13095. return ProceduralTexture;
  13096. })(BABYLON.Texture);
  13097. BABYLON.ProceduralTexture = ProceduralTexture;
  13098. })(BABYLON || (BABYLON = {}));
  13099. //# sourceMappingURL=babylon.proceduralTexture.js.map
  13100. var BABYLON;
  13101. (function (BABYLON) {
  13102. var WoodProceduralTexture = (function (_super) {
  13103. __extends(WoodProceduralTexture, _super);
  13104. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13105. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  13106. this._ampScale = 100.0;
  13107. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  13108. this.updateShaderUniforms();
  13109. this.refreshRate = 0;
  13110. }
  13111. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  13112. this.setFloat("ampScale", this._ampScale);
  13113. this.setColor3("woodColor", this._woodColor);
  13114. };
  13115. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  13116. get: function () {
  13117. return this._ampScale;
  13118. },
  13119. set: function (value) {
  13120. this._ampScale = value;
  13121. this.updateShaderUniforms();
  13122. },
  13123. enumerable: true,
  13124. configurable: true
  13125. });
  13126. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  13127. get: function () {
  13128. return this._woodColor;
  13129. },
  13130. set: function (value) {
  13131. this._woodColor = value;
  13132. this.updateShaderUniforms();
  13133. },
  13134. enumerable: true,
  13135. configurable: true
  13136. });
  13137. return WoodProceduralTexture;
  13138. })(BABYLON.ProceduralTexture);
  13139. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  13140. var FireProceduralTexture = (function (_super) {
  13141. __extends(FireProceduralTexture, _super);
  13142. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13143. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  13144. this._time = 0.0;
  13145. this._speed = new BABYLON.Vector2(0.5, 0.3);
  13146. this._shift = 1.6;
  13147. this._autoGenerateTime = true;
  13148. this._alphaThreshold = 0.5;
  13149. this._fireColors = FireProceduralTexture.RedFireColors;
  13150. this.updateShaderUniforms();
  13151. this.refreshRate = 1;
  13152. }
  13153. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  13154. this.setFloat("time", this._time);
  13155. this.setVector2("speed", this._speed);
  13156. this.setFloat("shift", this._shift);
  13157. this.setColor3("c1", this._fireColors[0]);
  13158. this.setColor3("c2", this._fireColors[1]);
  13159. this.setColor3("c3", this._fireColors[2]);
  13160. this.setColor3("c4", this._fireColors[3]);
  13161. this.setColor3("c5", this._fireColors[4]);
  13162. this.setColor3("c6", this._fireColors[5]);
  13163. this.setFloat("alphaThreshold", this._alphaThreshold);
  13164. };
  13165. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13166. if (this._autoGenerateTime) {
  13167. this._time += this.getScene().getAnimationRatio() * 0.03;
  13168. this.updateShaderUniforms();
  13169. }
  13170. _super.prototype.render.call(this, useCameraPostProcess);
  13171. };
  13172. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  13173. get: function () {
  13174. return [
  13175. new BABYLON.Color3(0.5, 0.0, 1.0),
  13176. new BABYLON.Color3(0.9, 0.0, 1.0),
  13177. new BABYLON.Color3(0.2, 0.0, 1.0),
  13178. new BABYLON.Color3(1.0, 0.9, 1.0),
  13179. new BABYLON.Color3(0.1, 0.1, 1.0),
  13180. new BABYLON.Color3(0.9, 0.9, 1.0)
  13181. ];
  13182. },
  13183. enumerable: true,
  13184. configurable: true
  13185. });
  13186. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  13187. get: function () {
  13188. return [
  13189. new BABYLON.Color3(0.5, 1.0, 0.0),
  13190. new BABYLON.Color3(0.5, 1.0, 0.0),
  13191. new BABYLON.Color3(0.3, 0.4, 0.0),
  13192. new BABYLON.Color3(0.5, 1.0, 0.0),
  13193. new BABYLON.Color3(0.2, 0.0, 0.0),
  13194. new BABYLON.Color3(0.5, 1.0, 0.0)
  13195. ];
  13196. },
  13197. enumerable: true,
  13198. configurable: true
  13199. });
  13200. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  13201. get: function () {
  13202. return [
  13203. new BABYLON.Color3(0.5, 0.0, 0.1),
  13204. new BABYLON.Color3(0.9, 0.0, 0.0),
  13205. new BABYLON.Color3(0.2, 0.0, 0.0),
  13206. new BABYLON.Color3(1.0, 0.9, 0.0),
  13207. new BABYLON.Color3(0.1, 0.1, 0.1),
  13208. new BABYLON.Color3(0.9, 0.9, 0.9)
  13209. ];
  13210. },
  13211. enumerable: true,
  13212. configurable: true
  13213. });
  13214. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  13215. get: function () {
  13216. return [
  13217. new BABYLON.Color3(0.1, 0.0, 0.5),
  13218. new BABYLON.Color3(0.0, 0.0, 0.5),
  13219. new BABYLON.Color3(0.1, 0.0, 0.2),
  13220. new BABYLON.Color3(0.0, 0.0, 1.0),
  13221. new BABYLON.Color3(0.1, 0.2, 0.3),
  13222. new BABYLON.Color3(0.0, 0.2, 0.9)
  13223. ];
  13224. },
  13225. enumerable: true,
  13226. configurable: true
  13227. });
  13228. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  13229. get: function () {
  13230. return this._fireColors;
  13231. },
  13232. set: function (value) {
  13233. this._fireColors = value;
  13234. this.updateShaderUniforms();
  13235. },
  13236. enumerable: true,
  13237. configurable: true
  13238. });
  13239. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  13240. get: function () {
  13241. return this._time;
  13242. },
  13243. set: function (value) {
  13244. this._time = value;
  13245. this.updateShaderUniforms();
  13246. },
  13247. enumerable: true,
  13248. configurable: true
  13249. });
  13250. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  13251. get: function () {
  13252. return this._speed;
  13253. },
  13254. set: function (value) {
  13255. this._speed = value;
  13256. this.updateShaderUniforms();
  13257. },
  13258. enumerable: true,
  13259. configurable: true
  13260. });
  13261. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  13262. get: function () {
  13263. return this._shift;
  13264. },
  13265. set: function (value) {
  13266. this._shift = value;
  13267. this.updateShaderUniforms();
  13268. },
  13269. enumerable: true,
  13270. configurable: true
  13271. });
  13272. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  13273. get: function () {
  13274. return this._alphaThreshold;
  13275. },
  13276. set: function (value) {
  13277. this._alphaThreshold = value;
  13278. this.updateShaderUniforms();
  13279. },
  13280. enumerable: true,
  13281. configurable: true
  13282. });
  13283. return FireProceduralTexture;
  13284. })(BABYLON.ProceduralTexture);
  13285. BABYLON.FireProceduralTexture = FireProceduralTexture;
  13286. var CloudProceduralTexture = (function (_super) {
  13287. __extends(CloudProceduralTexture, _super);
  13288. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13289. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  13290. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  13291. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  13292. this.updateShaderUniforms();
  13293. this.refreshRate = 0;
  13294. }
  13295. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  13296. this.setColor3("skyColor", this._skyColor);
  13297. this.setColor3("cloudColor", this._cloudColor);
  13298. };
  13299. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  13300. get: function () {
  13301. return this._skyColor;
  13302. },
  13303. set: function (value) {
  13304. this._skyColor = value;
  13305. this.updateShaderUniforms();
  13306. },
  13307. enumerable: true,
  13308. configurable: true
  13309. });
  13310. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  13311. get: function () {
  13312. return this._cloudColor;
  13313. },
  13314. set: function (value) {
  13315. this._cloudColor = value;
  13316. this.updateShaderUniforms();
  13317. },
  13318. enumerable: true,
  13319. configurable: true
  13320. });
  13321. return CloudProceduralTexture;
  13322. })(BABYLON.ProceduralTexture);
  13323. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  13324. var GrassProceduralTexture = (function (_super) {
  13325. __extends(GrassProceduralTexture, _super);
  13326. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13327. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  13328. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  13329. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  13330. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  13331. this._groundColor = new BABYLON.Color3(1, 1, 1);
  13332. this._grassColors = [
  13333. new BABYLON.Color3(0.29, 0.38, 0.02),
  13334. new BABYLON.Color3(0.36, 0.49, 0.09),
  13335. new BABYLON.Color3(0.51, 0.6, 0.28)
  13336. ];
  13337. this.updateShaderUniforms();
  13338. this.refreshRate = 0;
  13339. }
  13340. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  13341. this.setColor3("herb1Color", this._grassColors[0]);
  13342. this.setColor3("herb2Color", this._grassColors[1]);
  13343. this.setColor3("herb3Color", this._grassColors[2]);
  13344. this.setColor3("groundColor", this._groundColor);
  13345. };
  13346. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  13347. get: function () {
  13348. return this._grassColors;
  13349. },
  13350. set: function (value) {
  13351. this._grassColors = value;
  13352. this.updateShaderUniforms();
  13353. },
  13354. enumerable: true,
  13355. configurable: true
  13356. });
  13357. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  13358. get: function () {
  13359. return this._groundColor;
  13360. },
  13361. set: function (value) {
  13362. this.groundColor = value;
  13363. this.updateShaderUniforms();
  13364. },
  13365. enumerable: true,
  13366. configurable: true
  13367. });
  13368. return GrassProceduralTexture;
  13369. })(BABYLON.ProceduralTexture);
  13370. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  13371. var RoadProceduralTexture = (function (_super) {
  13372. __extends(RoadProceduralTexture, _super);
  13373. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13374. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  13375. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  13376. this.updateShaderUniforms();
  13377. this.refreshRate = 0;
  13378. }
  13379. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  13380. this.setColor3("roadColor", this._roadColor);
  13381. };
  13382. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  13383. get: function () {
  13384. return this._roadColor;
  13385. },
  13386. set: function (value) {
  13387. this._roadColor = value;
  13388. this.updateShaderUniforms();
  13389. },
  13390. enumerable: true,
  13391. configurable: true
  13392. });
  13393. return RoadProceduralTexture;
  13394. })(BABYLON.ProceduralTexture);
  13395. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  13396. var BrickProceduralTexture = (function (_super) {
  13397. __extends(BrickProceduralTexture, _super);
  13398. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13399. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  13400. this._numberOfBricksHeight = 15;
  13401. this._numberOfBricksWidth = 5;
  13402. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13403. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13404. this.updateShaderUniforms();
  13405. this.refreshRate = 0;
  13406. }
  13407. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  13408. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  13409. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  13410. this.setColor3("brickColor", this._brickColor);
  13411. this.setColor3("jointColor", this._jointColor);
  13412. };
  13413. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  13414. get: function () {
  13415. return this._numberOfBricksHeight;
  13416. },
  13417. enumerable: true,
  13418. configurable: true
  13419. });
  13420. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  13421. set: function (value) {
  13422. this._numberOfBricksHeight = value;
  13423. this.updateShaderUniforms();
  13424. },
  13425. enumerable: true,
  13426. configurable: true
  13427. });
  13428. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  13429. get: function () {
  13430. return this._numberOfBricksWidth;
  13431. },
  13432. set: function (value) {
  13433. this._numberOfBricksHeight = value;
  13434. this.updateShaderUniforms();
  13435. },
  13436. enumerable: true,
  13437. configurable: true
  13438. });
  13439. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  13440. get: function () {
  13441. return this._jointColor;
  13442. },
  13443. set: function (value) {
  13444. this._jointColor = value;
  13445. this.updateShaderUniforms();
  13446. },
  13447. enumerable: true,
  13448. configurable: true
  13449. });
  13450. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  13451. get: function () {
  13452. return this._brickColor;
  13453. },
  13454. set: function (value) {
  13455. this._brickColor = value;
  13456. this.updateShaderUniforms();
  13457. },
  13458. enumerable: true,
  13459. configurable: true
  13460. });
  13461. return BrickProceduralTexture;
  13462. })(BABYLON.ProceduralTexture);
  13463. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  13464. var MarbleProceduralTexture = (function (_super) {
  13465. __extends(MarbleProceduralTexture, _super);
  13466. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13467. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  13468. this._numberOfTilesHeight = 3;
  13469. this._numberOfTilesWidth = 3;
  13470. this._amplitude = 9.0;
  13471. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13472. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13473. this.updateShaderUniforms();
  13474. this.refreshRate = 0;
  13475. }
  13476. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  13477. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  13478. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  13479. this.setFloat("amplitude", this._amplitude);
  13480. this.setColor3("marbleColor", this._marbleColor);
  13481. this.setColor3("jointColor", this._jointColor);
  13482. };
  13483. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  13484. get: function () {
  13485. return this._numberOfTilesHeight;
  13486. },
  13487. set: function (value) {
  13488. this._numberOfTilesHeight = value;
  13489. this.updateShaderUniforms();
  13490. },
  13491. enumerable: true,
  13492. configurable: true
  13493. });
  13494. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  13495. get: function () {
  13496. return this._numberOfTilesWidth;
  13497. },
  13498. set: function (value) {
  13499. this._numberOfTilesWidth = value;
  13500. this.updateShaderUniforms();
  13501. },
  13502. enumerable: true,
  13503. configurable: true
  13504. });
  13505. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  13506. get: function () {
  13507. return this._jointColor;
  13508. },
  13509. set: function (value) {
  13510. this._jointColor = value;
  13511. this.updateShaderUniforms();
  13512. },
  13513. enumerable: true,
  13514. configurable: true
  13515. });
  13516. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  13517. get: function () {
  13518. return this._marbleColor;
  13519. },
  13520. set: function (value) {
  13521. this._marbleColor = value;
  13522. this.updateShaderUniforms();
  13523. },
  13524. enumerable: true,
  13525. configurable: true
  13526. });
  13527. return MarbleProceduralTexture;
  13528. })(BABYLON.ProceduralTexture);
  13529. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  13530. })(BABYLON || (BABYLON = {}));
  13531. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  13532. var BABYLON;
  13533. (function (BABYLON) {
  13534. var CustomProceduralTexture = (function (_super) {
  13535. __extends(CustomProceduralTexture, _super);
  13536. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  13537. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  13538. this._animate = true;
  13539. this._time = 0;
  13540. this._texturePath = texturePath;
  13541. //Try to load json
  13542. this.loadJson(texturePath);
  13543. this.refreshRate = 1;
  13544. }
  13545. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  13546. var _this = this;
  13547. var that = this;
  13548. function noConfigFile() {
  13549. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  13550. try {
  13551. that.setFragment(that._texturePath);
  13552. }
  13553. catch (ex) {
  13554. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  13555. }
  13556. }
  13557. var configFileUrl = jsonUrl + "/config.json";
  13558. var xhr = new XMLHttpRequest();
  13559. xhr.open("GET", configFileUrl, true);
  13560. xhr.addEventListener("load", function () {
  13561. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13562. try {
  13563. _this._config = JSON.parse(xhr.response);
  13564. _this.updateShaderUniforms();
  13565. _this.updateTextures();
  13566. _this.setFragment(_this._texturePath + "/custom");
  13567. _this._animate = _this._config.animate;
  13568. _this.refreshRate = _this._config.refreshrate;
  13569. }
  13570. catch (ex) {
  13571. noConfigFile();
  13572. }
  13573. }
  13574. else {
  13575. noConfigFile();
  13576. }
  13577. }, false);
  13578. xhr.addEventListener("error", function () {
  13579. noConfigFile();
  13580. }, false);
  13581. try {
  13582. xhr.send();
  13583. }
  13584. catch (ex) {
  13585. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  13586. }
  13587. };
  13588. CustomProceduralTexture.prototype.isReady = function () {
  13589. if (!_super.prototype.isReady.call(this)) {
  13590. return false;
  13591. }
  13592. for (var name in this._textures) {
  13593. var texture = this._textures[name];
  13594. if (!texture.isReady()) {
  13595. return false;
  13596. }
  13597. }
  13598. return true;
  13599. };
  13600. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13601. if (this._animate) {
  13602. this._time += this.getScene().getAnimationRatio() * 0.03;
  13603. this.updateShaderUniforms();
  13604. }
  13605. _super.prototype.render.call(this, useCameraPostProcess);
  13606. };
  13607. CustomProceduralTexture.prototype.updateTextures = function () {
  13608. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  13609. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  13610. }
  13611. };
  13612. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  13613. if (this._config) {
  13614. for (var j = 0; j < this._config.uniforms.length; j++) {
  13615. var uniform = this._config.uniforms[j];
  13616. switch (uniform.type) {
  13617. case "float":
  13618. this.setFloat(uniform.name, uniform.value);
  13619. break;
  13620. case "color3":
  13621. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  13622. break;
  13623. case "color4":
  13624. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  13625. break;
  13626. case "vector2":
  13627. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  13628. break;
  13629. case "vector3":
  13630. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  13631. break;
  13632. }
  13633. }
  13634. }
  13635. this.setFloat("time", this._time);
  13636. };
  13637. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  13638. get: function () {
  13639. return this._animate;
  13640. },
  13641. set: function (value) {
  13642. this._animate = value;
  13643. },
  13644. enumerable: true,
  13645. configurable: true
  13646. });
  13647. return CustomProceduralTexture;
  13648. })(BABYLON.ProceduralTexture);
  13649. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  13650. })(BABYLON || (BABYLON = {}));
  13651. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  13652. var BABYLON;
  13653. (function (BABYLON) {
  13654. var MirrorTexture = (function (_super) {
  13655. __extends(MirrorTexture, _super);
  13656. function MirrorTexture(name, size, scene, generateMipMaps) {
  13657. var _this = this;
  13658. _super.call(this, name, size, scene, generateMipMaps, true);
  13659. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  13660. this._transformMatrix = BABYLON.Matrix.Zero();
  13661. this._mirrorMatrix = BABYLON.Matrix.Zero();
  13662. this.onBeforeRender = function () {
  13663. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  13664. _this._savedViewMatrix = scene.getViewMatrix();
  13665. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  13666. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  13667. scene.clipPlane = _this.mirrorPlane;
  13668. scene.getEngine().cullBackFaces = false;
  13669. };
  13670. this.onAfterRender = function () {
  13671. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  13672. scene.getEngine().cullBackFaces = true;
  13673. delete scene.clipPlane;
  13674. };
  13675. }
  13676. MirrorTexture.prototype.clone = function () {
  13677. var textureSize = this.getSize();
  13678. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13679. // Base texture
  13680. newTexture.hasAlpha = this.hasAlpha;
  13681. newTexture.level = this.level;
  13682. // Mirror Texture
  13683. newTexture.mirrorPlane = this.mirrorPlane.clone();
  13684. newTexture.renderList = this.renderList.slice(0);
  13685. return newTexture;
  13686. };
  13687. return MirrorTexture;
  13688. })(BABYLON.RenderTargetTexture);
  13689. BABYLON.MirrorTexture = MirrorTexture;
  13690. })(BABYLON || (BABYLON = {}));
  13691. //# sourceMappingURL=babylon.mirrorTexture.js.map
  13692. var BABYLON;
  13693. (function (BABYLON) {
  13694. var DynamicTexture = (function (_super) {
  13695. __extends(DynamicTexture, _super);
  13696. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  13697. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13698. _super.call(this, null, scene, !generateMipMaps);
  13699. this.name = name;
  13700. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13701. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13702. this._generateMipMaps = generateMipMaps;
  13703. if (options.getContext) {
  13704. this._canvas = options;
  13705. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13706. }
  13707. else {
  13708. this._canvas = document.createElement("canvas");
  13709. if (options.width) {
  13710. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13711. }
  13712. else {
  13713. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  13714. }
  13715. }
  13716. var textureSize = this.getSize();
  13717. this._canvas.width = textureSize.width;
  13718. this._canvas.height = textureSize.height;
  13719. this._context = this._canvas.getContext("2d");
  13720. }
  13721. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  13722. get: function () {
  13723. return true;
  13724. },
  13725. enumerable: true,
  13726. configurable: true
  13727. });
  13728. DynamicTexture.prototype.scale = function (ratio) {
  13729. var textureSize = this.getSize();
  13730. textureSize.width *= ratio;
  13731. textureSize.height *= ratio;
  13732. this._canvas.width = textureSize.width;
  13733. this._canvas.height = textureSize.height;
  13734. this.releaseInternalTexture();
  13735. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  13736. };
  13737. DynamicTexture.prototype.getContext = function () {
  13738. return this._context;
  13739. };
  13740. DynamicTexture.prototype.clear = function () {
  13741. var size = this.getSize();
  13742. this._context.fillRect(0, 0, size.width, size.height);
  13743. };
  13744. DynamicTexture.prototype.update = function (invertY) {
  13745. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  13746. };
  13747. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  13748. if (update === void 0) { update = true; }
  13749. var size = this.getSize();
  13750. if (clearColor) {
  13751. this._context.fillStyle = clearColor;
  13752. this._context.fillRect(0, 0, size.width, size.height);
  13753. }
  13754. this._context.font = font;
  13755. if (x === null) {
  13756. var textSize = this._context.measureText(text);
  13757. x = (size.width - textSize.width) / 2;
  13758. }
  13759. this._context.fillStyle = color;
  13760. this._context.fillText(text, x, y);
  13761. if (update) {
  13762. this.update(invertY);
  13763. }
  13764. };
  13765. DynamicTexture.prototype.clone = function () {
  13766. var textureSize = this.getSize();
  13767. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13768. // Base texture
  13769. newTexture.hasAlpha = this.hasAlpha;
  13770. newTexture.level = this.level;
  13771. // Dynamic Texture
  13772. newTexture.wrapU = this.wrapU;
  13773. newTexture.wrapV = this.wrapV;
  13774. return newTexture;
  13775. };
  13776. return DynamicTexture;
  13777. })(BABYLON.Texture);
  13778. BABYLON.DynamicTexture = DynamicTexture;
  13779. })(BABYLON || (BABYLON = {}));
  13780. //# sourceMappingURL=babylon.dynamicTexture.js.map
  13781. var BABYLON;
  13782. (function (BABYLON) {
  13783. var VideoTexture = (function (_super) {
  13784. __extends(VideoTexture, _super);
  13785. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  13786. var _this = this;
  13787. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13788. _super.call(this, null, scene, !generateMipMaps, invertY);
  13789. this._autoLaunch = true;
  13790. this.name = name;
  13791. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  13792. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  13793. var requiredWidth = size.width || size;
  13794. var requiredHeight = size.height || size;
  13795. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  13796. var textureSize = this.getSize();
  13797. this.video = document.createElement("video");
  13798. this.video.width = textureSize.width;
  13799. this.video.height = textureSize.height;
  13800. this.video.autoplay = false;
  13801. this.video.loop = true;
  13802. this.video.addEventListener("canplaythrough", function () {
  13803. if (_this._texture) {
  13804. _this._texture.isReady = true;
  13805. }
  13806. });
  13807. urls.forEach(function (url) {
  13808. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  13809. var source = document.createElement("source");
  13810. source.src = url;
  13811. _this.video.appendChild(source);
  13812. });
  13813. this._lastUpdate = BABYLON.Tools.Now;
  13814. }
  13815. VideoTexture.prototype.update = function () {
  13816. if (this._autoLaunch) {
  13817. this._autoLaunch = false;
  13818. this.video.play();
  13819. }
  13820. var now = BABYLON.Tools.Now;
  13821. if (now - this._lastUpdate < 15) {
  13822. return false;
  13823. }
  13824. this._lastUpdate = now;
  13825. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  13826. return true;
  13827. };
  13828. return VideoTexture;
  13829. })(BABYLON.Texture);
  13830. BABYLON.VideoTexture = VideoTexture;
  13831. })(BABYLON || (BABYLON = {}));
  13832. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  13833. (function (BABYLON) {
  13834. var EffectFallbacks = (function () {
  13835. function EffectFallbacks() {
  13836. this._defines = {};
  13837. this._currentRank = 32;
  13838. this._maxRank = -1;
  13839. }
  13840. EffectFallbacks.prototype.addFallback = function (rank, define) {
  13841. if (!this._defines[rank]) {
  13842. if (rank < this._currentRank) {
  13843. this._currentRank = rank;
  13844. }
  13845. if (rank > this._maxRank) {
  13846. this._maxRank = rank;
  13847. }
  13848. this._defines[rank] = new Array();
  13849. }
  13850. this._defines[rank].push(define);
  13851. };
  13852. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  13853. get: function () {
  13854. return this._currentRank <= this._maxRank;
  13855. },
  13856. enumerable: true,
  13857. configurable: true
  13858. });
  13859. EffectFallbacks.prototype.reduce = function (currentDefines) {
  13860. var currentFallbacks = this._defines[this._currentRank];
  13861. for (var index = 0; index < currentFallbacks.length; index++) {
  13862. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  13863. }
  13864. this._currentRank++;
  13865. return currentDefines;
  13866. };
  13867. return EffectFallbacks;
  13868. })();
  13869. BABYLON.EffectFallbacks = EffectFallbacks;
  13870. var Effect = (function () {
  13871. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  13872. var _this = this;
  13873. this._isReady = false;
  13874. this._compilationError = "";
  13875. this._valueCache = [];
  13876. this._engine = engine;
  13877. this.name = baseName;
  13878. this.defines = defines;
  13879. this._uniformsNames = uniformsNames.concat(samplers);
  13880. this._samplers = samplers;
  13881. this._attributesNames = attributesNames;
  13882. this.onError = onError;
  13883. this.onCompiled = onCompiled;
  13884. var vertexSource;
  13885. var fragmentSource;
  13886. if (baseName.vertexElement) {
  13887. vertexSource = document.getElementById(baseName.vertexElement);
  13888. if (!vertexSource) {
  13889. vertexSource = baseName.vertexElement;
  13890. }
  13891. }
  13892. else {
  13893. vertexSource = baseName.vertex || baseName;
  13894. }
  13895. if (baseName.fragmentElement) {
  13896. fragmentSource = document.getElementById(baseName.fragmentElement);
  13897. if (!fragmentSource) {
  13898. fragmentSource = baseName.fragmentElement;
  13899. }
  13900. }
  13901. else {
  13902. fragmentSource = baseName.fragment || baseName;
  13903. }
  13904. this._loadVertexShader(vertexSource, function (vertexCode) {
  13905. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  13906. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  13907. });
  13908. });
  13909. }
  13910. // Properties
  13911. Effect.prototype.isReady = function () {
  13912. return this._isReady;
  13913. };
  13914. Effect.prototype.getProgram = function () {
  13915. return this._program;
  13916. };
  13917. Effect.prototype.getAttributesNames = function () {
  13918. return this._attributesNames;
  13919. };
  13920. Effect.prototype.getAttributeLocation = function (index) {
  13921. return this._attributes[index];
  13922. };
  13923. Effect.prototype.getAttributeLocationByName = function (name) {
  13924. var index = this._attributesNames.indexOf(name);
  13925. return this._attributes[index];
  13926. };
  13927. Effect.prototype.getAttributesCount = function () {
  13928. return this._attributes.length;
  13929. };
  13930. Effect.prototype.getUniformIndex = function (uniformName) {
  13931. return this._uniformsNames.indexOf(uniformName);
  13932. };
  13933. Effect.prototype.getUniform = function (uniformName) {
  13934. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  13935. };
  13936. Effect.prototype.getSamplers = function () {
  13937. return this._samplers;
  13938. };
  13939. Effect.prototype.getCompilationError = function () {
  13940. return this._compilationError;
  13941. };
  13942. // Methods
  13943. Effect.prototype._loadVertexShader = function (vertex, callback) {
  13944. // DOM element ?
  13945. if (vertex instanceof HTMLElement) {
  13946. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  13947. callback(vertexCode);
  13948. return;
  13949. }
  13950. // Is in local store ?
  13951. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  13952. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  13953. return;
  13954. }
  13955. var vertexShaderUrl;
  13956. if (vertex[0] === ".") {
  13957. vertexShaderUrl = vertex;
  13958. }
  13959. else {
  13960. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  13961. }
  13962. // Vertex shader
  13963. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  13964. };
  13965. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  13966. // DOM element ?
  13967. if (fragment instanceof HTMLElement) {
  13968. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  13969. callback(fragmentCode);
  13970. return;
  13971. }
  13972. // Is in local store ?
  13973. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  13974. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  13975. return;
  13976. }
  13977. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  13978. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  13979. return;
  13980. }
  13981. var fragmentShaderUrl;
  13982. if (fragment[0] === ".") {
  13983. fragmentShaderUrl = fragment;
  13984. }
  13985. else {
  13986. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  13987. }
  13988. // Fragment shader
  13989. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  13990. };
  13991. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  13992. try {
  13993. var engine = this._engine;
  13994. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  13995. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  13996. this._attributes = engine.getAttributes(this._program, attributesNames);
  13997. for (var index = 0; index < this._samplers.length; index++) {
  13998. var sampler = this.getUniform(this._samplers[index]);
  13999. if (sampler == null) {
  14000. this._samplers.splice(index, 1);
  14001. index--;
  14002. }
  14003. }
  14004. engine.bindSamplers(this);
  14005. this._isReady = true;
  14006. if (this.onCompiled) {
  14007. this.onCompiled(this);
  14008. }
  14009. }
  14010. catch (e) {
  14011. // Is it a problem with precision?
  14012. if (e.message.indexOf("highp") !== -1) {
  14013. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  14014. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  14015. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14016. return;
  14017. }
  14018. // Let's go through fallbacks then
  14019. if (fallbacks && fallbacks.isMoreFallbacks) {
  14020. defines = fallbacks.reduce(defines);
  14021. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14022. }
  14023. else {
  14024. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  14025. BABYLON.Tools.Error("Defines: " + defines);
  14026. BABYLON.Tools.Error("Error: " + e.message);
  14027. this._compilationError = e.message;
  14028. if (this.onError) {
  14029. this.onError(this, this._compilationError);
  14030. }
  14031. }
  14032. }
  14033. };
  14034. Effect.prototype._bindTexture = function (channel, texture) {
  14035. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  14036. };
  14037. Effect.prototype.setTexture = function (channel, texture) {
  14038. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  14039. };
  14040. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14041. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  14042. };
  14043. //public _cacheMatrix(uniformName, matrix) {
  14044. // if (!this._valueCache[uniformName]) {
  14045. // this._valueCache[uniformName] = new BABYLON.Matrix();
  14046. // }
  14047. // for (var index = 0; index < 16; index++) {
  14048. // this._valueCache[uniformName].m[index] = matrix.m[index];
  14049. // }
  14050. //};
  14051. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  14052. if (!this._valueCache[uniformName]) {
  14053. this._valueCache[uniformName] = [x, y];
  14054. return;
  14055. }
  14056. this._valueCache[uniformName][0] = x;
  14057. this._valueCache[uniformName][1] = y;
  14058. };
  14059. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  14060. if (!this._valueCache[uniformName]) {
  14061. this._valueCache[uniformName] = [x, y, z];
  14062. return;
  14063. }
  14064. this._valueCache[uniformName][0] = x;
  14065. this._valueCache[uniformName][1] = y;
  14066. this._valueCache[uniformName][2] = z;
  14067. };
  14068. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  14069. if (!this._valueCache[uniformName]) {
  14070. this._valueCache[uniformName] = [x, y, z, w];
  14071. return;
  14072. }
  14073. this._valueCache[uniformName][0] = x;
  14074. this._valueCache[uniformName][1] = y;
  14075. this._valueCache[uniformName][2] = z;
  14076. this._valueCache[uniformName][3] = w;
  14077. };
  14078. Effect.prototype.setArray = function (uniformName, array) {
  14079. this._engine.setArray(this.getUniform(uniformName), array);
  14080. return this;
  14081. };
  14082. Effect.prototype.setArray2 = function (uniformName, array) {
  14083. this._engine.setArray2(this.getUniform(uniformName), array);
  14084. return this;
  14085. };
  14086. Effect.prototype.setArray3 = function (uniformName, array) {
  14087. this._engine.setArray3(this.getUniform(uniformName), array);
  14088. return this;
  14089. };
  14090. Effect.prototype.setArray4 = function (uniformName, array) {
  14091. this._engine.setArray4(this.getUniform(uniformName), array);
  14092. return this;
  14093. };
  14094. Effect.prototype.setMatrices = function (uniformName, matrices) {
  14095. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  14096. return this;
  14097. };
  14098. Effect.prototype.setMatrix = function (uniformName, matrix) {
  14099. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  14100. // return;
  14101. //this._cacheMatrix(uniformName, matrix);
  14102. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  14103. return this;
  14104. };
  14105. Effect.prototype.setFloat = function (uniformName, value) {
  14106. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  14107. return this;
  14108. this._valueCache[uniformName] = value;
  14109. this._engine.setFloat(this.getUniform(uniformName), value);
  14110. return this;
  14111. };
  14112. Effect.prototype.setBool = function (uniformName, bool) {
  14113. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  14114. return this;
  14115. this._valueCache[uniformName] = bool;
  14116. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  14117. return this;
  14118. };
  14119. Effect.prototype.setVector2 = function (uniformName, vector2) {
  14120. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  14121. return this;
  14122. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  14123. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  14124. return this;
  14125. };
  14126. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  14127. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  14128. return this;
  14129. this._cacheFloat2(uniformName, x, y);
  14130. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  14131. return this;
  14132. };
  14133. Effect.prototype.setVector3 = function (uniformName, vector3) {
  14134. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  14135. return this;
  14136. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  14137. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  14138. return this;
  14139. };
  14140. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  14141. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  14142. return this;
  14143. this._cacheFloat3(uniformName, x, y, z);
  14144. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  14145. return this;
  14146. };
  14147. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  14148. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  14149. return this;
  14150. this._cacheFloat4(uniformName, x, y, z, w);
  14151. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  14152. return this;
  14153. };
  14154. Effect.prototype.setColor3 = function (uniformName, color3) {
  14155. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  14156. return this;
  14157. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  14158. this._engine.setColor3(this.getUniform(uniformName), color3);
  14159. return this;
  14160. };
  14161. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  14162. 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)
  14163. return this;
  14164. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  14165. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  14166. return this;
  14167. };
  14168. // Statics
  14169. Effect.ShadersStore={anaglyphPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\n\nvoid main(void)\n{\n vec4 leftFrag = texture2D(leftSampler, vUV);\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\n\n vec4 rightFrag = texture2D(textureSampler, vUV);\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\n\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\n}",
  14170. blackAndWhitePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void) \n{\n float luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\n gl_FragColor = vec4(luminance, luminance, luminance, 1.0);\n}",
  14171. blurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Parameters\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nvoid main(void)\n{\n float weights[7];\n weights[0] = 0.05;\n weights[1] = 0.1;\n weights[2] = 0.2;\n weights[3] = 0.3;\n weights[4] = 0.2;\n weights[5] = 0.1;\n weights[6] = 0.05;\n\n vec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\n vec2 texelStep = texelSize * direction * blurWidth;\n vec2 start = vUV - 3.0 * texelStep;\n\n vec4 baseColor = vec4(0., 0., 0., 0.);\n vec2 texelOffset = vec2(0., 0.);\n\n for (int i = 0; i < 7; i++)\n {\n baseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\n texelOffset += texelStep;\n }\n\n gl_FragColor = baseColor;\n}",
  14172. brickPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfBricksHeight;\nuniform float numberOfBricksWidth;\nuniform vec3 brickColor;\nuniform vec3 jointColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\nvoid main(void)\n{\n float brickW = 1.0 / numberOfBricksWidth;\n float brickH = 1.0 / numberOfBricksHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.05;\n vec3 color = brickColor;\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n }\n else if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\n color = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n }\n else {\n float brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\n\n if (brickColorSwitch == 0.0)\n color = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\n else if (brickColorSwitch == 2.0)\n color = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\n }\n\n gl_FragColor = vec4(color, 1.0);\n}",
  14173. chromaticAberrationPixelShader:"/*\n BABYLON.JS Chromatic Aberration GLSL Shader\n Author: Olivier Guyot\n Separates very slightly R, G and B colors on the edges of the screen\n Inspired by Francois Tarlier & Martins Upitis \n*/\n\n#ifdef GL_ES\nprecision highp float;\n#endif\n\n// samplers\nuniform sampler2D textureSampler; // original color\n\n// uniforms\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\n// varyings\nvarying vec2 vUV;\n\nvoid main(void)\n{\n vec2 centered_screen_pos = vec2(vUV.x-0.5, vUV.y-0.5);\n float radius2 = centered_screen_pos.x*centered_screen_pos.x\n + centered_screen_pos.y*centered_screen_pos.y;\n float radius = sqrt(radius2);\n\n vec4 original = texture2D(textureSampler, vUV);\n\n if(chromatic_aberration > 0.0) {\n //index of refraction of each color channel, causing chromatic dispersion\n vec3 ref_indices = vec3(0.6, 0.3, 0.0);\n float ref_shiftX = chromatic_aberration * radius * 12.0 / screen_width;\n float ref_shiftY = chromatic_aberration * radius * 12.0 / screen_height;\n\n // shifts for red, green & blue\n vec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\n vec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\n vec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\n\n original.r = texture2D(textureSampler, ref_coords_r).r;\n original.g = texture2D(textureSampler, ref_coords_g).g;\n original.b = texture2D(textureSampler, ref_coords_b).b;\n }\n\n gl_FragColor = original;\n}",
  14174. cloudPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\n\nuniform vec3 skyColor;\nuniform vec3 cloudColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main() {\n\n vec2 p = vUV * 12.0;\n vec3 c = mix(skyColor, cloudColor, fbm(p));\n gl_FragColor = vec4(c, 1);\n\n}",
  14175. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  14176. colorVertexShader:"precision highp float;\n\n// Attributes\nattribute vec3 position;\n\n// Uniforms\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n}",
  14177. colorCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// samplers\nuniform sampler2D textureSampler; // screen render\nuniform sampler2D colorTable; // color table with modified colors\n\n// varyings\nvarying vec2 vUV;\n\n// constants\nconst float SLICE_COUNT = 16.0; // how many slices in the color cube; 1 slice = 1 pixel\n// it means the image is 256x16 pixels\n\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\n float sliceSize = 1.0 / width; // space of 1 slice\n float slicePixelSize = sliceSize / width; // space of 1 pixel\n float sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\n float zSlice0 = min(floor(uv.z * width), width - 1.0);\n float zSlice1 = min(zSlice0 + 1.0, width - 1.0);\n float xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\n float s0 = xOffset + (zSlice0 * sliceSize);\n float s1 = xOffset + (zSlice1 * sliceSize);\n vec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\n vec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\n float zOffset = mod(uv.z * width, 1.0);\n vec4 result = mix(slice0Color, slice1Color, zOffset);\n return result;\n}\n\nvoid main(void)\n{\n vec4 screen_color = texture2D(textureSampler, vUV);\n gl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\n\n}",
  14178. convolutionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform float kernel[9];\n\nvoid main(void)\n{\n vec2 onePixel = vec2(1.0, 1.0) / screenSize;\n vec4 colorSum =\n texture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\n texture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\n texture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\n\n float kernelWeight =\n kernel[0] +\n kernel[1] +\n kernel[2] +\n kernel[3] +\n kernel[4] +\n kernel[5] +\n kernel[6] +\n kernel[7] +\n kernel[8];\n\n if (kernelWeight <= 0.0) {\n kernelWeight = 1.0;\n }\n\n gl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\n}",
  14179. defaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\n\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform vec3 shadowsInfo0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform vec3 shadowsInfo1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform vec3 shadowsInfo2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform vec3 shadowsInfo3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\n return dot(color, bit_shift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv)) + bias;\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) + bias < depth.z) visibility -= 0.25;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t, float bias)\n{\n if (t - bias <= moments.x)\n {\n return 0.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.002);\n\n float d = t - moments.x;\n\n return clamp(variance / (variance + d * d) - 0.05, 0.0, 1.0);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return 1.0 - ChebychevInequality(moments, depth.z, bias);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n#ifdef NORMAL\n vec3 normalW = normalize(vNormalW);\n#else\n vec3 normalW = vec3(1.0, 1.0, 1.0);\n#endif\n\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  14180. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n// Output\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef REFLECTION\n vPositionUVW = position;\n#endif \n\n#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#else\n finalWorld = finalWorld * (m0 + m1 + m2);\n#endif \n\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n\n#ifdef NORMAL\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n#endif\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n\n // Point size\n#ifdef POINTSIZE\n gl_PointSize = pointSize;\n#endif\n}",
  14181. depthPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nuniform float far;\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n float depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\n gl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\n}",
  14182. depthVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  14183. depthBoxBlurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Parameters\nuniform vec2 screenSize;\n\nvoid main(void)\n{\n vec4 colorDepth = vec4(0.0);\n\n for (int x = -OFFSET; x <= OFFSET; x++)\n for (int y = -OFFSET; y <= OFFSET; y++)\n colorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\n\n gl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\n}",
  14184. depthOfFieldPixelShader:"/*\n BABYLON.JS Depth-of-field GLSL Shader\n Author: Olivier Guyot\n Does depth-of-field blur, edge blur, highlights enhancing\n Inspired by Francois Tarlier & Martins Upitis\n*/\n\n#ifdef GL_ES\nprecision highp float;\n#endif\n\n\n// samplers\nuniform sampler2D textureSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\n// uniforms\nuniform float grain_amount;\nuniform bool pentagon;\nuniform float maxZ;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform float focus_depth;\nuniform float aperture;\nuniform float gain;\nuniform float threshold;\nuniform float edge_blur;\n\n// varyings\nvarying vec2 vUV;\n\n// constants\n#define PI 3.14159265\nconst int RING_1_SAMPLES = 4;\nconst int RING_2_SAMPLES = 6;\nconst int RING_3_SAMPLES = 9;\nconst int RING_4_SAMPLES = 12;\nconst int RING_5_SAMPLES = 16;\n//const int RING_6_SAMPLES = 15;\nconst float RING_STEP_DIST = 0.4; // a new blur ring is added each time this distance is passed\nconst float PENTAGON_ANGLE_SUB = 1.2566; // 2PI / 5\nconst float PENTAGON_ANGLE_SUB_HALF = 0.6283; // 2PI / 10\n\n// common calculations\nvec2 centered_screen_pos;\nfloat radius2;\nfloat radius;\n\n\n// applies edge distortion on texture coords\nvec2 getDistortedCoords(vec2 coords) {\n\n if(distortion == 0.0) { return coords; }\n\n vec2 direction = 1.0 * normalize(centered_screen_pos);\n vec2 dist_coords = vec2(0.5, 0.5);\n dist_coords.x = 0.5 + direction.x * radius2 * 1.0;\n dist_coords.y = 0.5 + direction.y * radius2 * 1.0;\n float dist_amount = clamp(distortion*0.23, 0.0, 1.0);\n\n dist_coords = mix(coords, dist_coords, dist_amount);\n\n return dist_coords;\n}\n\n// picks either original screen color or highlights only\nvec4 getColor(vec2 coords, bool highlight) {\n\n vec4 color = texture2D(textureSampler, coords);\n\n if(highlight) {\n float luminance = dot(color.rgb, vec3(0.2125, 0.7154, 0.0721));\n float lum_threshold;\n if(threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\n else { lum_threshold = 0.5 + 0.44 * threshold; }\n if(luminance < lum_threshold) {\n color.rgb = vec3(0.0, 0.0, 0.0);\n color.a = 1.0;\n }\n }\n\n return color;\n}\n\n// returns a modifier to be applied on the radius, in order to simulate a pentagon\nfloat pentagonShape(float angle) {\n float a1 = mod(angle, PENTAGON_ANGLE_SUB) / PENTAGON_ANGLE_SUB - 0.5;\n float a2 = 0.5 - a1 * a1;\n return 1.35 - 0.94 * a2;\n}\n\n// returns original screen color after blur\nvec4 getBlurColor(vec2 coords, float size, bool highlight) {\n\n float w = (size/screen_width);\n float h = (size/screen_height);\n\n vec4 col = getColor(coords, highlight);\n if(size == 0.0) { return col; }\n\n float s = 1.0;\n float pw; // sample x relative coord\n float ph; // sample y relative coord\n float bias = 0.65; // inner/outer ring bias\n if(highlight) { bias = 0.95; }\n float sample_angle;\n float ratio_rings;\n float ring_radius;\n float penta; // pentagon shape modifier\n\n int ring_count;\n if(size >= 6.0 * RING_STEP_DIST) { ring_count = 6; }\n else if(size >= 5.0 * RING_STEP_DIST) { ring_count = 5; }\n else if(size >= 4.0 * RING_STEP_DIST) { ring_count = 4; }\n else if(size >= 3.0 * RING_STEP_DIST) { ring_count = 3; }\n else if(size >= 2.0 * RING_STEP_DIST) { ring_count = 2; }\n else { ring_count = 1; }\n \n // RING 1\n if(size > RING_STEP_DIST) {\n ring_radius = size / float(ring_count);\n ratio_rings = 1.0 / float(ring_count);\n for(int i = 0; i < RING_1_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_1_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias);\n }\n } \n\n // RING 2\n if(size > RING_STEP_DIST * 2.0) {\n ring_radius = 2.0 * size / float(ring_count);\n ratio_rings = 2.0 / float(ring_count);\n for(int i = 0; i < RING_2_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_2_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias); \n }\n } \n\n // RING 3\n if(size > RING_STEP_DIST * 3.0) {\n ring_radius = 3.0 * size / float(ring_count);\n ratio_rings = 3.0 / float(ring_count);\n for(int i = 0; i < RING_3_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_3_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias); \n }\n } \n\n // RING 4\n if(size > RING_STEP_DIST * 4.0) {\n ring_radius = 4.0 * size / float(ring_count);\n ratio_rings = 4.0 / float(ring_count);\n for(int i = 0; i < RING_4_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_4_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias); \n }\n } \n\n // RING 5\n if(size > RING_STEP_DIST * 5.0) {\n ring_radius = 5.0 * size / float(ring_count);\n ratio_rings = 5.0 / float(ring_count);\n for(int i = 0; i < RING_5_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_5_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias); \n }\n } \n\n col /= s; // scales color according to samples taken\n col.a = 1.0;\n\n return col;\n}\n\n// on-the-fly constant noise\nvec2 rand(vec2 co)\n{\n float noise1 = (fract(sin(dot(co ,vec2(12.9898,78.233))) * 43758.5453));\n float noise2 = (fract(sin(dot(co ,vec2(12.9898,78.233)*2.0)) * 43758.5453));\n return clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvoid main(void)\n{\n\n // Common calc\n centered_screen_pos = vec2(vUV.x-0.5, vUV.y-0.5);\n radius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\n radius = sqrt(radius2);\n\n vec4 final_color;\n vec2 distorted_coords = getDistortedCoords(vUV);\n vec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height); // varies from 0 to SCREEN_WIDTH or _HEIGHT\n\n // blur from depth of field effect\n float dof_blur_amount = 0.0;\n if(focus_depth != -1.0) {\n vec4 depth_sample = texture2D(depthSampler, distorted_coords);\n float depth = depth_sample.r;\n dof_blur_amount = abs(depth - focus_depth) * aperture * 3.5;\n if(dof_blur_amount < 0.05) { dof_blur_amount = 0.0; } // no blur at all\n else if( depth - focus_depth < 0.0 ) { dof_blur_amount *= 2.0; } // blur more when close to camera\n dof_blur_amount = clamp(dof_blur_amount, 0.0, 1.0);\n }\n\n // blur from edge blur effect\n float edge_blur_amount = 0.0;\n if(edge_blur > 0.0) {\n edge_blur_amount = clamp( ( radius*2.0 - 1.0 + 0.15*edge_blur ) * 1.5 , 0.0 , 1.0 ) * 1.3;\n }\n\n // total blur amount\n float blur_amount = max(edge_blur_amount, dof_blur_amount);\n\n // apply blur if necessary\n if(blur_amount == 0.0) {\n gl_FragColor = getColor(distorted_coords, false);\n } else {\n gl_FragColor = getBlurColor(distorted_coords, blur_amount * 1.7, false)\n + gain * blur_amount*getBlurColor(distorted_coords, blur_amount * 2.75, true);\n\n if(blur_noise) {\n // we put a slight amount of noise in the blurred color\n vec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\n vec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\n gl_FragColor = 0.04 * getColor(blurred_coord, false) + 0.96 * gl_FragColor;\n }\n }\n\n if(grain_amount > 0.0) {\n vec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\n gl_FragColor.rgb += ( -0.5 + grain_color.rgb ) * 0.20;\n }\n}",
  14185. displayPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(passSampler, vUV);\n}",
  14186. filterPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform mat4 kernelMatrix;\n\nvoid main(void)\n{\n vec3 baseColor = texture2D(textureSampler, vUV).rgb;\n vec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\n\n gl_FragColor = vec4(updatedColor, 1.0);\n}",
  14187. firePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform float time;\nuniform vec3 c1;\nuniform vec3 c2;\nuniform vec3 c3;\nuniform vec3 c4;\nuniform vec3 c5;\nuniform vec3 c6;\nuniform vec2 speed;\nuniform float shift;\nuniform float alphaThreshold;\n\nvarying vec2 vUV;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main() {\n vec2 p = vUV * 8.0;\n float q = fbm(p - time * 0.1);\n vec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\n vec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\n vec3 color = c * cos(shift * vUV.y);\n float luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\n\n gl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\n}",
  14188. fxaaPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\n\nvoid main(){\n vec2 localTexelSize = texelSize;\n vec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\n vec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\n vec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\n vec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\n vec4 rgbM = texture2D(textureSampler, vUV);\n vec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n vec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\n\n float dirReduce = max(\n (lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\n FXAA_REDUCE_MIN);\n\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * localTexelSize;\n\n vec4 rgbA = 0.5 * (\n texture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\n texture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\n\n vec4 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(textureSampler, vUV + dir * -0.5) +\n texture2D(textureSampler, vUV + dir * 0.5));\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax)) {\n gl_FragColor = rgbA;\n }\n else {\n gl_FragColor = rgbB;\n }\n}",
  14189. grassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform vec3 herb1Color;\nuniform vec3 herb2Color;\nuniform vec3 herb3Color;\nuniform vec3 groundColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n vec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\n color = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\n color = mix(color, herb3Color, rand(gl_FragCoord.xy));\n color = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\n gl_FragColor = vec4(color, 1.0);\n}",
  14190. layerPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Color\nuniform vec4 color;\n\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n\n gl_FragColor = baseColor * color;\n}",
  14191. layerVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Uniforms\nuniform mat4 textureMatrix;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  14192. legacydefaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_PROJECTION 4.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return 0.;\n }\n return 1.;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW;\n if (lightData.w == 0.)\n {\n lightVectorW = normalize(lightData.xyz - vPositionW);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\n result[0] = ndl * diffuseColor.rgb;\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = ndl * spotAtten * diffuseColor.rgb;\n result[1] = specComp * specularColor * spotAtten;\n result[2] = vec3(0.);\n\n return result;\n }\n\n result[0] = vec3(0.);\n result[1] = vec3(0.);\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\n mat3 result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = mix(groundColor, diffuseColor.rgb, ndl);\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n mat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\n mat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n mat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  14193. legacydefaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return position;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n finalWorld = world;\n#endif\n\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef REFLECTION\n vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}",
  14194. lensFlarePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Color\nuniform vec4 color;\n\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n\n gl_FragColor = baseColor * color;\n}",
  14195. lensFlareVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Uniforms\nuniform mat4 viewportMatrix;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = position * madd + madd;\n gl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\n}",
  14196. marblePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfTilesHeight;\nuniform float numberOfTilesWidth;\nuniform float amplitude;\nuniform vec3 brickColor;\nuniform vec3 jointColor;\n\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat turbulence(vec2 P)\n{\n float val = 0.0;\n float freq = 1.0;\n for (int i = 0; i < 4; i++)\n {\n val += abs(noise(P*freq) / freq);\n freq *= 2.07;\n }\n return val;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\nvec3 marble_color(float x)\n{\n vec3 col;\n x = 0.5*(x + 1.);\n x = sqrt(x); \n x = sqrt(x);\n x = sqrt(x);\n col = vec3(.2 + .75*x); \n col.b *= 0.95; \n return col;\n}\n\nvoid main()\n{\n float brickW = 1.0 / numberOfTilesWidth;\n float brickH = 1.0 / numberOfTilesHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.01;\n vec3 color = brickColor;\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n }\n else if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\n color = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n }\n else {\n float t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\n t += amplitude * turbulence(brickvUV.xy);\n t = sin(t);\n color = marble_color(t);\n }\n\n gl_FragColor = vec4(color, 0.0);\n}",
  14197. oculusDistortionCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\n\nvec2 HmdWarp(vec2 in01) {\n\n vec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\n float rSq = theta.x * theta.x + theta.y * theta.y;\n vec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\n return LensCenter + Scale * rvector;\n}\n\nvoid main(void)\n{\n vec2 tc = HmdWarp(vUV);\n if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n else{\n gl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\n }\n}",
  14198. outlinePixelShader:"precision highp float;\n\nuniform vec4 color;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void) {\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n gl_FragColor = color;\n}",
  14199. outlineVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\nattribute vec3 normal;\n\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\nuniform float offset;\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n vec3 offsetPosition = position + normal * offset;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#else\n gl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  14200. particlesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\nvoid main(void) {\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n vec4 baseColor = texture2D(diffuseSampler, vUV);\n\n gl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\n}",
  14201. particlesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\n// Uniforms\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n\nvoid main(void) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n float size = options.y;\n float angle = options.x;\n vec2 offset = options.zw;\n\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n \n vColor = color;\n vUV = offset;\n\n // Clip plane\n#ifdef CLIPPLANE\n vec4 worldPos = invView * vec4(viewPos, 1.0);\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n}",
  14202. passPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void) \n{\n gl_FragColor = texture2D(textureSampler, vUV);\n}",
  14203. postprocessVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = position * madd + madd;\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  14204. proceduralVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Output\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n vPosition = position;\n vUV = position * madd + madd;\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  14205. refractionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\n// Parameters\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\n\nvoid main() {\n float ref = 1.0 - texture2D(refractionSampler, vUV).r;\n\n vec2 uv = vUV - vec2(0.5);\n vec2 offset = uv * depth * ref;\n vec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\n\n gl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\n}",
  14206. roadPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV; \nuniform vec3 roadColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n float ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\n vec3 color = roadColor * ratioy;\n gl_FragColor = vec4(color, 1.0);\n}",
  14207. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\n const vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\n const vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\n\n vec4 res = fract(depth * bit_shift);\n res -= res.xxyz * bit_mask;\n\n return res;\n}\n\n// Thanks to http://devmaster.net/\nvec2 packHalf(float depth) \n{ \n const vec2 bitOffset = vec2(1.0 / 255., 0.);\n vec2 color = vec2(depth, fract(depth * 255.));\n\n return color - (color.yy * bitOffset);\n}\n\nvarying vec4 vPosition;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n float depth = vPosition.z / vPosition.w;\n depth = depth * 0.5 + 0.5;\n\n#ifdef VSM\n float moment1 = depth;\n float moment2 = moment1 * moment1;\n\n gl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\n gl_FragColor = pack(depth);\n#endif\n}",
  14208. shadowMapVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\nvarying vec4 vPosition;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#endif\n\n vPosition = viewProjection * finalWorld * vec4(position, 1.0);\n gl_Position = vPosition;\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  14209. spritesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform bool alphaTest;\n\nvarying vec4 vColor;\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return min(1., max(0., fogCoeff));\n}\n#endif\n\n\nvoid main(void) {\n vec4 baseColor = texture2D(diffuseSampler, vUV);\n\n if (alphaTest) \n {\n if (baseColor.a < 0.95)\n discard;\n }\n\n baseColor *= vColor;\n\n#ifdef FOG\n float fog = CalcFogFactor();\n baseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = baseColor;\n}",
  14210. spritesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\n// Uniforms\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\nvoid main(void) { \n vec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \n vec2 cornerPos;\n \n float angle = position.w;\n vec2 size = vec2(options.x, options.y);\n vec2 offset = options.zw;\n vec2 uvScale = textureInfos.xy;\n\n cornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n\n // Color\n vColor = color;\n \n // Texture\n vec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\n\n vUV = (uvOffset + cellInfo.zw) * uvScale;\n\n // Fog\n#ifdef FOG\n fFogDistance = viewPos.z;\n#endif\n}",
  14211. ssaoPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define SAMPLES 16\n\nuniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\n\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[16];\n\nvarying vec2 vUV;\n\nconst vec2 offset1 = vec2(0.0, 0.01);\nconst vec2 offset2 = vec2(0.01, 0.0);\n\nvec3 normalFromDepth(const float depth, const vec2 coords) {\n float depth1 = texture2D(textureSampler, coords + offset1).r;\n float depth2 = texture2D(textureSampler, coords + offset2).r;\n\n vec3 p1 = vec3(offset1, depth1 - depth);\n vec3 p2 = vec3(offset2, depth2 - depth);\n\n vec3 normal = cross(p1, p2);\n normal.z = -normal.z;\n\n return normalize(normal);\n}\n\nvoid main(void)\n{\n const float totalStrength = 1.0;\n const float base = 0.2;\n const float area = 0.0075;\n const float fallOff = 0.000001;\n const float radius = 0.0005;\n\n vec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\n float depth = texture2D(textureSampler, vUV).r;\n vec3 position = vec3(vUV, depth);\n vec3 normal = normalFromDepth(depth, vUV);\n float radiusDepth = radius / depth;\n float occlusion = 0.0;\n\n vec3 ray;\n vec3 hemiRay;\n float occlusionDepth;\n float difference;\n\n for (int i = 0; i < SAMPLES; i++)\n {\n ray = radiusDepth * reflect(sampleSphere[i], random);\n hemiRay = position + dot(ray, normal) * ray;\n\n occlusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\n difference = depth - occlusionDepth;\n\n occlusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\n }\n\n float ao = 1.0 - totalStrength * occlusion * samplesFactor;\n\n float result = clamp(ao + base, 0.0, 1.0);\n gl_FragColor.r = result;\n gl_FragColor.g = result;\n gl_FragColor.b = result;\n gl_FragColor.a = 1.0;\n}",
  14212. ssaoCombinePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D originalColor;\n\nvarying vec2 vUV;\n\nvoid main(void) {\n gl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\n}",
  14213. volumetricLightScatteringPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\n\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\n\nvarying vec2 vUV;\n\nvoid main(void) {\n vec2 tc = vUV;\n vec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\n\n float illuminationDecay = 1.0;\n\n vec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\n\n for(int i=0; i < NUM_SAMPLES; i++) {\n tc -= deltaTexCoord;\n vec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\n sample *= illuminationDecay * weight;\n color += sample;\n illuminationDecay *= decay;\n }\n\n vec4 realColor = texture2D(textureSampler, vUV);\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\n}",
  14214. volumetricLightScatteringPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER) || defined(OPACITY)\nvarying vec2 vUV;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nuniform sampler2D diffuseSampler;\n#endif\n\n#if defined(OPACITY)\nuniform sampler2D opacitySampler;\nuniform float opacityLevel;\n#endif\n\nvoid main(void)\n{\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n vec4 diffuseColor = texture2D(diffuseSampler, vUV);\n#endif\n\n#ifdef ALPHATEST\n if (diffuseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef OPACITY\n vec4 opacityColor = texture2D(opacitySampler, vUV);\n float alpha = 1.0;\n\n #ifdef OPACITYRGB\n opacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\n #else\n alpha *= opacityColor.a * opacityLevel;\n #endif\n\n #if defined(BASIC_RENDER)\n gl_FragColor = vec4(diffuseColor.rgb, alpha);\n #else\n gl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\n #endif\n\n gl_FragColor.a = alpha;\n#else\n #ifndef BASIC_RENDER\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n #else\n gl_FragColor = diffuseColor;\n #endif\n#endif\n\n}",
  14215. woodPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float ampScale;\nuniform vec3 woodColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n float ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\n vec3 wood = woodColor * ratioy;\n gl_FragColor = vec4(wood, 1.0);\n}",
  14216. };
  14217. return Effect;
  14218. })();
  14219. BABYLON.Effect = Effect;
  14220. })(BABYLON || (BABYLON = {}));
  14221. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  14222. (function (BABYLON) {
  14223. var Material = (function () {
  14224. function Material(name, scene, doNotAdd) {
  14225. this.name = name;
  14226. this.checkReadyOnEveryCall = true;
  14227. this.checkReadyOnlyOnce = false;
  14228. this.state = "";
  14229. this.alpha = 1.0;
  14230. this.backFaceCulling = true;
  14231. this._wasPreviouslyReady = false;
  14232. this._fillMode = Material.TriangleFillMode;
  14233. this.pointSize = 1.0;
  14234. this.id = name;
  14235. this._scene = scene;
  14236. if (!doNotAdd) {
  14237. scene.materials.push(this);
  14238. }
  14239. }
  14240. Object.defineProperty(Material, "TriangleFillMode", {
  14241. get: function () {
  14242. return Material._TriangleFillMode;
  14243. },
  14244. enumerable: true,
  14245. configurable: true
  14246. });
  14247. Object.defineProperty(Material, "WireFrameFillMode", {
  14248. get: function () {
  14249. return Material._WireFrameFillMode;
  14250. },
  14251. enumerable: true,
  14252. configurable: true
  14253. });
  14254. Object.defineProperty(Material, "PointFillMode", {
  14255. get: function () {
  14256. return Material._PointFillMode;
  14257. },
  14258. enumerable: true,
  14259. configurable: true
  14260. });
  14261. Object.defineProperty(Material.prototype, "wireframe", {
  14262. get: function () {
  14263. return this._fillMode === Material.WireFrameFillMode;
  14264. },
  14265. set: function (value) {
  14266. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  14267. },
  14268. enumerable: true,
  14269. configurable: true
  14270. });
  14271. Object.defineProperty(Material.prototype, "pointsCloud", {
  14272. get: function () {
  14273. return this._fillMode === Material.PointFillMode;
  14274. },
  14275. set: function (value) {
  14276. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  14277. },
  14278. enumerable: true,
  14279. configurable: true
  14280. });
  14281. Object.defineProperty(Material.prototype, "fillMode", {
  14282. get: function () {
  14283. return this._fillMode;
  14284. },
  14285. set: function (value) {
  14286. this._fillMode = value;
  14287. },
  14288. enumerable: true,
  14289. configurable: true
  14290. });
  14291. Material.prototype.isReady = function (mesh, useInstances) {
  14292. return true;
  14293. };
  14294. Material.prototype.getEffect = function () {
  14295. return this._effect;
  14296. };
  14297. Material.prototype.getScene = function () {
  14298. return this._scene;
  14299. };
  14300. Material.prototype.needAlphaBlending = function () {
  14301. return (this.alpha < 1.0);
  14302. };
  14303. Material.prototype.needAlphaTesting = function () {
  14304. return false;
  14305. };
  14306. Material.prototype.getAlphaTestTexture = function () {
  14307. return null;
  14308. };
  14309. Material.prototype.trackCreation = function (onCompiled, onError) {
  14310. };
  14311. Material.prototype._preBind = function () {
  14312. var engine = this._scene.getEngine();
  14313. engine.enableEffect(this._effect);
  14314. engine.setState(this.backFaceCulling);
  14315. };
  14316. Material.prototype.bind = function (world, mesh) {
  14317. this._scene._cachedMaterial = this;
  14318. if (this.onBind) {
  14319. this.onBind(this);
  14320. }
  14321. };
  14322. Material.prototype.bindOnlyWorldMatrix = function (world) {
  14323. };
  14324. Material.prototype.unbind = function () {
  14325. };
  14326. Material.prototype.dispose = function (forceDisposeEffect) {
  14327. // Remove from scene
  14328. var index = this._scene.materials.indexOf(this);
  14329. this._scene.materials.splice(index, 1);
  14330. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  14331. if (forceDisposeEffect && this._effect) {
  14332. this._scene.getEngine()._releaseEffect(this._effect);
  14333. this._effect = null;
  14334. }
  14335. // Callback
  14336. if (this.onDispose) {
  14337. this.onDispose();
  14338. }
  14339. };
  14340. Material._TriangleFillMode = 0;
  14341. Material._WireFrameFillMode = 1;
  14342. Material._PointFillMode = 2;
  14343. return Material;
  14344. })();
  14345. BABYLON.Material = Material;
  14346. })(BABYLON || (BABYLON = {}));
  14347. //# sourceMappingURL=babylon.material.js.map
  14348. var BABYLON;
  14349. (function (BABYLON) {
  14350. var maxSimultaneousLights = 4;
  14351. var FresnelParameters = (function () {
  14352. function FresnelParameters() {
  14353. this.isEnabled = true;
  14354. this.leftColor = BABYLON.Color3.White();
  14355. this.rightColor = BABYLON.Color3.Black();
  14356. this.bias = 0;
  14357. this.power = 1;
  14358. }
  14359. return FresnelParameters;
  14360. })();
  14361. BABYLON.FresnelParameters = FresnelParameters;
  14362. var StandardMaterial = (function (_super) {
  14363. __extends(StandardMaterial, _super);
  14364. function StandardMaterial(name, scene) {
  14365. var _this = this;
  14366. _super.call(this, name, scene);
  14367. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14368. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  14369. this.specularColor = new BABYLON.Color3(1, 1, 1);
  14370. this.specularPower = 64;
  14371. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  14372. this.useAlphaFromDiffuseTexture = false;
  14373. this.useSpecularOverAlpha = true;
  14374. this.fogEnabled = true;
  14375. this._cachedDefines = null;
  14376. this._renderTargets = new BABYLON.SmartArray(16);
  14377. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  14378. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  14379. this._scaledDiffuse = new BABYLON.Color3();
  14380. this._scaledSpecular = new BABYLON.Color3();
  14381. this.getRenderTargetTextures = function () {
  14382. _this._renderTargets.reset();
  14383. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  14384. _this._renderTargets.push(_this.reflectionTexture);
  14385. }
  14386. return _this._renderTargets;
  14387. };
  14388. }
  14389. StandardMaterial.prototype.needAlphaBlending = function () {
  14390. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  14391. };
  14392. StandardMaterial.prototype.needAlphaTesting = function () {
  14393. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  14394. };
  14395. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  14396. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  14397. };
  14398. StandardMaterial.prototype.getAlphaTestTexture = function () {
  14399. return this.diffuseTexture;
  14400. };
  14401. // Methods
  14402. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  14403. if (this.checkReadyOnlyOnce) {
  14404. if (this._wasPreviouslyReady) {
  14405. }
  14406. }
  14407. var scene = this.getScene();
  14408. if (!this.checkReadyOnEveryCall) {
  14409. if (this._renderId === scene.getRenderId()) {
  14410. }
  14411. }
  14412. var engine = scene.getEngine();
  14413. var defines = [];
  14414. var fallbacks = new BABYLON.EffectFallbacks();
  14415. var needNormals = false;
  14416. var needUVs = false;
  14417. // Textures
  14418. if (scene.texturesEnabled) {
  14419. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14420. if (!this.diffuseTexture.isReady()) {
  14421. return false;
  14422. }
  14423. else {
  14424. needUVs = true;
  14425. defines.push("#define DIFFUSE");
  14426. }
  14427. }
  14428. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14429. if (!this.ambientTexture.isReady()) {
  14430. return false;
  14431. }
  14432. else {
  14433. needUVs = true;
  14434. defines.push("#define AMBIENT");
  14435. }
  14436. }
  14437. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14438. if (!this.opacityTexture.isReady()) {
  14439. return false;
  14440. }
  14441. else {
  14442. needUVs = true;
  14443. defines.push("#define OPACITY");
  14444. if (this.opacityTexture.getAlphaFromRGB) {
  14445. defines.push("#define OPACITYRGB");
  14446. }
  14447. }
  14448. }
  14449. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14450. if (!this.reflectionTexture.isReady()) {
  14451. return false;
  14452. }
  14453. else {
  14454. needNormals = true;
  14455. needUVs = true;
  14456. defines.push("#define REFLECTION");
  14457. fallbacks.addFallback(0, "REFLECTION");
  14458. }
  14459. }
  14460. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14461. if (!this.emissiveTexture.isReady()) {
  14462. return false;
  14463. }
  14464. else {
  14465. needUVs = true;
  14466. defines.push("#define EMISSIVE");
  14467. }
  14468. }
  14469. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14470. if (!this.specularTexture.isReady()) {
  14471. return false;
  14472. }
  14473. else {
  14474. needUVs = true;
  14475. defines.push("#define SPECULAR");
  14476. fallbacks.addFallback(0, "SPECULAR");
  14477. }
  14478. }
  14479. }
  14480. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  14481. if (!this.bumpTexture.isReady()) {
  14482. return false;
  14483. }
  14484. else {
  14485. needUVs = true;
  14486. defines.push("#define BUMP");
  14487. fallbacks.addFallback(0, "BUMP");
  14488. }
  14489. }
  14490. // Effect
  14491. if (this.useSpecularOverAlpha) {
  14492. defines.push("#define SPECULAROVERALPHA");
  14493. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  14494. }
  14495. if (scene.clipPlane) {
  14496. defines.push("#define CLIPPLANE");
  14497. }
  14498. if (engine.getAlphaTesting()) {
  14499. defines.push("#define ALPHATEST");
  14500. }
  14501. if (this._shouldUseAlphaFromDiffuseTexture()) {
  14502. defines.push("#define ALPHAFROMDIFFUSE");
  14503. }
  14504. // Point size
  14505. if (this.pointsCloud || scene.forcePointsCloud) {
  14506. defines.push("#define POINTSIZE");
  14507. }
  14508. // Fog
  14509. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14510. defines.push("#define FOG");
  14511. fallbacks.addFallback(1, "FOG");
  14512. }
  14513. var shadowsActivated = false;
  14514. var lightIndex = 0;
  14515. if (scene.lightsEnabled) {
  14516. for (var index = 0; index < scene.lights.length; index++) {
  14517. var light = scene.lights[index];
  14518. if (!light.isEnabled()) {
  14519. continue;
  14520. }
  14521. // Excluded check
  14522. if (light._excludedMeshesIds.length > 0) {
  14523. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  14524. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  14525. if (excludedMesh) {
  14526. light.excludedMeshes.push(excludedMesh);
  14527. }
  14528. }
  14529. light._excludedMeshesIds = [];
  14530. }
  14531. // Included check
  14532. if (light._includedOnlyMeshesIds.length > 0) {
  14533. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  14534. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  14535. if (includedOnlyMesh) {
  14536. light.includedOnlyMeshes.push(includedOnlyMesh);
  14537. }
  14538. }
  14539. light._includedOnlyMeshesIds = [];
  14540. }
  14541. if (!light.canAffectMesh(mesh)) {
  14542. continue;
  14543. }
  14544. needNormals = true;
  14545. defines.push("#define LIGHT" + lightIndex);
  14546. if (lightIndex > 0) {
  14547. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  14548. }
  14549. var type;
  14550. if (light instanceof BABYLON.SpotLight) {
  14551. type = "#define SPOTLIGHT" + lightIndex;
  14552. }
  14553. else if (light instanceof BABYLON.HemisphericLight) {
  14554. type = "#define HEMILIGHT" + lightIndex;
  14555. }
  14556. else {
  14557. type = "#define POINTDIRLIGHT" + lightIndex;
  14558. }
  14559. defines.push(type);
  14560. if (lightIndex > 0) {
  14561. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  14562. }
  14563. // Shadows
  14564. if (scene.shadowsEnabled) {
  14565. var shadowGenerator = light.getShadowGenerator();
  14566. if (mesh && mesh.receiveShadows && shadowGenerator) {
  14567. defines.push("#define SHADOW" + lightIndex);
  14568. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  14569. if (!shadowsActivated) {
  14570. defines.push("#define SHADOWS");
  14571. shadowsActivated = true;
  14572. }
  14573. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  14574. defines.push("#define SHADOWVSM" + lightIndex);
  14575. if (lightIndex > 0) {
  14576. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  14577. }
  14578. }
  14579. if (shadowGenerator.usePoissonSampling) {
  14580. defines.push("#define SHADOWPCF" + lightIndex);
  14581. if (lightIndex > 0) {
  14582. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  14583. }
  14584. }
  14585. }
  14586. }
  14587. lightIndex++;
  14588. if (lightIndex === maxSimultaneousLights)
  14589. break;
  14590. }
  14591. }
  14592. if (StandardMaterial.FresnelEnabled) {
  14593. // Fresnel
  14594. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14595. var fresnelRank = 1;
  14596. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14597. defines.push("#define DIFFUSEFRESNEL");
  14598. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  14599. fresnelRank++;
  14600. }
  14601. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14602. defines.push("#define OPACITYFRESNEL");
  14603. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  14604. fresnelRank++;
  14605. }
  14606. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14607. defines.push("#define REFLECTIONFRESNEL");
  14608. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  14609. fresnelRank++;
  14610. }
  14611. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14612. defines.push("#define EMISSIVEFRESNEL");
  14613. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  14614. fresnelRank++;
  14615. }
  14616. needNormals = true;
  14617. defines.push("#define FRESNEL");
  14618. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  14619. }
  14620. }
  14621. // Attribs
  14622. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14623. if (mesh) {
  14624. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14625. attribs.push(BABYLON.VertexBuffer.NormalKind);
  14626. defines.push("#define NORMAL");
  14627. }
  14628. if (needUVs) {
  14629. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14630. attribs.push(BABYLON.VertexBuffer.UVKind);
  14631. defines.push("#define UV1");
  14632. }
  14633. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14634. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14635. defines.push("#define UV2");
  14636. }
  14637. }
  14638. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14639. attribs.push(BABYLON.VertexBuffer.ColorKind);
  14640. defines.push("#define VERTEXCOLOR");
  14641. if (mesh.hasVertexAlpha) {
  14642. defines.push("#define VERTEXALPHA");
  14643. }
  14644. }
  14645. if (mesh.useBones) {
  14646. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14647. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14648. defines.push("#define BONES");
  14649. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14650. defines.push("#define BONES4");
  14651. fallbacks.addFallback(0, "BONES4");
  14652. }
  14653. // Instances
  14654. if (useInstances) {
  14655. defines.push("#define INSTANCES");
  14656. attribs.push("world0");
  14657. attribs.push("world1");
  14658. attribs.push("world2");
  14659. attribs.push("world3");
  14660. }
  14661. }
  14662. // Get correct effect
  14663. var join = defines.join("\n");
  14664. if (this._cachedDefines !== join) {
  14665. this._cachedDefines = join;
  14666. scene.resetCachedMaterial();
  14667. // Legacy browser patch
  14668. var shaderName = "default";
  14669. if (!scene.getEngine().getCaps().standardDerivatives) {
  14670. shaderName = "legacydefault";
  14671. }
  14672. 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);
  14673. }
  14674. if (!this._effect.isReady()) {
  14675. return false;
  14676. }
  14677. this._renderId = scene.getRenderId();
  14678. this._wasPreviouslyReady = true;
  14679. return true;
  14680. };
  14681. StandardMaterial.prototype.unbind = function () {
  14682. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  14683. this._effect.setTexture("reflection2DSampler", null);
  14684. }
  14685. };
  14686. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  14687. this._effect.setMatrix("world", world);
  14688. };
  14689. StandardMaterial.prototype.bind = function (world, mesh) {
  14690. var scene = this.getScene();
  14691. // Matrices
  14692. this.bindOnlyWorldMatrix(world);
  14693. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  14694. // Bones
  14695. if (mesh.useBones) {
  14696. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  14697. }
  14698. if (scene.getCachedMaterial() !== this) {
  14699. if (StandardMaterial.FresnelEnabled) {
  14700. // Fresnel
  14701. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14702. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  14703. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  14704. }
  14705. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14706. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  14707. }
  14708. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14709. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  14710. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  14711. }
  14712. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14713. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  14714. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  14715. }
  14716. }
  14717. // Textures
  14718. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14719. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  14720. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  14721. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  14722. }
  14723. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14724. this._effect.setTexture("ambientSampler", this.ambientTexture);
  14725. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  14726. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  14727. }
  14728. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14729. this._effect.setTexture("opacitySampler", this.opacityTexture);
  14730. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  14731. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  14732. }
  14733. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14734. if (this.reflectionTexture.isCube) {
  14735. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  14736. }
  14737. else {
  14738. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  14739. }
  14740. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  14741. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  14742. }
  14743. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14744. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  14745. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  14746. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  14747. }
  14748. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14749. this._effect.setTexture("specularSampler", this.specularTexture);
  14750. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  14751. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  14752. }
  14753. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  14754. this._effect.setTexture("bumpSampler", this.bumpTexture);
  14755. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  14756. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  14757. }
  14758. // Clip plane
  14759. if (scene.clipPlane) {
  14760. var clipPlane = scene.clipPlane;
  14761. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14762. }
  14763. // Point size
  14764. if (this.pointsCloud) {
  14765. this._effect.setFloat("pointSize", this.pointSize);
  14766. }
  14767. // Colors
  14768. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  14769. // Scaling down color according to emissive
  14770. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14771. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14772. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14773. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  14774. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  14775. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  14776. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  14777. }
  14778. // Scaling down color according to emissive
  14779. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14780. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14781. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14782. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  14783. if (scene.lightsEnabled) {
  14784. var lightIndex = 0;
  14785. for (var index = 0; index < scene.lights.length; index++) {
  14786. var light = scene.lights[index];
  14787. if (!light.isEnabled()) {
  14788. continue;
  14789. }
  14790. if (!light.canAffectMesh(mesh)) {
  14791. continue;
  14792. }
  14793. if (light instanceof BABYLON.PointLight) {
  14794. // Point Light
  14795. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14796. }
  14797. else if (light instanceof BABYLON.DirectionalLight) {
  14798. // Directional Light
  14799. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14800. }
  14801. else if (light instanceof BABYLON.SpotLight) {
  14802. // Spot Light
  14803. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  14804. }
  14805. else if (light instanceof BABYLON.HemisphericLight) {
  14806. // Hemispheric Light
  14807. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  14808. }
  14809. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  14810. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  14811. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  14812. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  14813. // Shadows
  14814. if (scene.shadowsEnabled) {
  14815. var shadowGenerator = light.getShadowGenerator();
  14816. if (mesh.receiveShadows && shadowGenerator) {
  14817. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  14818. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  14819. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  14820. }
  14821. }
  14822. lightIndex++;
  14823. if (lightIndex === maxSimultaneousLights)
  14824. break;
  14825. }
  14826. }
  14827. // View
  14828. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  14829. this._effect.setMatrix("view", scene.getViewMatrix());
  14830. }
  14831. // Fog
  14832. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  14833. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  14834. this._effect.setColor3("vFogColor", scene.fogColor);
  14835. }
  14836. _super.prototype.bind.call(this, world, mesh);
  14837. };
  14838. StandardMaterial.prototype.getAnimatables = function () {
  14839. var results = [];
  14840. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  14841. results.push(this.diffuseTexture);
  14842. }
  14843. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  14844. results.push(this.ambientTexture);
  14845. }
  14846. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  14847. results.push(this.opacityTexture);
  14848. }
  14849. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  14850. results.push(this.reflectionTexture);
  14851. }
  14852. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  14853. results.push(this.emissiveTexture);
  14854. }
  14855. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  14856. results.push(this.specularTexture);
  14857. }
  14858. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  14859. results.push(this.bumpTexture);
  14860. }
  14861. return results;
  14862. };
  14863. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  14864. if (this.diffuseTexture) {
  14865. this.diffuseTexture.dispose();
  14866. }
  14867. if (this.ambientTexture) {
  14868. this.ambientTexture.dispose();
  14869. }
  14870. if (this.opacityTexture) {
  14871. this.opacityTexture.dispose();
  14872. }
  14873. if (this.reflectionTexture) {
  14874. this.reflectionTexture.dispose();
  14875. }
  14876. if (this.emissiveTexture) {
  14877. this.emissiveTexture.dispose();
  14878. }
  14879. if (this.specularTexture) {
  14880. this.specularTexture.dispose();
  14881. }
  14882. if (this.bumpTexture) {
  14883. this.bumpTexture.dispose();
  14884. }
  14885. _super.prototype.dispose.call(this, forceDisposeEffect);
  14886. };
  14887. StandardMaterial.prototype.clone = function (name) {
  14888. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  14889. // Base material
  14890. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  14891. newStandardMaterial.alpha = this.alpha;
  14892. newStandardMaterial.fillMode = this.fillMode;
  14893. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  14894. // Standard material
  14895. if (this.diffuseTexture && this.diffuseTexture.clone) {
  14896. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  14897. }
  14898. if (this.ambientTexture && this.ambientTexture.clone) {
  14899. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  14900. }
  14901. if (this.opacityTexture && this.opacityTexture.clone) {
  14902. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  14903. }
  14904. if (this.reflectionTexture && this.reflectionTexture.clone) {
  14905. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  14906. }
  14907. if (this.emissiveTexture && this.emissiveTexture.clone) {
  14908. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  14909. }
  14910. if (this.specularTexture && this.specularTexture.clone) {
  14911. newStandardMaterial.specularTexture = this.specularTexture.clone();
  14912. }
  14913. if (this.bumpTexture && this.bumpTexture.clone) {
  14914. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  14915. }
  14916. newStandardMaterial.ambientColor = this.ambientColor.clone();
  14917. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  14918. newStandardMaterial.specularColor = this.specularColor.clone();
  14919. newStandardMaterial.specularPower = this.specularPower;
  14920. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  14921. return newStandardMaterial;
  14922. };
  14923. // Statics
  14924. // Flags used to enable or disable a type of texture for all Standard Materials
  14925. StandardMaterial.DiffuseTextureEnabled = true;
  14926. StandardMaterial.AmbientTextureEnabled = true;
  14927. StandardMaterial.OpacityTextureEnabled = true;
  14928. StandardMaterial.ReflectionTextureEnabled = true;
  14929. StandardMaterial.EmissiveTextureEnabled = true;
  14930. StandardMaterial.SpecularTextureEnabled = true;
  14931. StandardMaterial.BumpTextureEnabled = true;
  14932. StandardMaterial.FresnelEnabled = true;
  14933. return StandardMaterial;
  14934. })(BABYLON.Material);
  14935. BABYLON.StandardMaterial = StandardMaterial;
  14936. })(BABYLON || (BABYLON = {}));
  14937. //# sourceMappingURL=babylon.standardMaterial.js.map
  14938. var BABYLON;
  14939. (function (BABYLON) {
  14940. var MultiMaterial = (function (_super) {
  14941. __extends(MultiMaterial, _super);
  14942. function MultiMaterial(name, scene) {
  14943. _super.call(this, name, scene, true);
  14944. this.subMaterials = new Array();
  14945. scene.multiMaterials.push(this);
  14946. }
  14947. // Properties
  14948. MultiMaterial.prototype.getSubMaterial = function (index) {
  14949. if (index < 0 || index >= this.subMaterials.length) {
  14950. return this.getScene().defaultMaterial;
  14951. }
  14952. return this.subMaterials[index];
  14953. };
  14954. // Methods
  14955. MultiMaterial.prototype.isReady = function (mesh) {
  14956. for (var index = 0; index < this.subMaterials.length; index++) {
  14957. var subMaterial = this.subMaterials[index];
  14958. if (subMaterial) {
  14959. if (!this.subMaterials[index].isReady(mesh)) {
  14960. return false;
  14961. }
  14962. }
  14963. }
  14964. return true;
  14965. };
  14966. return MultiMaterial;
  14967. })(BABYLON.Material);
  14968. BABYLON.MultiMaterial = MultiMaterial;
  14969. })(BABYLON || (BABYLON = {}));
  14970. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  14971. (function (BABYLON) {
  14972. var Database = (function () {
  14973. function Database(urlToScene, callbackManifestChecked) {
  14974. // Handling various flavors of prefixed version of IndexedDB
  14975. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  14976. this.callbackManifestChecked = callbackManifestChecked;
  14977. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  14978. this.db = null;
  14979. this.enableSceneOffline = false;
  14980. this.enableTexturesOffline = false;
  14981. this.manifestVersionFound = 0;
  14982. this.mustUpdateRessources = false;
  14983. this.hasReachedQuota = false;
  14984. this.checkManifestFile();
  14985. }
  14986. Database.prototype.checkManifestFile = function () {
  14987. var _this = this;
  14988. function noManifestFile() {
  14989. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  14990. that.enableSceneOffline = false;
  14991. that.enableTexturesOffline = false;
  14992. that.callbackManifestChecked(false);
  14993. }
  14994. var that = this;
  14995. var manifestURL = this.currentSceneUrl + ".manifest";
  14996. var xhr = new XMLHttpRequest();
  14997. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  14998. xhr.open("GET", manifestURLTimeStamped, true);
  14999. xhr.addEventListener("load", function () {
  15000. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  15001. try {
  15002. var manifestFile = JSON.parse(xhr.response);
  15003. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  15004. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  15005. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  15006. _this.manifestVersionFound = manifestFile.version;
  15007. }
  15008. if (_this.callbackManifestChecked) {
  15009. _this.callbackManifestChecked(true);
  15010. }
  15011. }
  15012. catch (ex) {
  15013. noManifestFile();
  15014. }
  15015. }
  15016. else {
  15017. noManifestFile();
  15018. }
  15019. }, false);
  15020. xhr.addEventListener("error", function (event) {
  15021. noManifestFile();
  15022. }, false);
  15023. try {
  15024. xhr.send();
  15025. }
  15026. catch (ex) {
  15027. BABYLON.Tools.Error("Error on XHR send request.");
  15028. that.callbackManifestChecked(false);
  15029. }
  15030. };
  15031. Database.prototype.openAsync = function (successCallback, errorCallback) {
  15032. var _this = this;
  15033. function handleError() {
  15034. that.isSupported = false;
  15035. if (errorCallback)
  15036. errorCallback();
  15037. }
  15038. var that = this;
  15039. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  15040. // Your browser doesn't support IndexedDB
  15041. this.isSupported = false;
  15042. if (errorCallback)
  15043. errorCallback();
  15044. }
  15045. else {
  15046. // If the DB hasn't been opened or created yet
  15047. if (!this.db) {
  15048. this.hasReachedQuota = false;
  15049. this.isSupported = true;
  15050. var request = this.idbFactory.open("babylonjs", 1);
  15051. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  15052. request.onerror = function (event) {
  15053. handleError();
  15054. };
  15055. // executes when a version change transaction cannot complete due to other active transactions
  15056. request.onblocked = function (event) {
  15057. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  15058. handleError();
  15059. };
  15060. // DB has been opened successfully
  15061. request.onsuccess = function (event) {
  15062. _this.db = request.result;
  15063. successCallback();
  15064. };
  15065. // Initialization of the DB. Creating Scenes & Textures stores
  15066. request.onupgradeneeded = function (event) {
  15067. _this.db = (event.target).result;
  15068. try {
  15069. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  15070. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  15071. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  15072. }
  15073. catch (ex) {
  15074. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  15075. handleError();
  15076. }
  15077. };
  15078. }
  15079. else {
  15080. if (successCallback)
  15081. successCallback();
  15082. }
  15083. }
  15084. };
  15085. Database.prototype.loadImageFromDB = function (url, image) {
  15086. var _this = this;
  15087. var completeURL = Database.ReturnFullUrlLocation(url);
  15088. var saveAndLoadImage = function () {
  15089. if (!_this.hasReachedQuota && _this.db !== null) {
  15090. // the texture is not yet in the DB, let's try to save it
  15091. _this._saveImageIntoDBAsync(completeURL, image);
  15092. }
  15093. else {
  15094. image.src = url;
  15095. }
  15096. };
  15097. if (!this.mustUpdateRessources) {
  15098. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  15099. }
  15100. else {
  15101. saveAndLoadImage();
  15102. }
  15103. };
  15104. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  15105. if (this.isSupported && this.db !== null) {
  15106. var texture;
  15107. var transaction = this.db.transaction(["textures"]);
  15108. transaction.onabort = function (event) {
  15109. image.src = url;
  15110. };
  15111. transaction.oncomplete = function (event) {
  15112. var blobTextureURL;
  15113. if (texture) {
  15114. var URL = window.URL || window.webkitURL;
  15115. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  15116. image.onerror = function () {
  15117. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  15118. image.src = url;
  15119. };
  15120. image.src = blobTextureURL;
  15121. }
  15122. else {
  15123. notInDBCallback();
  15124. }
  15125. };
  15126. var getRequest = transaction.objectStore("textures").get(url);
  15127. getRequest.onsuccess = function (event) {
  15128. texture = (event.target).result;
  15129. };
  15130. getRequest.onerror = function (event) {
  15131. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  15132. image.src = url;
  15133. };
  15134. }
  15135. else {
  15136. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15137. image.src = url;
  15138. }
  15139. };
  15140. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  15141. var _this = this;
  15142. if (this.isSupported) {
  15143. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  15144. var generateBlobUrl = function () {
  15145. var blobTextureURL;
  15146. if (blob) {
  15147. var URL = window.URL || window.webkitURL;
  15148. try {
  15149. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  15150. }
  15151. catch (ex) {
  15152. blobTextureURL = URL.createObjectURL(blob);
  15153. }
  15154. }
  15155. image.src = blobTextureURL;
  15156. };
  15157. if (Database.isUASupportingBlobStorage) {
  15158. var xhr = new XMLHttpRequest(), blob;
  15159. xhr.open("GET", url, true);
  15160. xhr.responseType = "blob";
  15161. xhr.addEventListener("load", function () {
  15162. if (xhr.status === 200) {
  15163. // Blob as response (XHR2)
  15164. blob = xhr.response;
  15165. var transaction = _this.db.transaction(["textures"], "readwrite");
  15166. // the transaction could abort because of a QuotaExceededError error
  15167. transaction.onabort = function (event) {
  15168. try {
  15169. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15170. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15171. this.hasReachedQuota = true;
  15172. }
  15173. }
  15174. catch (ex) {
  15175. }
  15176. generateBlobUrl();
  15177. };
  15178. transaction.oncomplete = function (event) {
  15179. generateBlobUrl();
  15180. };
  15181. var newTexture = { textureUrl: url, data: blob };
  15182. try {
  15183. // Put the blob into the dabase
  15184. var addRequest = transaction.objectStore("textures").put(newTexture);
  15185. addRequest.onsuccess = function (event) {
  15186. };
  15187. addRequest.onerror = function (event) {
  15188. generateBlobUrl();
  15189. };
  15190. }
  15191. catch (ex) {
  15192. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  15193. if (ex.code === 25) {
  15194. Database.isUASupportingBlobStorage = false;
  15195. }
  15196. image.src = url;
  15197. }
  15198. }
  15199. else {
  15200. image.src = url;
  15201. }
  15202. }, false);
  15203. xhr.addEventListener("error", function (event) {
  15204. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  15205. image.src = url;
  15206. }, false);
  15207. xhr.send();
  15208. }
  15209. else {
  15210. image.src = url;
  15211. }
  15212. }
  15213. else {
  15214. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15215. image.src = url;
  15216. }
  15217. };
  15218. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  15219. var _this = this;
  15220. var updateVersion = function (event) {
  15221. // the version is not yet in the DB or we need to update it
  15222. _this._saveVersionIntoDBAsync(url, versionLoaded);
  15223. };
  15224. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  15225. };
  15226. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  15227. var _this = this;
  15228. if (this.isSupported) {
  15229. var version;
  15230. try {
  15231. var transaction = this.db.transaction(["versions"]);
  15232. transaction.oncomplete = function (event) {
  15233. if (version) {
  15234. // If the version in the JSON file is > than the version in DB
  15235. if (_this.manifestVersionFound > version.data) {
  15236. _this.mustUpdateRessources = true;
  15237. updateInDBCallback();
  15238. }
  15239. else {
  15240. callback(version.data);
  15241. }
  15242. }
  15243. else {
  15244. _this.mustUpdateRessources = true;
  15245. updateInDBCallback();
  15246. }
  15247. };
  15248. transaction.onabort = function (event) {
  15249. callback(-1);
  15250. };
  15251. var getRequest = transaction.objectStore("versions").get(url);
  15252. getRequest.onsuccess = function (event) {
  15253. version = (event.target).result;
  15254. };
  15255. getRequest.onerror = function (event) {
  15256. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  15257. callback(-1);
  15258. };
  15259. }
  15260. catch (ex) {
  15261. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  15262. callback(-1);
  15263. }
  15264. }
  15265. else {
  15266. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15267. callback(-1);
  15268. }
  15269. };
  15270. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  15271. var _this = this;
  15272. if (this.isSupported && !this.hasReachedQuota) {
  15273. try {
  15274. // Open a transaction to the database
  15275. var transaction = this.db.transaction(["versions"], "readwrite");
  15276. // the transaction could abort because of a QuotaExceededError error
  15277. transaction.onabort = function (event) {
  15278. try {
  15279. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15280. _this.hasReachedQuota = true;
  15281. }
  15282. }
  15283. catch (ex) {
  15284. }
  15285. callback(-1);
  15286. };
  15287. transaction.oncomplete = function (event) {
  15288. callback(_this.manifestVersionFound);
  15289. };
  15290. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  15291. // Put the scene into the database
  15292. var addRequest = transaction.objectStore("versions").put(newVersion);
  15293. addRequest.onsuccess = function (event) {
  15294. };
  15295. addRequest.onerror = function (event) {
  15296. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  15297. };
  15298. }
  15299. catch (ex) {
  15300. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  15301. callback(-1);
  15302. }
  15303. }
  15304. else {
  15305. callback(-1);
  15306. }
  15307. };
  15308. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  15309. var _this = this;
  15310. var completeUrl = Database.ReturnFullUrlLocation(url);
  15311. var saveAndLoadFile = function (event) {
  15312. // the scene is not yet in the DB, let's try to save it
  15313. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  15314. };
  15315. this._checkVersionFromDB(completeUrl, function (version) {
  15316. if (version !== -1) {
  15317. if (!_this.mustUpdateRessources) {
  15318. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  15319. }
  15320. else {
  15321. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  15322. }
  15323. }
  15324. else {
  15325. errorCallback();
  15326. }
  15327. });
  15328. };
  15329. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  15330. if (this.isSupported) {
  15331. var targetStore;
  15332. if (url.indexOf(".babylon") !== -1) {
  15333. targetStore = "scenes";
  15334. }
  15335. else {
  15336. targetStore = "textures";
  15337. }
  15338. var file;
  15339. var transaction = this.db.transaction([targetStore]);
  15340. transaction.oncomplete = function (event) {
  15341. if (file) {
  15342. callback(file.data);
  15343. }
  15344. else {
  15345. notInDBCallback();
  15346. }
  15347. };
  15348. transaction.onabort = function (event) {
  15349. notInDBCallback();
  15350. };
  15351. var getRequest = transaction.objectStore(targetStore).get(url);
  15352. getRequest.onsuccess = function (event) {
  15353. file = (event.target).result;
  15354. };
  15355. getRequest.onerror = function (event) {
  15356. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  15357. notInDBCallback();
  15358. };
  15359. }
  15360. else {
  15361. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15362. callback();
  15363. }
  15364. };
  15365. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  15366. var _this = this;
  15367. if (this.isSupported) {
  15368. var targetStore;
  15369. if (url.indexOf(".babylon") !== -1) {
  15370. targetStore = "scenes";
  15371. }
  15372. else {
  15373. targetStore = "textures";
  15374. }
  15375. // Create XHR
  15376. var xhr = new XMLHttpRequest(), fileData;
  15377. xhr.open("GET", url, true);
  15378. if (useArrayBuffer) {
  15379. xhr.responseType = "arraybuffer";
  15380. }
  15381. xhr.onprogress = progressCallback;
  15382. xhr.addEventListener("load", function () {
  15383. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  15384. // Blob as response (XHR2)
  15385. //fileData = xhr.responseText;
  15386. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  15387. if (!_this.hasReachedQuota) {
  15388. // Open a transaction to the database
  15389. var transaction = _this.db.transaction([targetStore], "readwrite");
  15390. // the transaction could abort because of a QuotaExceededError error
  15391. transaction.onabort = function (event) {
  15392. try {
  15393. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15394. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15395. this.hasReachedQuota = true;
  15396. }
  15397. }
  15398. catch (ex) {
  15399. }
  15400. callback(fileData);
  15401. };
  15402. transaction.oncomplete = function (event) {
  15403. callback(fileData);
  15404. };
  15405. var newFile;
  15406. if (targetStore === "scenes") {
  15407. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  15408. }
  15409. else {
  15410. newFile = { textureUrl: url, data: fileData };
  15411. }
  15412. try {
  15413. // Put the scene into the database
  15414. var addRequest = transaction.objectStore(targetStore).put(newFile);
  15415. addRequest.onsuccess = function (event) {
  15416. };
  15417. addRequest.onerror = function (event) {
  15418. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  15419. };
  15420. }
  15421. catch (ex) {
  15422. callback(fileData);
  15423. }
  15424. }
  15425. else {
  15426. callback(fileData);
  15427. }
  15428. }
  15429. else {
  15430. callback();
  15431. }
  15432. }, false);
  15433. xhr.addEventListener("error", function (event) {
  15434. BABYLON.Tools.Error("error on XHR request.");
  15435. callback();
  15436. }, false);
  15437. xhr.send();
  15438. }
  15439. else {
  15440. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15441. callback();
  15442. }
  15443. };
  15444. Database.isUASupportingBlobStorage = true;
  15445. Database.parseURL = function (url) {
  15446. var a = document.createElement('a');
  15447. a.href = url;
  15448. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  15449. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  15450. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  15451. return absLocation;
  15452. };
  15453. Database.ReturnFullUrlLocation = function (url) {
  15454. if (url.indexOf("http:/") === -1) {
  15455. return (BABYLON.Database.parseURL(window.location.href) + url);
  15456. }
  15457. else {
  15458. return url;
  15459. }
  15460. };
  15461. return Database;
  15462. })();
  15463. BABYLON.Database = Database;
  15464. })(BABYLON || (BABYLON = {}));
  15465. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  15466. (function (BABYLON) {
  15467. var SpriteManager = (function () {
  15468. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  15469. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15470. this.name = name;
  15471. this.cellSize = cellSize;
  15472. this.sprites = new Array();
  15473. this.renderingGroupId = 0;
  15474. this.fogEnabled = true;
  15475. this._vertexDeclaration = [4, 4, 4, 4];
  15476. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  15477. this._capacity = capacity;
  15478. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  15479. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15480. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15481. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  15482. this._scene = scene;
  15483. this._scene.spriteManagers.push(this);
  15484. // VBO
  15485. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15486. var indices = [];
  15487. var index = 0;
  15488. for (var count = 0; count < capacity; count++) {
  15489. indices.push(index);
  15490. indices.push(index + 1);
  15491. indices.push(index + 2);
  15492. indices.push(index);
  15493. indices.push(index + 2);
  15494. indices.push(index + 3);
  15495. index += 4;
  15496. }
  15497. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15498. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15499. // Effects
  15500. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  15501. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  15502. }
  15503. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  15504. var arrayOffset = index * 16;
  15505. if (offsetX === 0)
  15506. offsetX = this._epsilon;
  15507. else if (offsetX === 1)
  15508. offsetX = 1 - this._epsilon;
  15509. if (offsetY === 0)
  15510. offsetY = this._epsilon;
  15511. else if (offsetY === 1)
  15512. offsetY = 1 - this._epsilon;
  15513. this._vertices[arrayOffset] = sprite.position.x;
  15514. this._vertices[arrayOffset + 1] = sprite.position.y;
  15515. this._vertices[arrayOffset + 2] = sprite.position.z;
  15516. this._vertices[arrayOffset + 3] = sprite.angle;
  15517. this._vertices[arrayOffset + 4] = sprite.width;
  15518. this._vertices[arrayOffset + 5] = sprite.height;
  15519. this._vertices[arrayOffset + 6] = offsetX;
  15520. this._vertices[arrayOffset + 7] = offsetY;
  15521. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  15522. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  15523. var offset = (sprite.cellIndex / rowSize) >> 0;
  15524. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  15525. this._vertices[arrayOffset + 11] = offset;
  15526. // Color
  15527. this._vertices[arrayOffset + 12] = sprite.color.r;
  15528. this._vertices[arrayOffset + 13] = sprite.color.g;
  15529. this._vertices[arrayOffset + 14] = sprite.color.b;
  15530. this._vertices[arrayOffset + 15] = sprite.color.a;
  15531. };
  15532. SpriteManager.prototype.render = function () {
  15533. // Check
  15534. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  15535. return;
  15536. var engine = this._scene.getEngine();
  15537. var baseSize = this._spriteTexture.getBaseSize();
  15538. // Sprites
  15539. var deltaTime = engine.getDeltaTime();
  15540. var max = Math.min(this._capacity, this.sprites.length);
  15541. var rowSize = baseSize.width / this.cellSize;
  15542. var offset = 0;
  15543. for (var index = 0; index < max; index++) {
  15544. var sprite = this.sprites[index];
  15545. if (!sprite) {
  15546. continue;
  15547. }
  15548. sprite._animate(deltaTime);
  15549. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  15550. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  15551. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  15552. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  15553. }
  15554. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15555. // Render
  15556. var effect = this._effectBase;
  15557. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15558. effect = this._effectFog;
  15559. }
  15560. engine.enableEffect(effect);
  15561. var viewMatrix = this._scene.getViewMatrix();
  15562. effect.setTexture("diffuseSampler", this._spriteTexture);
  15563. effect.setMatrix("view", viewMatrix);
  15564. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15565. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  15566. // Fog
  15567. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15568. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  15569. effect.setColor3("vFogColor", this._scene.fogColor);
  15570. }
  15571. // VBOs
  15572. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15573. // Draw order
  15574. effect.setBool("alphaTest", true);
  15575. engine.setColorWrite(false);
  15576. engine.draw(true, 0, max * 6);
  15577. engine.setColorWrite(true);
  15578. effect.setBool("alphaTest", false);
  15579. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15580. engine.draw(true, 0, max * 6);
  15581. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15582. };
  15583. SpriteManager.prototype.dispose = function () {
  15584. if (this._vertexBuffer) {
  15585. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15586. this._vertexBuffer = null;
  15587. }
  15588. if (this._indexBuffer) {
  15589. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15590. this._indexBuffer = null;
  15591. }
  15592. if (this._spriteTexture) {
  15593. this._spriteTexture.dispose();
  15594. this._spriteTexture = null;
  15595. }
  15596. // Remove from scene
  15597. var index = this._scene.spriteManagers.indexOf(this);
  15598. this._scene.spriteManagers.splice(index, 1);
  15599. // Callback
  15600. if (this.onDispose) {
  15601. this.onDispose();
  15602. }
  15603. };
  15604. return SpriteManager;
  15605. })();
  15606. BABYLON.SpriteManager = SpriteManager;
  15607. })(BABYLON || (BABYLON = {}));
  15608. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  15609. (function (BABYLON) {
  15610. var Sprite = (function () {
  15611. function Sprite(name, manager) {
  15612. this.name = name;
  15613. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15614. this.width = 1.0;
  15615. this.height = 1.0;
  15616. this.angle = 0;
  15617. this.cellIndex = 0;
  15618. this.invertU = 0;
  15619. this.invertV = 0;
  15620. this.animations = new Array();
  15621. this._animationStarted = false;
  15622. this._loopAnimation = false;
  15623. this._fromIndex = 0;
  15624. this._toIndex = 0;
  15625. this._delay = 0;
  15626. this._direction = 1;
  15627. this._frameCount = 0;
  15628. this._time = 0;
  15629. this._manager = manager;
  15630. this._manager.sprites.push(this);
  15631. this.position = BABYLON.Vector3.Zero();
  15632. }
  15633. Object.defineProperty(Sprite.prototype, "size", {
  15634. get: function () {
  15635. return this.width;
  15636. },
  15637. set: function (value) {
  15638. this.width = value;
  15639. this.height = value;
  15640. },
  15641. enumerable: true,
  15642. configurable: true
  15643. });
  15644. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  15645. this._fromIndex = from;
  15646. this._toIndex = to;
  15647. this._loopAnimation = loop;
  15648. this._delay = delay;
  15649. this._animationStarted = true;
  15650. this._direction = from < to ? 1 : -1;
  15651. this.cellIndex = from;
  15652. this._time = 0;
  15653. };
  15654. Sprite.prototype.stopAnimation = function () {
  15655. this._animationStarted = false;
  15656. };
  15657. Sprite.prototype._animate = function (deltaTime) {
  15658. if (!this._animationStarted)
  15659. return;
  15660. this._time += deltaTime;
  15661. if (this._time > this._delay) {
  15662. this._time = this._time % this._delay;
  15663. this.cellIndex += this._direction;
  15664. if (this.cellIndex == this._toIndex) {
  15665. if (this._loopAnimation) {
  15666. this.cellIndex = this._fromIndex;
  15667. }
  15668. else {
  15669. this._animationStarted = false;
  15670. if (this.disposeWhenFinishedAnimating) {
  15671. this.dispose();
  15672. }
  15673. }
  15674. }
  15675. }
  15676. };
  15677. Sprite.prototype.dispose = function () {
  15678. for (var i = 0; i < this._manager.sprites.length; i++) {
  15679. if (this._manager.sprites[i] == this) {
  15680. this._manager.sprites.splice(i, 1);
  15681. }
  15682. }
  15683. };
  15684. return Sprite;
  15685. })();
  15686. BABYLON.Sprite = Sprite;
  15687. })(BABYLON || (BABYLON = {}));
  15688. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  15689. (function (BABYLON) {
  15690. var Layer = (function () {
  15691. function Layer(name, imgUrl, scene, isBackground, color) {
  15692. this.name = name;
  15693. this._vertexDeclaration = [2];
  15694. this._vertexStrideSize = 2 * 4;
  15695. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  15696. this.isBackground = isBackground === undefined ? true : isBackground;
  15697. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  15698. this._scene = scene;
  15699. this._scene.layers.push(this);
  15700. // VBO
  15701. var vertices = [];
  15702. vertices.push(1, 1);
  15703. vertices.push(-1, 1);
  15704. vertices.push(-1, -1);
  15705. vertices.push(1, -1);
  15706. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15707. // Indices
  15708. var indices = [];
  15709. indices.push(0);
  15710. indices.push(1);
  15711. indices.push(2);
  15712. indices.push(0);
  15713. indices.push(2);
  15714. indices.push(3);
  15715. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15716. // Effects
  15717. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  15718. }
  15719. Layer.prototype.render = function () {
  15720. // Check
  15721. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  15722. return;
  15723. var engine = this._scene.getEngine();
  15724. // Render
  15725. engine.enableEffect(this._effect);
  15726. engine.setState(false);
  15727. // Texture
  15728. this._effect.setTexture("textureSampler", this.texture);
  15729. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  15730. // Color
  15731. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  15732. // VBOs
  15733. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15734. // Draw order
  15735. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15736. engine.draw(true, 0, 6);
  15737. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15738. };
  15739. Layer.prototype.dispose = function () {
  15740. if (this._vertexBuffer) {
  15741. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15742. this._vertexBuffer = null;
  15743. }
  15744. if (this._indexBuffer) {
  15745. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15746. this._indexBuffer = null;
  15747. }
  15748. if (this.texture) {
  15749. this.texture.dispose();
  15750. this.texture = null;
  15751. }
  15752. // Remove from scene
  15753. var index = this._scene.layers.indexOf(this);
  15754. this._scene.layers.splice(index, 1);
  15755. // Callback
  15756. if (this.onDispose) {
  15757. this.onDispose();
  15758. }
  15759. };
  15760. return Layer;
  15761. })();
  15762. BABYLON.Layer = Layer;
  15763. })(BABYLON || (BABYLON = {}));
  15764. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  15765. (function (BABYLON) {
  15766. var Particle = (function () {
  15767. function Particle() {
  15768. this.position = BABYLON.Vector3.Zero();
  15769. this.direction = BABYLON.Vector3.Zero();
  15770. this.color = new BABYLON.Color4(0, 0, 0, 0);
  15771. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  15772. this.lifeTime = 1.0;
  15773. this.age = 0;
  15774. this.size = 0;
  15775. this.angle = 0;
  15776. this.angularSpeed = 0;
  15777. }
  15778. Particle.prototype.copyTo = function (other) {
  15779. other.position.copyFrom(this.position);
  15780. other.direction.copyFrom(this.direction);
  15781. other.color.copyFrom(this.color);
  15782. other.colorStep.copyFrom(this.colorStep);
  15783. other.lifeTime = this.lifeTime;
  15784. other.age = this.age;
  15785. other.size = this.size;
  15786. other.angle = this.angle;
  15787. other.angularSpeed = this.angularSpeed;
  15788. };
  15789. return Particle;
  15790. })();
  15791. BABYLON.Particle = Particle;
  15792. })(BABYLON || (BABYLON = {}));
  15793. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  15794. (function (BABYLON) {
  15795. var randomNumber = function (min, max) {
  15796. if (min === max) {
  15797. return (min);
  15798. }
  15799. var random = Math.random();
  15800. return ((random * (max - min)) + min);
  15801. };
  15802. var ParticleSystem = (function () {
  15803. function ParticleSystem(name, capacity, scene, customEffect) {
  15804. var _this = this;
  15805. this.name = name;
  15806. this.renderingGroupId = 0;
  15807. this.emitter = null;
  15808. this.emitRate = 10;
  15809. this.manualEmitCount = -1;
  15810. this.updateSpeed = 0.01;
  15811. this.targetStopDuration = 0;
  15812. this.disposeOnStop = false;
  15813. this.minEmitPower = 1;
  15814. this.maxEmitPower = 1;
  15815. this.minLifeTime = 1;
  15816. this.maxLifeTime = 1;
  15817. this.minSize = 1;
  15818. this.maxSize = 1;
  15819. this.minAngularSpeed = 0;
  15820. this.maxAngularSpeed = 0;
  15821. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  15822. this.forceDepthWrite = false;
  15823. this.gravity = BABYLON.Vector3.Zero();
  15824. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  15825. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  15826. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  15827. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15828. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15829. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15830. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  15831. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15832. this.particles = new Array();
  15833. this._vertexDeclaration = [3, 4, 4];
  15834. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  15835. this._stockParticles = new Array();
  15836. this._newPartsExcess = 0;
  15837. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  15838. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  15839. this._scaledDirection = BABYLON.Vector3.Zero();
  15840. this._scaledGravity = BABYLON.Vector3.Zero();
  15841. this._currentRenderId = -1;
  15842. this._started = false;
  15843. this._stopped = false;
  15844. this._actualFrame = 0;
  15845. this.id = name;
  15846. this._capacity = capacity;
  15847. this._scene = scene;
  15848. this._customEffect = customEffect;
  15849. scene.particleSystems.push(this);
  15850. // VBO
  15851. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15852. var indices = [];
  15853. var index = 0;
  15854. for (var count = 0; count < capacity; count++) {
  15855. indices.push(index);
  15856. indices.push(index + 1);
  15857. indices.push(index + 2);
  15858. indices.push(index);
  15859. indices.push(index + 2);
  15860. indices.push(index + 3);
  15861. index += 4;
  15862. }
  15863. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15864. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15865. // Default behaviors
  15866. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  15867. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  15868. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  15869. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  15870. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  15871. };
  15872. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  15873. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  15874. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  15875. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  15876. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  15877. };
  15878. this.updateFunction = function (particles) {
  15879. for (var index = 0; index < particles.length; index++) {
  15880. var particle = particles[index];
  15881. particle.age += _this._scaledUpdateSpeed;
  15882. if (particle.age >= particle.lifeTime) {
  15883. _this.recycleParticle(particle);
  15884. index--;
  15885. continue;
  15886. }
  15887. else {
  15888. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  15889. particle.color.addInPlace(_this._scaledColorStep);
  15890. if (particle.color.a < 0)
  15891. particle.color.a = 0;
  15892. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  15893. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  15894. particle.position.addInPlace(_this._scaledDirection);
  15895. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  15896. particle.direction.addInPlace(_this._scaledGravity);
  15897. }
  15898. }
  15899. };
  15900. }
  15901. ParticleSystem.prototype.recycleParticle = function (particle) {
  15902. var lastParticle = this.particles.pop();
  15903. if (lastParticle !== particle) {
  15904. lastParticle.copyTo(particle);
  15905. this._stockParticles.push(lastParticle);
  15906. }
  15907. };
  15908. ParticleSystem.prototype.getCapacity = function () {
  15909. return this._capacity;
  15910. };
  15911. ParticleSystem.prototype.isAlive = function () {
  15912. return this._alive;
  15913. };
  15914. ParticleSystem.prototype.isStarted = function () {
  15915. return this._started;
  15916. };
  15917. ParticleSystem.prototype.start = function () {
  15918. this._started = true;
  15919. this._stopped = false;
  15920. this._actualFrame = 0;
  15921. };
  15922. ParticleSystem.prototype.stop = function () {
  15923. this._stopped = true;
  15924. };
  15925. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  15926. var offset = index * 11;
  15927. this._vertices[offset] = particle.position.x;
  15928. this._vertices[offset + 1] = particle.position.y;
  15929. this._vertices[offset + 2] = particle.position.z;
  15930. this._vertices[offset + 3] = particle.color.r;
  15931. this._vertices[offset + 4] = particle.color.g;
  15932. this._vertices[offset + 5] = particle.color.b;
  15933. this._vertices[offset + 6] = particle.color.a;
  15934. this._vertices[offset + 7] = particle.angle;
  15935. this._vertices[offset + 8] = particle.size;
  15936. this._vertices[offset + 9] = offsetX;
  15937. this._vertices[offset + 10] = offsetY;
  15938. };
  15939. ParticleSystem.prototype._update = function (newParticles) {
  15940. // Update current
  15941. this._alive = this.particles.length > 0;
  15942. this.updateFunction(this.particles);
  15943. // Add new ones
  15944. var worldMatrix;
  15945. if (this.emitter.position) {
  15946. worldMatrix = this.emitter.getWorldMatrix();
  15947. }
  15948. else {
  15949. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  15950. }
  15951. for (var index = 0; index < newParticles; index++) {
  15952. if (this.particles.length === this._capacity) {
  15953. break;
  15954. }
  15955. if (this._stockParticles.length !== 0) {
  15956. var particle = this._stockParticles.pop();
  15957. particle.age = 0;
  15958. }
  15959. else {
  15960. particle = new BABYLON.Particle();
  15961. }
  15962. this.particles.push(particle);
  15963. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  15964. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  15965. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  15966. particle.size = randomNumber(this.minSize, this.maxSize);
  15967. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  15968. this.startPositionFunction(worldMatrix, particle.position);
  15969. var step = randomNumber(0, 1.0);
  15970. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  15971. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  15972. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  15973. }
  15974. };
  15975. ParticleSystem.prototype._getEffect = function () {
  15976. if (this._customEffect) {
  15977. return this._customEffect;
  15978. }
  15979. ;
  15980. var defines = [];
  15981. if (this._scene.clipPlane) {
  15982. defines.push("#define CLIPPLANE");
  15983. }
  15984. // Effect
  15985. var join = defines.join("\n");
  15986. if (this._cachedDefines !== join) {
  15987. this._cachedDefines = join;
  15988. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  15989. }
  15990. return this._effect;
  15991. };
  15992. ParticleSystem.prototype.animate = function () {
  15993. if (!this._started)
  15994. return;
  15995. var effect = this._getEffect();
  15996. // Check
  15997. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  15998. return;
  15999. if (this._currentRenderId === this._scene.getRenderId()) {
  16000. return;
  16001. }
  16002. this._currentRenderId = this._scene.getRenderId();
  16003. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  16004. // determine the number of particles we need to create
  16005. var emitCout;
  16006. if (this.manualEmitCount > -1) {
  16007. emitCout = this.manualEmitCount;
  16008. this.manualEmitCount = 0;
  16009. }
  16010. else {
  16011. emitCout = this.emitRate;
  16012. }
  16013. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  16014. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  16015. if (this._newPartsExcess > 1.0) {
  16016. newParticles += this._newPartsExcess >> 0;
  16017. this._newPartsExcess -= this._newPartsExcess >> 0;
  16018. }
  16019. this._alive = false;
  16020. if (!this._stopped) {
  16021. this._actualFrame += this._scaledUpdateSpeed;
  16022. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  16023. this.stop();
  16024. }
  16025. else {
  16026. newParticles = 0;
  16027. }
  16028. this._update(newParticles);
  16029. // Stopped?
  16030. if (this._stopped) {
  16031. if (!this._alive) {
  16032. this._started = false;
  16033. if (this.disposeOnStop) {
  16034. this._scene._toBeDisposed.push(this);
  16035. }
  16036. }
  16037. }
  16038. // Update VBO
  16039. var offset = 0;
  16040. for (var index = 0; index < this.particles.length; index++) {
  16041. var particle = this.particles[index];
  16042. this._appendParticleVertex(offset++, particle, 0, 0);
  16043. this._appendParticleVertex(offset++, particle, 1, 0);
  16044. this._appendParticleVertex(offset++, particle, 1, 1);
  16045. this._appendParticleVertex(offset++, particle, 0, 1);
  16046. }
  16047. var engine = this._scene.getEngine();
  16048. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  16049. };
  16050. ParticleSystem.prototype.render = function () {
  16051. var effect = this._getEffect();
  16052. // Check
  16053. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  16054. return 0;
  16055. var engine = this._scene.getEngine();
  16056. // Render
  16057. engine.enableEffect(effect);
  16058. engine.setState(false);
  16059. var viewMatrix = this._scene.getViewMatrix();
  16060. effect.setTexture("diffuseSampler", this.particleTexture);
  16061. effect.setMatrix("view", viewMatrix);
  16062. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  16063. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  16064. if (this._scene.clipPlane) {
  16065. var clipPlane = this._scene.clipPlane;
  16066. var invView = viewMatrix.clone();
  16067. invView.invert();
  16068. effect.setMatrix("invView", invView);
  16069. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  16070. }
  16071. // VBOs
  16072. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16073. // Draw order
  16074. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  16075. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16076. }
  16077. else {
  16078. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16079. }
  16080. if (this.forceDepthWrite) {
  16081. engine.setDepthWrite(true);
  16082. }
  16083. engine.draw(true, 0, this.particles.length * 6);
  16084. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16085. return this.particles.length;
  16086. };
  16087. ParticleSystem.prototype.dispose = function () {
  16088. if (this._vertexBuffer) {
  16089. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16090. this._vertexBuffer = null;
  16091. }
  16092. if (this._indexBuffer) {
  16093. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16094. this._indexBuffer = null;
  16095. }
  16096. if (this.particleTexture) {
  16097. this.particleTexture.dispose();
  16098. this.particleTexture = null;
  16099. }
  16100. // Remove from scene
  16101. var index = this._scene.particleSystems.indexOf(this);
  16102. this._scene.particleSystems.splice(index, 1);
  16103. // Callback
  16104. if (this.onDispose) {
  16105. this.onDispose();
  16106. }
  16107. };
  16108. // Clone
  16109. ParticleSystem.prototype.clone = function (name, newEmitter) {
  16110. var result = new ParticleSystem(name, this._capacity, this._scene);
  16111. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  16112. if (newEmitter === undefined) {
  16113. newEmitter = this.emitter;
  16114. }
  16115. result.emitter = newEmitter;
  16116. if (this.particleTexture) {
  16117. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  16118. }
  16119. result.start();
  16120. return result;
  16121. };
  16122. // Statics
  16123. ParticleSystem.BLENDMODE_ONEONE = 0;
  16124. ParticleSystem.BLENDMODE_STANDARD = 1;
  16125. return ParticleSystem;
  16126. })();
  16127. BABYLON.ParticleSystem = ParticleSystem;
  16128. })(BABYLON || (BABYLON = {}));
  16129. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  16130. (function (BABYLON) {
  16131. var Animation = (function () {
  16132. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  16133. this.name = name;
  16134. this.targetProperty = targetProperty;
  16135. this.framePerSecond = framePerSecond;
  16136. this.dataType = dataType;
  16137. this.loopMode = loopMode;
  16138. this._offsetsCache = {};
  16139. this._highLimitsCache = {};
  16140. this._stopped = false;
  16141. this.targetPropertyPath = targetProperty.split(".");
  16142. this.dataType = dataType;
  16143. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  16144. }
  16145. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  16146. var dataType = undefined;
  16147. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  16148. dataType = Animation.ANIMATIONTYPE_FLOAT;
  16149. }
  16150. else if (from instanceof BABYLON.Quaternion) {
  16151. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  16152. }
  16153. else if (from instanceof BABYLON.Vector3) {
  16154. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  16155. }
  16156. else if (from instanceof BABYLON.Vector2) {
  16157. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  16158. }
  16159. else if (from instanceof BABYLON.Color3) {
  16160. dataType = Animation.ANIMATIONTYPE_COLOR3;
  16161. }
  16162. if (dataType == undefined) {
  16163. return null;
  16164. }
  16165. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  16166. var keys = [];
  16167. keys.push({ frame: 0, value: from });
  16168. keys.push({ frame: totalFrame, value: to });
  16169. animation.setKeys(keys);
  16170. mesh.animations.push(animation);
  16171. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  16172. };
  16173. // Methods
  16174. Animation.prototype.isStopped = function () {
  16175. return this._stopped;
  16176. };
  16177. Animation.prototype.getKeys = function () {
  16178. return this._keys;
  16179. };
  16180. Animation.prototype.getEasingFunction = function () {
  16181. return this._easingFunction;
  16182. };
  16183. Animation.prototype.setEasingFunction = function (easingFunction) {
  16184. this._easingFunction = easingFunction;
  16185. };
  16186. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  16187. return startValue + (endValue - startValue) * gradient;
  16188. };
  16189. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  16190. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  16191. };
  16192. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  16193. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  16194. };
  16195. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  16196. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  16197. };
  16198. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  16199. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  16200. };
  16201. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  16202. var startScale = new BABYLON.Vector3(0, 0, 0);
  16203. var startRotation = new BABYLON.Quaternion();
  16204. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  16205. startValue.decompose(startScale, startRotation, startTranslation);
  16206. var endScale = new BABYLON.Vector3(0, 0, 0);
  16207. var endRotation = new BABYLON.Quaternion();
  16208. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  16209. endValue.decompose(endScale, endRotation, endTranslation);
  16210. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  16211. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  16212. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  16213. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  16214. return result;
  16215. };
  16216. Animation.prototype.clone = function () {
  16217. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  16218. clone.setKeys(this._keys);
  16219. return clone;
  16220. };
  16221. Animation.prototype.setKeys = function (values) {
  16222. this._keys = values.slice(0);
  16223. this._offsetsCache = {};
  16224. this._highLimitsCache = {};
  16225. };
  16226. Animation.prototype._getKeyValue = function (value) {
  16227. if (typeof value === "function") {
  16228. return value();
  16229. }
  16230. return value;
  16231. };
  16232. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  16233. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  16234. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  16235. }
  16236. this.currentFrame = currentFrame;
  16237. // Try to get a hash to find the right key
  16238. 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));
  16239. if (this._keys[startKey].frame >= currentFrame) {
  16240. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  16241. startKey--;
  16242. }
  16243. }
  16244. for (var key = startKey; key < this._keys.length; key++) {
  16245. if (this._keys[key + 1].frame >= currentFrame) {
  16246. var startValue = this._getKeyValue(this._keys[key].value);
  16247. var endValue = this._getKeyValue(this._keys[key + 1].value);
  16248. // gradient : percent of currentFrame between the frame inf and the frame sup
  16249. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  16250. // check for easingFunction and correction of gradient
  16251. if (this._easingFunction != null) {
  16252. gradient = this._easingFunction.ease(gradient);
  16253. }
  16254. switch (this.dataType) {
  16255. case Animation.ANIMATIONTYPE_FLOAT:
  16256. switch (loopMode) {
  16257. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16258. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16259. return this.floatInterpolateFunction(startValue, endValue, gradient);
  16260. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16261. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  16262. }
  16263. break;
  16264. case Animation.ANIMATIONTYPE_QUATERNION:
  16265. var quaternion = null;
  16266. switch (loopMode) {
  16267. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16268. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16269. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  16270. break;
  16271. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16272. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16273. break;
  16274. }
  16275. return quaternion;
  16276. case Animation.ANIMATIONTYPE_VECTOR3:
  16277. switch (loopMode) {
  16278. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16279. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16280. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  16281. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16282. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16283. }
  16284. case Animation.ANIMATIONTYPE_VECTOR2:
  16285. switch (loopMode) {
  16286. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16287. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16288. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  16289. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16290. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16291. }
  16292. case Animation.ANIMATIONTYPE_COLOR3:
  16293. switch (loopMode) {
  16294. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16295. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16296. return this.color3InterpolateFunction(startValue, endValue, gradient);
  16297. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16298. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16299. }
  16300. case Animation.ANIMATIONTYPE_MATRIX:
  16301. switch (loopMode) {
  16302. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16303. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16304. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16305. return startValue;
  16306. }
  16307. default:
  16308. break;
  16309. }
  16310. break;
  16311. }
  16312. }
  16313. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  16314. };
  16315. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  16316. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  16317. this._stopped = true;
  16318. return false;
  16319. }
  16320. var returnValue = true;
  16321. // Adding a start key at frame 0 if missing
  16322. if (this._keys[0].frame !== 0) {
  16323. var newKey = { frame: 0, value: this._keys[0].value };
  16324. this._keys.splice(0, 0, newKey);
  16325. }
  16326. // Check limits
  16327. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  16328. from = this._keys[0].frame;
  16329. }
  16330. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  16331. to = this._keys[this._keys.length - 1].frame;
  16332. }
  16333. // Compute ratio
  16334. var range = to - from;
  16335. var offsetValue;
  16336. // ratio represents the frame delta between from and to
  16337. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  16338. var highLimitValue = 0;
  16339. if (ratio > range && !loop) {
  16340. returnValue = false;
  16341. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  16342. }
  16343. else {
  16344. // Get max value if required
  16345. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  16346. var keyOffset = to.toString() + from.toString();
  16347. if (!this._offsetsCache[keyOffset]) {
  16348. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16349. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16350. switch (this.dataType) {
  16351. case Animation.ANIMATIONTYPE_FLOAT:
  16352. this._offsetsCache[keyOffset] = toValue - fromValue;
  16353. break;
  16354. case Animation.ANIMATIONTYPE_QUATERNION:
  16355. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16356. break;
  16357. case Animation.ANIMATIONTYPE_VECTOR3:
  16358. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16359. case Animation.ANIMATIONTYPE_VECTOR2:
  16360. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16361. case Animation.ANIMATIONTYPE_COLOR3:
  16362. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16363. default:
  16364. break;
  16365. }
  16366. this._highLimitsCache[keyOffset] = toValue;
  16367. }
  16368. highLimitValue = this._highLimitsCache[keyOffset];
  16369. offsetValue = this._offsetsCache[keyOffset];
  16370. }
  16371. }
  16372. if (offsetValue === undefined) {
  16373. switch (this.dataType) {
  16374. case Animation.ANIMATIONTYPE_FLOAT:
  16375. offsetValue = 0;
  16376. break;
  16377. case Animation.ANIMATIONTYPE_QUATERNION:
  16378. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  16379. break;
  16380. case Animation.ANIMATIONTYPE_VECTOR3:
  16381. offsetValue = BABYLON.Vector3.Zero();
  16382. break;
  16383. case Animation.ANIMATIONTYPE_VECTOR2:
  16384. offsetValue = BABYLON.Vector2.Zero();
  16385. break;
  16386. case Animation.ANIMATIONTYPE_COLOR3:
  16387. offsetValue = BABYLON.Color3.Black();
  16388. }
  16389. }
  16390. // Compute value
  16391. var repeatCount = (ratio / range) >> 0;
  16392. var currentFrame = returnValue ? from + ratio % range : to;
  16393. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  16394. // Set value
  16395. if (this.targetPropertyPath.length > 1) {
  16396. var property = this._target[this.targetPropertyPath[0]];
  16397. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  16398. property = property[this.targetPropertyPath[index]];
  16399. }
  16400. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  16401. }
  16402. else {
  16403. this._target[this.targetPropertyPath[0]] = currentValue;
  16404. }
  16405. if (this._target.markAsDirty) {
  16406. this._target.markAsDirty(this.targetProperty);
  16407. }
  16408. if (!returnValue) {
  16409. this._stopped = true;
  16410. }
  16411. return returnValue;
  16412. };
  16413. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  16414. get: function () {
  16415. return Animation._ANIMATIONTYPE_FLOAT;
  16416. },
  16417. enumerable: true,
  16418. configurable: true
  16419. });
  16420. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  16421. get: function () {
  16422. return Animation._ANIMATIONTYPE_VECTOR3;
  16423. },
  16424. enumerable: true,
  16425. configurable: true
  16426. });
  16427. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  16428. get: function () {
  16429. return Animation._ANIMATIONTYPE_VECTOR2;
  16430. },
  16431. enumerable: true,
  16432. configurable: true
  16433. });
  16434. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  16435. get: function () {
  16436. return Animation._ANIMATIONTYPE_QUATERNION;
  16437. },
  16438. enumerable: true,
  16439. configurable: true
  16440. });
  16441. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  16442. get: function () {
  16443. return Animation._ANIMATIONTYPE_MATRIX;
  16444. },
  16445. enumerable: true,
  16446. configurable: true
  16447. });
  16448. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  16449. get: function () {
  16450. return Animation._ANIMATIONTYPE_COLOR3;
  16451. },
  16452. enumerable: true,
  16453. configurable: true
  16454. });
  16455. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  16456. get: function () {
  16457. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  16458. },
  16459. enumerable: true,
  16460. configurable: true
  16461. });
  16462. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  16463. get: function () {
  16464. return Animation._ANIMATIONLOOPMODE_CYCLE;
  16465. },
  16466. enumerable: true,
  16467. configurable: true
  16468. });
  16469. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  16470. get: function () {
  16471. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  16472. },
  16473. enumerable: true,
  16474. configurable: true
  16475. });
  16476. // Statics
  16477. Animation._ANIMATIONTYPE_FLOAT = 0;
  16478. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  16479. Animation._ANIMATIONTYPE_QUATERNION = 2;
  16480. Animation._ANIMATIONTYPE_MATRIX = 3;
  16481. Animation._ANIMATIONTYPE_COLOR3 = 4;
  16482. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  16483. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  16484. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  16485. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  16486. return Animation;
  16487. })();
  16488. BABYLON.Animation = Animation;
  16489. })(BABYLON || (BABYLON = {}));
  16490. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  16491. (function (BABYLON) {
  16492. var Animatable = (function () {
  16493. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  16494. if (fromFrame === void 0) { fromFrame = 0; }
  16495. if (toFrame === void 0) { toFrame = 100; }
  16496. if (loopAnimation === void 0) { loopAnimation = false; }
  16497. if (speedRatio === void 0) { speedRatio = 1.0; }
  16498. this.target = target;
  16499. this.fromFrame = fromFrame;
  16500. this.toFrame = toFrame;
  16501. this.loopAnimation = loopAnimation;
  16502. this.speedRatio = speedRatio;
  16503. this.onAnimationEnd = onAnimationEnd;
  16504. this._animations = new Array();
  16505. this._paused = false;
  16506. this.animationStarted = false;
  16507. if (animations) {
  16508. this.appendAnimations(target, animations);
  16509. }
  16510. this._scene = scene;
  16511. scene._activeAnimatables.push(this);
  16512. }
  16513. // Methods
  16514. Animatable.prototype.appendAnimations = function (target, animations) {
  16515. for (var index = 0; index < animations.length; index++) {
  16516. var animation = animations[index];
  16517. animation._target = target;
  16518. this._animations.push(animation);
  16519. }
  16520. };
  16521. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  16522. var animations = this._animations;
  16523. for (var index = 0; index < animations.length; index++) {
  16524. if (animations[index].targetProperty === property) {
  16525. return animations[index];
  16526. }
  16527. }
  16528. return null;
  16529. };
  16530. Animatable.prototype.pause = function () {
  16531. if (this._paused) {
  16532. return;
  16533. }
  16534. this._paused = true;
  16535. };
  16536. Animatable.prototype.restart = function () {
  16537. this._paused = false;
  16538. };
  16539. Animatable.prototype.stop = function () {
  16540. var index = this._scene._activeAnimatables.indexOf(this);
  16541. if (index > -1) {
  16542. this._scene._activeAnimatables.splice(index, 1);
  16543. }
  16544. if (this.onAnimationEnd) {
  16545. this.onAnimationEnd();
  16546. }
  16547. };
  16548. Animatable.prototype._animate = function (delay) {
  16549. if (this._paused) {
  16550. if (!this._pausedDelay) {
  16551. this._pausedDelay = delay;
  16552. }
  16553. return true;
  16554. }
  16555. if (!this._localDelayOffset) {
  16556. this._localDelayOffset = delay;
  16557. }
  16558. else if (this._pausedDelay) {
  16559. this._localDelayOffset += delay - this._pausedDelay;
  16560. this._pausedDelay = null;
  16561. }
  16562. // Animating
  16563. var running = false;
  16564. var animations = this._animations;
  16565. for (var index = 0; index < animations.length; index++) {
  16566. var animation = animations[index];
  16567. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  16568. running = running || isRunning;
  16569. }
  16570. if (!running) {
  16571. // Remove from active animatables
  16572. index = this._scene._activeAnimatables.indexOf(this);
  16573. this._scene._activeAnimatables.splice(index, 1);
  16574. }
  16575. if (!running && this.onAnimationEnd) {
  16576. this.onAnimationEnd();
  16577. }
  16578. return running;
  16579. };
  16580. return Animatable;
  16581. })();
  16582. BABYLON.Animatable = Animatable;
  16583. })(BABYLON || (BABYLON = {}));
  16584. //# sourceMappingURL=babylon.animatable.js.map
  16585. var BABYLON;
  16586. (function (BABYLON) {
  16587. var EasingFunction = (function () {
  16588. function EasingFunction() {
  16589. // Properties
  16590. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  16591. }
  16592. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  16593. get: function () {
  16594. return EasingFunction._EASINGMODE_EASEIN;
  16595. },
  16596. enumerable: true,
  16597. configurable: true
  16598. });
  16599. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  16600. get: function () {
  16601. return EasingFunction._EASINGMODE_EASEOUT;
  16602. },
  16603. enumerable: true,
  16604. configurable: true
  16605. });
  16606. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  16607. get: function () {
  16608. return EasingFunction._EASINGMODE_EASEINOUT;
  16609. },
  16610. enumerable: true,
  16611. configurable: true
  16612. });
  16613. EasingFunction.prototype.setEasingMode = function (easingMode) {
  16614. var n = Math.min(Math.max(easingMode, 0), 2);
  16615. this._easingMode = n;
  16616. };
  16617. EasingFunction.prototype.getEasingMode = function () {
  16618. return this._easingMode;
  16619. };
  16620. EasingFunction.prototype.easeInCore = function (gradient) {
  16621. throw new Error('You must implement this method');
  16622. };
  16623. EasingFunction.prototype.ease = function (gradient) {
  16624. switch (this._easingMode) {
  16625. case EasingFunction.EASINGMODE_EASEIN:
  16626. return this.easeInCore(gradient);
  16627. case EasingFunction.EASINGMODE_EASEOUT:
  16628. return (1 - this.easeInCore(1 - gradient));
  16629. }
  16630. if (gradient >= 0.5) {
  16631. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  16632. }
  16633. return (this.easeInCore(gradient * 2) * 0.5);
  16634. };
  16635. //Statics
  16636. EasingFunction._EASINGMODE_EASEIN = 0;
  16637. EasingFunction._EASINGMODE_EASEOUT = 1;
  16638. EasingFunction._EASINGMODE_EASEINOUT = 2;
  16639. return EasingFunction;
  16640. })();
  16641. BABYLON.EasingFunction = EasingFunction;
  16642. var CircleEase = (function (_super) {
  16643. __extends(CircleEase, _super);
  16644. function CircleEase() {
  16645. _super.apply(this, arguments);
  16646. }
  16647. CircleEase.prototype.easeInCore = function (gradient) {
  16648. gradient = Math.max(0, Math.min(1, gradient));
  16649. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  16650. };
  16651. return CircleEase;
  16652. })(EasingFunction);
  16653. BABYLON.CircleEase = CircleEase;
  16654. var BackEase = (function (_super) {
  16655. __extends(BackEase, _super);
  16656. function BackEase(amplitude) {
  16657. if (amplitude === void 0) { amplitude = 1; }
  16658. _super.call(this);
  16659. this.amplitude = amplitude;
  16660. }
  16661. BackEase.prototype.easeInCore = function (gradient) {
  16662. var num = Math.max(0, this.amplitude);
  16663. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  16664. };
  16665. return BackEase;
  16666. })(EasingFunction);
  16667. BABYLON.BackEase = BackEase;
  16668. var BounceEase = (function (_super) {
  16669. __extends(BounceEase, _super);
  16670. function BounceEase(bounces, bounciness) {
  16671. if (bounces === void 0) { bounces = 3; }
  16672. if (bounciness === void 0) { bounciness = 2; }
  16673. _super.call(this);
  16674. this.bounces = bounces;
  16675. this.bounciness = bounciness;
  16676. }
  16677. BounceEase.prototype.easeInCore = function (gradient) {
  16678. var y = Math.max(0.0, this.bounces);
  16679. var bounciness = this.bounciness;
  16680. if (bounciness <= 1.0) {
  16681. bounciness = 1.001;
  16682. }
  16683. var num9 = Math.pow(bounciness, y);
  16684. var num5 = 1.0 - bounciness;
  16685. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  16686. var num15 = gradient * num4;
  16687. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  16688. var num3 = Math.floor(num65);
  16689. var num13 = num3 + 1.0;
  16690. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  16691. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  16692. var num7 = (num8 + num12) * 0.5;
  16693. var num6 = gradient - num7;
  16694. var num2 = num7 - num8;
  16695. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  16696. };
  16697. return BounceEase;
  16698. })(EasingFunction);
  16699. BABYLON.BounceEase = BounceEase;
  16700. var CubicEase = (function (_super) {
  16701. __extends(CubicEase, _super);
  16702. function CubicEase() {
  16703. _super.apply(this, arguments);
  16704. }
  16705. CubicEase.prototype.easeInCore = function (gradient) {
  16706. return (gradient * gradient * gradient);
  16707. };
  16708. return CubicEase;
  16709. })(EasingFunction);
  16710. BABYLON.CubicEase = CubicEase;
  16711. var ElasticEase = (function (_super) {
  16712. __extends(ElasticEase, _super);
  16713. function ElasticEase(oscillations, springiness) {
  16714. if (oscillations === void 0) { oscillations = 3; }
  16715. if (springiness === void 0) { springiness = 3; }
  16716. _super.call(this);
  16717. this.oscillations = oscillations;
  16718. this.springiness = springiness;
  16719. }
  16720. ElasticEase.prototype.easeInCore = function (gradient) {
  16721. var num2;
  16722. var num3 = Math.max(0.0, this.oscillations);
  16723. var num = Math.max(0.0, this.springiness);
  16724. if (num == 0) {
  16725. num2 = gradient;
  16726. }
  16727. else {
  16728. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  16729. }
  16730. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  16731. };
  16732. return ElasticEase;
  16733. })(EasingFunction);
  16734. BABYLON.ElasticEase = ElasticEase;
  16735. var ExponentialEase = (function (_super) {
  16736. __extends(ExponentialEase, _super);
  16737. function ExponentialEase(exponent) {
  16738. if (exponent === void 0) { exponent = 2; }
  16739. _super.call(this);
  16740. this.exponent = exponent;
  16741. }
  16742. ExponentialEase.prototype.easeInCore = function (gradient) {
  16743. if (this.exponent <= 0) {
  16744. return gradient;
  16745. }
  16746. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  16747. };
  16748. return ExponentialEase;
  16749. })(EasingFunction);
  16750. BABYLON.ExponentialEase = ExponentialEase;
  16751. var PowerEase = (function (_super) {
  16752. __extends(PowerEase, _super);
  16753. function PowerEase(power) {
  16754. if (power === void 0) { power = 2; }
  16755. _super.call(this);
  16756. this.power = power;
  16757. }
  16758. PowerEase.prototype.easeInCore = function (gradient) {
  16759. var y = Math.max(0.0, this.power);
  16760. return Math.pow(gradient, y);
  16761. };
  16762. return PowerEase;
  16763. })(EasingFunction);
  16764. BABYLON.PowerEase = PowerEase;
  16765. var QuadraticEase = (function (_super) {
  16766. __extends(QuadraticEase, _super);
  16767. function QuadraticEase() {
  16768. _super.apply(this, arguments);
  16769. }
  16770. QuadraticEase.prototype.easeInCore = function (gradient) {
  16771. return (gradient * gradient);
  16772. };
  16773. return QuadraticEase;
  16774. })(EasingFunction);
  16775. BABYLON.QuadraticEase = QuadraticEase;
  16776. var QuarticEase = (function (_super) {
  16777. __extends(QuarticEase, _super);
  16778. function QuarticEase() {
  16779. _super.apply(this, arguments);
  16780. }
  16781. QuarticEase.prototype.easeInCore = function (gradient) {
  16782. return (gradient * gradient * gradient * gradient);
  16783. };
  16784. return QuarticEase;
  16785. })(EasingFunction);
  16786. BABYLON.QuarticEase = QuarticEase;
  16787. var QuinticEase = (function (_super) {
  16788. __extends(QuinticEase, _super);
  16789. function QuinticEase() {
  16790. _super.apply(this, arguments);
  16791. }
  16792. QuinticEase.prototype.easeInCore = function (gradient) {
  16793. return (gradient * gradient * gradient * gradient * gradient);
  16794. };
  16795. return QuinticEase;
  16796. })(EasingFunction);
  16797. BABYLON.QuinticEase = QuinticEase;
  16798. var SineEase = (function (_super) {
  16799. __extends(SineEase, _super);
  16800. function SineEase() {
  16801. _super.apply(this, arguments);
  16802. }
  16803. SineEase.prototype.easeInCore = function (gradient) {
  16804. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  16805. };
  16806. return SineEase;
  16807. })(EasingFunction);
  16808. BABYLON.SineEase = SineEase;
  16809. var BezierCurveEase = (function (_super) {
  16810. __extends(BezierCurveEase, _super);
  16811. function BezierCurveEase(x1, y1, x2, y2) {
  16812. if (x1 === void 0) { x1 = 0; }
  16813. if (y1 === void 0) { y1 = 0; }
  16814. if (x2 === void 0) { x2 = 1; }
  16815. if (y2 === void 0) { y2 = 1; }
  16816. _super.call(this);
  16817. this.x1 = x1;
  16818. this.y1 = y1;
  16819. this.x2 = x2;
  16820. this.y2 = y2;
  16821. }
  16822. BezierCurveEase.prototype.easeInCore = function (gradient) {
  16823. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  16824. };
  16825. return BezierCurveEase;
  16826. })(EasingFunction);
  16827. BABYLON.BezierCurveEase = BezierCurveEase;
  16828. })(BABYLON || (BABYLON = {}));
  16829. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  16830. (function (BABYLON) {
  16831. var Octree = (function () {
  16832. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  16833. if (maxDepth === void 0) { maxDepth = 2; }
  16834. this.maxDepth = maxDepth;
  16835. this.dynamicContent = new Array();
  16836. this._maxBlockCapacity = maxBlockCapacity || 64;
  16837. this._selectionContent = new BABYLON.SmartArray(1024);
  16838. this._creationFunc = creationFunc;
  16839. }
  16840. // Methods
  16841. Octree.prototype.update = function (worldMin, worldMax, entries) {
  16842. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  16843. };
  16844. Octree.prototype.addMesh = function (entry) {
  16845. for (var index = 0; index < this.blocks.length; index++) {
  16846. var block = this.blocks[index];
  16847. block.addEntry(entry);
  16848. }
  16849. };
  16850. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  16851. this._selectionContent.reset();
  16852. for (var index = 0; index < this.blocks.length; index++) {
  16853. var block = this.blocks[index];
  16854. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  16855. }
  16856. if (allowDuplicate) {
  16857. this._selectionContent.concat(this.dynamicContent);
  16858. }
  16859. else {
  16860. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16861. }
  16862. return this._selectionContent;
  16863. };
  16864. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  16865. this._selectionContent.reset();
  16866. for (var index = 0; index < this.blocks.length; index++) {
  16867. var block = this.blocks[index];
  16868. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  16869. }
  16870. if (allowDuplicate) {
  16871. this._selectionContent.concat(this.dynamicContent);
  16872. }
  16873. else {
  16874. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16875. }
  16876. return this._selectionContent;
  16877. };
  16878. Octree.prototype.intersectsRay = function (ray) {
  16879. this._selectionContent.reset();
  16880. for (var index = 0; index < this.blocks.length; index++) {
  16881. var block = this.blocks[index];
  16882. block.intersectsRay(ray, this._selectionContent);
  16883. }
  16884. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16885. return this._selectionContent;
  16886. };
  16887. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  16888. target.blocks = new Array();
  16889. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  16890. for (var x = 0; x < 2; x++) {
  16891. for (var y = 0; y < 2; y++) {
  16892. for (var z = 0; z < 2; z++) {
  16893. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  16894. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  16895. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  16896. block.addEntries(entries);
  16897. target.blocks.push(block);
  16898. }
  16899. }
  16900. }
  16901. };
  16902. Octree.CreationFuncForMeshes = function (entry, block) {
  16903. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16904. block.entries.push(entry);
  16905. }
  16906. };
  16907. Octree.CreationFuncForSubMeshes = function (entry, block) {
  16908. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16909. block.entries.push(entry);
  16910. }
  16911. };
  16912. return Octree;
  16913. })();
  16914. BABYLON.Octree = Octree;
  16915. })(BABYLON || (BABYLON = {}));
  16916. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  16917. (function (BABYLON) {
  16918. var OctreeBlock = (function () {
  16919. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  16920. this.entries = new Array();
  16921. this._boundingVectors = new Array();
  16922. this._capacity = capacity;
  16923. this._depth = depth;
  16924. this._maxDepth = maxDepth;
  16925. this._creationFunc = creationFunc;
  16926. this._minPoint = minPoint;
  16927. this._maxPoint = maxPoint;
  16928. this._boundingVectors.push(minPoint.clone());
  16929. this._boundingVectors.push(maxPoint.clone());
  16930. this._boundingVectors.push(minPoint.clone());
  16931. this._boundingVectors[2].x = maxPoint.x;
  16932. this._boundingVectors.push(minPoint.clone());
  16933. this._boundingVectors[3].y = maxPoint.y;
  16934. this._boundingVectors.push(minPoint.clone());
  16935. this._boundingVectors[4].z = maxPoint.z;
  16936. this._boundingVectors.push(maxPoint.clone());
  16937. this._boundingVectors[5].z = minPoint.z;
  16938. this._boundingVectors.push(maxPoint.clone());
  16939. this._boundingVectors[6].x = minPoint.x;
  16940. this._boundingVectors.push(maxPoint.clone());
  16941. this._boundingVectors[7].y = minPoint.y;
  16942. }
  16943. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  16944. // Property
  16945. get: function () {
  16946. return this._capacity;
  16947. },
  16948. enumerable: true,
  16949. configurable: true
  16950. });
  16951. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  16952. get: function () {
  16953. return this._minPoint;
  16954. },
  16955. enumerable: true,
  16956. configurable: true
  16957. });
  16958. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  16959. get: function () {
  16960. return this._maxPoint;
  16961. },
  16962. enumerable: true,
  16963. configurable: true
  16964. });
  16965. // Methods
  16966. OctreeBlock.prototype.addEntry = function (entry) {
  16967. if (this.blocks) {
  16968. for (var index = 0; index < this.blocks.length; index++) {
  16969. var block = this.blocks[index];
  16970. block.addEntry(entry);
  16971. }
  16972. return;
  16973. }
  16974. this._creationFunc(entry, this);
  16975. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  16976. this.createInnerBlocks();
  16977. }
  16978. };
  16979. OctreeBlock.prototype.addEntries = function (entries) {
  16980. for (var index = 0; index < entries.length; index++) {
  16981. var mesh = entries[index];
  16982. this.addEntry(mesh);
  16983. }
  16984. };
  16985. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  16986. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  16987. if (this.blocks) {
  16988. for (var index = 0; index < this.blocks.length; index++) {
  16989. var block = this.blocks[index];
  16990. block.select(frustumPlanes, selection, allowDuplicate);
  16991. }
  16992. return;
  16993. }
  16994. if (allowDuplicate) {
  16995. selection.concat(this.entries);
  16996. }
  16997. else {
  16998. selection.concatWithNoDuplicate(this.entries);
  16999. }
  17000. }
  17001. };
  17002. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  17003. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  17004. if (this.blocks) {
  17005. for (var index = 0; index < this.blocks.length; index++) {
  17006. var block = this.blocks[index];
  17007. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  17008. }
  17009. return;
  17010. }
  17011. if (allowDuplicate) {
  17012. selection.concat(this.entries);
  17013. }
  17014. else {
  17015. selection.concatWithNoDuplicate(this.entries);
  17016. }
  17017. }
  17018. };
  17019. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  17020. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  17021. if (this.blocks) {
  17022. for (var index = 0; index < this.blocks.length; index++) {
  17023. var block = this.blocks[index];
  17024. block.intersectsRay(ray, selection);
  17025. }
  17026. return;
  17027. }
  17028. selection.concatWithNoDuplicate(this.entries);
  17029. }
  17030. };
  17031. OctreeBlock.prototype.createInnerBlocks = function () {
  17032. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  17033. };
  17034. return OctreeBlock;
  17035. })();
  17036. BABYLON.OctreeBlock = OctreeBlock;
  17037. })(BABYLON || (BABYLON = {}));
  17038. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  17039. (function (BABYLON) {
  17040. var Bone = (function () {
  17041. function Bone(name, skeleton, parentBone, matrix) {
  17042. this.name = name;
  17043. this.children = new Array();
  17044. this.animations = new Array();
  17045. this._worldTransform = new BABYLON.Matrix();
  17046. this._absoluteTransform = new BABYLON.Matrix();
  17047. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  17048. this._skeleton = skeleton;
  17049. this._matrix = matrix;
  17050. this._baseMatrix = matrix;
  17051. skeleton.bones.push(this);
  17052. if (parentBone) {
  17053. this._parent = parentBone;
  17054. parentBone.children.push(this);
  17055. }
  17056. else {
  17057. this._parent = null;
  17058. }
  17059. this._updateDifferenceMatrix();
  17060. }
  17061. // Members
  17062. Bone.prototype.getParent = function () {
  17063. return this._parent;
  17064. };
  17065. Bone.prototype.getLocalMatrix = function () {
  17066. return this._matrix;
  17067. };
  17068. Bone.prototype.getBaseMatrix = function () {
  17069. return this._baseMatrix;
  17070. };
  17071. Bone.prototype.getWorldMatrix = function () {
  17072. return this._worldTransform;
  17073. };
  17074. Bone.prototype.getInvertedAbsoluteTransform = function () {
  17075. return this._invertedAbsoluteTransform;
  17076. };
  17077. Bone.prototype.getAbsoluteMatrix = function () {
  17078. var matrix = this._matrix.clone();
  17079. var parent = this._parent;
  17080. while (parent) {
  17081. matrix = matrix.multiply(parent.getLocalMatrix());
  17082. parent = parent.getParent();
  17083. }
  17084. return matrix;
  17085. };
  17086. // Methods
  17087. Bone.prototype.updateMatrix = function (matrix) {
  17088. this._matrix = matrix;
  17089. this._skeleton._markAsDirty();
  17090. this._updateDifferenceMatrix();
  17091. };
  17092. Bone.prototype._updateDifferenceMatrix = function () {
  17093. if (this._parent) {
  17094. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  17095. }
  17096. else {
  17097. this._absoluteTransform.copyFrom(this._matrix);
  17098. }
  17099. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  17100. for (var index = 0; index < this.children.length; index++) {
  17101. this.children[index]._updateDifferenceMatrix();
  17102. }
  17103. };
  17104. Bone.prototype.markAsDirty = function () {
  17105. this._skeleton._markAsDirty();
  17106. };
  17107. return Bone;
  17108. })();
  17109. BABYLON.Bone = Bone;
  17110. })(BABYLON || (BABYLON = {}));
  17111. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  17112. (function (BABYLON) {
  17113. var Skeleton = (function () {
  17114. function Skeleton(name, id, scene) {
  17115. this.name = name;
  17116. this.id = id;
  17117. this.bones = new Array();
  17118. this._isDirty = true;
  17119. this._identity = BABYLON.Matrix.Identity();
  17120. this.bones = [];
  17121. this._scene = scene;
  17122. scene.skeletons.push(this);
  17123. }
  17124. // Members
  17125. Skeleton.prototype.getTransformMatrices = function () {
  17126. return this._transformMatrices;
  17127. };
  17128. // Methods
  17129. Skeleton.prototype._markAsDirty = function () {
  17130. this._isDirty = true;
  17131. };
  17132. Skeleton.prototype.prepare = function () {
  17133. if (!this._isDirty) {
  17134. return;
  17135. }
  17136. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  17137. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  17138. }
  17139. for (var index = 0; index < this.bones.length; index++) {
  17140. var bone = this.bones[index];
  17141. var parentBone = bone.getParent();
  17142. if (parentBone) {
  17143. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  17144. }
  17145. else {
  17146. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  17147. }
  17148. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  17149. }
  17150. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  17151. this._isDirty = false;
  17152. this._scene._activeBones += this.bones.length;
  17153. };
  17154. Skeleton.prototype.getAnimatables = function () {
  17155. if (!this._animatables || this._animatables.length !== this.bones.length) {
  17156. this._animatables = [];
  17157. for (var index = 0; index < this.bones.length; index++) {
  17158. this._animatables.push(this.bones[index]);
  17159. }
  17160. }
  17161. return this._animatables;
  17162. };
  17163. Skeleton.prototype.clone = function (name, id) {
  17164. var result = new Skeleton(name, id || name, this._scene);
  17165. for (var index = 0; index < this.bones.length; index++) {
  17166. var source = this.bones[index];
  17167. var parentBone = null;
  17168. if (source.getParent()) {
  17169. var parentIndex = this.bones.indexOf(source.getParent());
  17170. parentBone = result.bones[parentIndex];
  17171. }
  17172. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  17173. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  17174. }
  17175. return result;
  17176. };
  17177. return Skeleton;
  17178. })();
  17179. BABYLON.Skeleton = Skeleton;
  17180. })(BABYLON || (BABYLON = {}));
  17181. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  17182. (function (BABYLON) {
  17183. var PostProcess = (function () {
  17184. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  17185. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  17186. this.name = name;
  17187. this.width = -1;
  17188. this.height = -1;
  17189. this._reusable = false;
  17190. this._textures = new BABYLON.SmartArray(2);
  17191. this._currentRenderTextureInd = 0;
  17192. if (camera != null) {
  17193. this._camera = camera;
  17194. this._scene = camera.getScene();
  17195. camera.attachPostProcess(this);
  17196. this._engine = this._scene.getEngine();
  17197. }
  17198. else {
  17199. this._engine = engine;
  17200. }
  17201. this._renderRatio = ratio;
  17202. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  17203. this._reusable = reusable || false;
  17204. samplers = samplers || [];
  17205. samplers.push("textureSampler");
  17206. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  17207. }
  17208. PostProcess.prototype.isReusable = function () {
  17209. return this._reusable;
  17210. };
  17211. PostProcess.prototype.activate = function (camera, sourceTexture) {
  17212. camera = camera || this._camera;
  17213. var scene = camera.getScene();
  17214. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  17215. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  17216. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  17217. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  17218. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  17219. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  17220. if (this._textures.length > 0) {
  17221. for (var i = 0; i < this._textures.length; i++) {
  17222. this._engine._releaseTexture(this._textures.data[i]);
  17223. }
  17224. this._textures.reset();
  17225. }
  17226. this.width = desiredWidth;
  17227. this.height = desiredHeight;
  17228. 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 }));
  17229. if (this._reusable) {
  17230. 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 }));
  17231. }
  17232. if (this.onSizeChanged) {
  17233. this.onSizeChanged();
  17234. }
  17235. }
  17236. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  17237. if (this.onActivate) {
  17238. this.onActivate(camera);
  17239. }
  17240. // Clear
  17241. if (this.clearColor) {
  17242. this._engine.clear(this.clearColor, true, true);
  17243. }
  17244. else {
  17245. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  17246. }
  17247. if (this._reusable) {
  17248. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  17249. }
  17250. };
  17251. PostProcess.prototype.apply = function () {
  17252. // Check
  17253. if (!this._effect.isReady())
  17254. return null;
  17255. // States
  17256. this._engine.enableEffect(this._effect);
  17257. this._engine.setState(false);
  17258. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17259. this._engine.setDepthBuffer(false);
  17260. this._engine.setDepthWrite(false);
  17261. // Texture
  17262. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  17263. // Parameters
  17264. if (this.onApply) {
  17265. this.onApply(this._effect);
  17266. }
  17267. return this._effect;
  17268. };
  17269. PostProcess.prototype.dispose = function (camera) {
  17270. camera = camera || this._camera;
  17271. if (this._textures.length > 0) {
  17272. for (var i = 0; i < this._textures.length; i++) {
  17273. this._engine._releaseTexture(this._textures.data[i]);
  17274. }
  17275. this._textures.reset();
  17276. }
  17277. if (!camera) {
  17278. return;
  17279. }
  17280. camera.detachPostProcess(this);
  17281. var index = camera._postProcesses.indexOf(this);
  17282. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  17283. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  17284. }
  17285. };
  17286. return PostProcess;
  17287. })();
  17288. BABYLON.PostProcess = PostProcess;
  17289. })(BABYLON || (BABYLON = {}));
  17290. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  17291. (function (BABYLON) {
  17292. var PostProcessManager = (function () {
  17293. function PostProcessManager(scene) {
  17294. this._vertexDeclaration = [2];
  17295. this._vertexStrideSize = 2 * 4;
  17296. this._scene = scene;
  17297. // VBO
  17298. var vertices = [];
  17299. vertices.push(1, 1);
  17300. vertices.push(-1, 1);
  17301. vertices.push(-1, -1);
  17302. vertices.push(1, -1);
  17303. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17304. // Indices
  17305. var indices = [];
  17306. indices.push(0);
  17307. indices.push(1);
  17308. indices.push(2);
  17309. indices.push(0);
  17310. indices.push(2);
  17311. indices.push(3);
  17312. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17313. }
  17314. // Methods
  17315. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  17316. var postProcesses = this._scene.activeCamera._postProcesses;
  17317. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17318. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17319. return false;
  17320. }
  17321. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  17322. return true;
  17323. };
  17324. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  17325. var engine = this._scene.getEngine();
  17326. for (var index = 0; index < postProcesses.length; index++) {
  17327. if (index < postProcesses.length - 1) {
  17328. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  17329. }
  17330. else {
  17331. if (targetTexture) {
  17332. engine.bindFramebuffer(targetTexture);
  17333. }
  17334. else {
  17335. engine.restoreDefaultFramebuffer();
  17336. }
  17337. }
  17338. var pp = postProcesses[index];
  17339. var effect = pp.apply();
  17340. if (effect) {
  17341. if (pp.onBeforeRender) {
  17342. pp.onBeforeRender(effect);
  17343. }
  17344. // VBOs
  17345. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17346. // Draw order
  17347. engine.draw(true, 0, 6);
  17348. }
  17349. }
  17350. // Restore depth buffer
  17351. engine.setDepthBuffer(true);
  17352. engine.setDepthWrite(true);
  17353. };
  17354. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  17355. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  17356. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17357. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17358. return;
  17359. }
  17360. var engine = this._scene.getEngine();
  17361. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  17362. if (index < postProcessesTakenIndices.length - 1) {
  17363. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  17364. }
  17365. else {
  17366. if (targetTexture) {
  17367. engine.bindFramebuffer(targetTexture);
  17368. }
  17369. else {
  17370. engine.restoreDefaultFramebuffer();
  17371. }
  17372. }
  17373. if (doNotPresent) {
  17374. break;
  17375. }
  17376. var pp = postProcesses[postProcessesTakenIndices[index]];
  17377. var effect = pp.apply();
  17378. if (effect) {
  17379. if (pp.onBeforeRender) {
  17380. pp.onBeforeRender(effect);
  17381. }
  17382. // VBOs
  17383. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17384. // Draw order
  17385. engine.draw(true, 0, 6);
  17386. }
  17387. }
  17388. // Restore depth buffer
  17389. engine.setDepthBuffer(true);
  17390. engine.setDepthWrite(true);
  17391. };
  17392. PostProcessManager.prototype.dispose = function () {
  17393. if (this._vertexBuffer) {
  17394. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17395. this._vertexBuffer = null;
  17396. }
  17397. if (this._indexBuffer) {
  17398. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17399. this._indexBuffer = null;
  17400. }
  17401. };
  17402. return PostProcessManager;
  17403. })();
  17404. BABYLON.PostProcessManager = PostProcessManager;
  17405. })(BABYLON || (BABYLON = {}));
  17406. //# sourceMappingURL=babylon.postProcessManager.js.map
  17407. var BABYLON;
  17408. (function (BABYLON) {
  17409. var PassPostProcess = (function (_super) {
  17410. __extends(PassPostProcess, _super);
  17411. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17412. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  17413. }
  17414. return PassPostProcess;
  17415. })(BABYLON.PostProcess);
  17416. BABYLON.PassPostProcess = PassPostProcess;
  17417. })(BABYLON || (BABYLON = {}));
  17418. //# sourceMappingURL=babylon.passPostProcess.js.map
  17419. var BABYLON;
  17420. (function (BABYLON) {
  17421. var BlurPostProcess = (function (_super) {
  17422. __extends(BlurPostProcess, _super);
  17423. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  17424. var _this = this;
  17425. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  17426. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  17427. this.direction = direction;
  17428. this.blurWidth = blurWidth;
  17429. this.onApply = function (effect) {
  17430. effect.setFloat2("screenSize", _this.width, _this.height);
  17431. effect.setVector2("direction", _this.direction);
  17432. effect.setFloat("blurWidth", _this.blurWidth);
  17433. };
  17434. }
  17435. return BlurPostProcess;
  17436. })(BABYLON.PostProcess);
  17437. BABYLON.BlurPostProcess = BlurPostProcess;
  17438. })(BABYLON || (BABYLON = {}));
  17439. //# sourceMappingURL=babylon.blurPostProcess.js.map
  17440. var BABYLON;
  17441. (function (BABYLON) {
  17442. var FilterPostProcess = (function (_super) {
  17443. __extends(FilterPostProcess, _super);
  17444. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  17445. var _this = this;
  17446. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  17447. this.kernelMatrix = kernelMatrix;
  17448. this.onApply = function (effect) {
  17449. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  17450. };
  17451. }
  17452. return FilterPostProcess;
  17453. })(BABYLON.PostProcess);
  17454. BABYLON.FilterPostProcess = FilterPostProcess;
  17455. })(BABYLON || (BABYLON = {}));
  17456. //# sourceMappingURL=babylon.filterPostProcess.js.map
  17457. var BABYLON;
  17458. (function (BABYLON) {
  17459. var RefractionPostProcess = (function (_super) {
  17460. __extends(RefractionPostProcess, _super);
  17461. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  17462. var _this = this;
  17463. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  17464. this.color = color;
  17465. this.depth = depth;
  17466. this.colorLevel = colorLevel;
  17467. this.onActivate = function (cam) {
  17468. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  17469. };
  17470. this.onApply = function (effect) {
  17471. effect.setColor3("baseColor", _this.color);
  17472. effect.setFloat("depth", _this.depth);
  17473. effect.setFloat("colorLevel", _this.colorLevel);
  17474. effect.setTexture("refractionSampler", _this._refRexture);
  17475. };
  17476. }
  17477. // Methods
  17478. RefractionPostProcess.prototype.dispose = function (camera) {
  17479. if (this._refRexture) {
  17480. this._refRexture.dispose();
  17481. }
  17482. _super.prototype.dispose.call(this, camera);
  17483. };
  17484. return RefractionPostProcess;
  17485. })(BABYLON.PostProcess);
  17486. BABYLON.RefractionPostProcess = RefractionPostProcess;
  17487. })(BABYLON || (BABYLON = {}));
  17488. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  17489. var BABYLON;
  17490. (function (BABYLON) {
  17491. var BlackAndWhitePostProcess = (function (_super) {
  17492. __extends(BlackAndWhitePostProcess, _super);
  17493. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17494. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  17495. }
  17496. return BlackAndWhitePostProcess;
  17497. })(BABYLON.PostProcess);
  17498. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  17499. })(BABYLON || (BABYLON = {}));
  17500. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  17501. var BABYLON;
  17502. (function (BABYLON) {
  17503. var ConvolutionPostProcess = (function (_super) {
  17504. __extends(ConvolutionPostProcess, _super);
  17505. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  17506. var _this = this;
  17507. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  17508. this.kernel = kernel;
  17509. this.onApply = function (effect) {
  17510. effect.setFloat2("screenSize", _this.width, _this.height);
  17511. effect.setArray("kernel", _this.kernel);
  17512. };
  17513. }
  17514. // Statics
  17515. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  17516. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  17517. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  17518. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  17519. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  17520. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  17521. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  17522. return ConvolutionPostProcess;
  17523. })(BABYLON.PostProcess);
  17524. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  17525. })(BABYLON || (BABYLON = {}));
  17526. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  17527. var BABYLON;
  17528. (function (BABYLON) {
  17529. var FxaaPostProcess = (function (_super) {
  17530. __extends(FxaaPostProcess, _super);
  17531. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17532. var _this = this;
  17533. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  17534. this.onSizeChanged = function () {
  17535. _this.texelWidth = 1.0 / _this.width;
  17536. _this.texelHeight = 1.0 / _this.height;
  17537. };
  17538. this.onApply = function (effect) {
  17539. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  17540. };
  17541. }
  17542. return FxaaPostProcess;
  17543. })(BABYLON.PostProcess);
  17544. BABYLON.FxaaPostProcess = FxaaPostProcess;
  17545. })(BABYLON || (BABYLON = {}));
  17546. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  17547. (function (BABYLON) {
  17548. var LensFlare = (function () {
  17549. function LensFlare(size, position, color, imgUrl, system) {
  17550. this.size = size;
  17551. this.position = position;
  17552. this.dispose = function () {
  17553. if (this.texture) {
  17554. this.texture.dispose();
  17555. }
  17556. // Remove from scene
  17557. var index = this._system.lensFlares.indexOf(this);
  17558. this._system.lensFlares.splice(index, 1);
  17559. };
  17560. this.color = color || new BABYLON.Color3(1, 1, 1);
  17561. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  17562. this._system = system;
  17563. system.lensFlares.push(this);
  17564. }
  17565. return LensFlare;
  17566. })();
  17567. BABYLON.LensFlare = LensFlare;
  17568. })(BABYLON || (BABYLON = {}));
  17569. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  17570. (function (BABYLON) {
  17571. var LensFlareSystem = (function () {
  17572. function LensFlareSystem(name, emitter, scene) {
  17573. this.name = name;
  17574. this.lensFlares = new Array();
  17575. this.borderLimit = 300;
  17576. this._vertexDeclaration = [2];
  17577. this._vertexStrideSize = 2 * 4;
  17578. this._isEnabled = true;
  17579. this._scene = scene;
  17580. this._emitter = emitter;
  17581. scene.lensFlareSystems.push(this);
  17582. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  17583. // VBO
  17584. var vertices = [];
  17585. vertices.push(1, 1);
  17586. vertices.push(-1, 1);
  17587. vertices.push(-1, -1);
  17588. vertices.push(1, -1);
  17589. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17590. // Indices
  17591. var indices = [];
  17592. indices.push(0);
  17593. indices.push(1);
  17594. indices.push(2);
  17595. indices.push(0);
  17596. indices.push(2);
  17597. indices.push(3);
  17598. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17599. // Effects
  17600. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  17601. }
  17602. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  17603. get: function () {
  17604. return this._isEnabled;
  17605. },
  17606. set: function (value) {
  17607. this._isEnabled = value;
  17608. },
  17609. enumerable: true,
  17610. configurable: true
  17611. });
  17612. LensFlareSystem.prototype.getScene = function () {
  17613. return this._scene;
  17614. };
  17615. LensFlareSystem.prototype.getEmitter = function () {
  17616. return this._emitter;
  17617. };
  17618. LensFlareSystem.prototype.getEmitterPosition = function () {
  17619. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  17620. };
  17621. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  17622. var position = this.getEmitterPosition();
  17623. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  17624. this._positionX = position.x;
  17625. this._positionY = position.y;
  17626. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  17627. if (position.z > 0) {
  17628. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  17629. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  17630. return true;
  17631. }
  17632. }
  17633. return false;
  17634. };
  17635. LensFlareSystem.prototype._isVisible = function () {
  17636. if (!this._isEnabled) {
  17637. return false;
  17638. }
  17639. var emitterPosition = this.getEmitterPosition();
  17640. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  17641. var distance = direction.length();
  17642. direction.normalize();
  17643. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  17644. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  17645. return !pickInfo.hit || pickInfo.distance > distance;
  17646. };
  17647. LensFlareSystem.prototype.render = function () {
  17648. if (!this._effect.isReady())
  17649. return false;
  17650. var engine = this._scene.getEngine();
  17651. var viewport = this._scene.activeCamera.viewport;
  17652. var globalViewport = viewport.toGlobal(engine);
  17653. // Position
  17654. if (!this.computeEffectivePosition(globalViewport)) {
  17655. return false;
  17656. }
  17657. // Visibility
  17658. if (!this._isVisible()) {
  17659. return false;
  17660. }
  17661. // Intensity
  17662. var awayX;
  17663. var awayY;
  17664. if (this._positionX < this.borderLimit + globalViewport.x) {
  17665. awayX = this.borderLimit + globalViewport.x - this._positionX;
  17666. }
  17667. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  17668. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  17669. }
  17670. else {
  17671. awayX = 0;
  17672. }
  17673. if (this._positionY < this.borderLimit + globalViewport.y) {
  17674. awayY = this.borderLimit + globalViewport.y - this._positionY;
  17675. }
  17676. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  17677. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  17678. }
  17679. else {
  17680. awayY = 0;
  17681. }
  17682. var away = (awayX > awayY) ? awayX : awayY;
  17683. if (away > this.borderLimit) {
  17684. away = this.borderLimit;
  17685. }
  17686. var intensity = 1.0 - (away / this.borderLimit);
  17687. if (intensity < 0) {
  17688. return false;
  17689. }
  17690. if (intensity > 1.0) {
  17691. intensity = 1.0;
  17692. }
  17693. // Position
  17694. var centerX = globalViewport.x + globalViewport.width / 2;
  17695. var centerY = globalViewport.y + globalViewport.height / 2;
  17696. var distX = centerX - this._positionX;
  17697. var distY = centerY - this._positionY;
  17698. // Effects
  17699. engine.enableEffect(this._effect);
  17700. engine.setState(false);
  17701. engine.setDepthBuffer(false);
  17702. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  17703. // VBOs
  17704. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17705. for (var index = 0; index < this.lensFlares.length; index++) {
  17706. var flare = this.lensFlares[index];
  17707. var x = centerX - (distX * flare.position);
  17708. var y = centerY - (distY * flare.position);
  17709. var cw = flare.size;
  17710. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  17711. var cx = 2 * (x / globalViewport.width) - 1.0;
  17712. var cy = 1.0 - 2 * (y / globalViewport.height);
  17713. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  17714. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  17715. // Texture
  17716. this._effect.setTexture("textureSampler", flare.texture);
  17717. // Color
  17718. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  17719. // Draw order
  17720. engine.draw(true, 0, 6);
  17721. }
  17722. engine.setDepthBuffer(true);
  17723. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17724. return true;
  17725. };
  17726. LensFlareSystem.prototype.dispose = function () {
  17727. if (this._vertexBuffer) {
  17728. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17729. this._vertexBuffer = null;
  17730. }
  17731. if (this._indexBuffer) {
  17732. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17733. this._indexBuffer = null;
  17734. }
  17735. while (this.lensFlares.length) {
  17736. this.lensFlares[0].dispose();
  17737. }
  17738. // Remove from scene
  17739. var index = this._scene.lensFlareSystems.indexOf(this);
  17740. this._scene.lensFlareSystems.splice(index, 1);
  17741. };
  17742. return LensFlareSystem;
  17743. })();
  17744. BABYLON.LensFlareSystem = LensFlareSystem;
  17745. })(BABYLON || (BABYLON = {}));
  17746. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  17747. (function (BABYLON) {
  17748. var IntersectionInfo = (function () {
  17749. function IntersectionInfo(bu, bv, distance) {
  17750. this.bu = bu;
  17751. this.bv = bv;
  17752. this.distance = distance;
  17753. this.faceId = 0;
  17754. this.subMeshId = 0;
  17755. }
  17756. return IntersectionInfo;
  17757. })();
  17758. BABYLON.IntersectionInfo = IntersectionInfo;
  17759. var PickingInfo = (function () {
  17760. function PickingInfo() {
  17761. this.hit = false;
  17762. this.distance = 0;
  17763. this.pickedPoint = null;
  17764. this.pickedMesh = null;
  17765. this.bu = 0;
  17766. this.bv = 0;
  17767. this.faceId = -1;
  17768. this.subMeshId = 0;
  17769. }
  17770. // Methods
  17771. PickingInfo.prototype.getNormal = function () {
  17772. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17773. return null;
  17774. }
  17775. var indices = this.pickedMesh.getIndices();
  17776. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17777. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  17778. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  17779. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  17780. normal0 = normal0.scale(this.bu);
  17781. normal1 = normal1.scale(this.bv);
  17782. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  17783. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  17784. };
  17785. PickingInfo.prototype.getTextureCoordinates = function () {
  17786. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17787. return null;
  17788. }
  17789. var indices = this.pickedMesh.getIndices();
  17790. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17791. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  17792. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  17793. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  17794. uv0 = uv0.scale(this.bu);
  17795. uv1 = uv1.scale(this.bv);
  17796. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  17797. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  17798. };
  17799. return PickingInfo;
  17800. })();
  17801. BABYLON.PickingInfo = PickingInfo;
  17802. })(BABYLON || (BABYLON = {}));
  17803. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  17804. (function (BABYLON) {
  17805. var FilesInput = (function () {
  17806. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  17807. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  17808. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  17809. this._engine = p_engine;
  17810. this._canvas = p_canvas;
  17811. this._currentScene = p_scene;
  17812. this._sceneLoadedCallback = p_sceneLoadedCallback;
  17813. this._progressCallback = p_progressCallback;
  17814. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  17815. this._textureLoadingCallback = p_textureLoadingCallback;
  17816. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  17817. }
  17818. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  17819. var _this = this;
  17820. if (p_elementToMonitor) {
  17821. this._elementToMonitor = p_elementToMonitor;
  17822. this._elementToMonitor.addEventListener("dragenter", function (e) {
  17823. _this.drag(e);
  17824. }, false);
  17825. this._elementToMonitor.addEventListener("dragover", function (e) {
  17826. _this.drag(e);
  17827. }, false);
  17828. this._elementToMonitor.addEventListener("drop", function (e) {
  17829. _this.drop(e);
  17830. }, false);
  17831. }
  17832. };
  17833. FilesInput.prototype.renderFunction = function () {
  17834. if (this._additionnalRenderLoopLogicCallback) {
  17835. this._additionnalRenderLoopLogicCallback();
  17836. }
  17837. if (this._currentScene) {
  17838. if (this._textureLoadingCallback) {
  17839. var remaining = this._currentScene.getWaitingItemsCount();
  17840. if (remaining > 0) {
  17841. this._textureLoadingCallback(remaining);
  17842. }
  17843. }
  17844. this._currentScene.render();
  17845. }
  17846. };
  17847. FilesInput.prototype.drag = function (e) {
  17848. e.stopPropagation();
  17849. e.preventDefault();
  17850. };
  17851. FilesInput.prototype.drop = function (eventDrop) {
  17852. eventDrop.stopPropagation();
  17853. eventDrop.preventDefault();
  17854. this.loadFiles(eventDrop);
  17855. };
  17856. FilesInput.prototype.loadFiles = function (event) {
  17857. if (this._startingProcessingFilesCallback)
  17858. this._startingProcessingFilesCallback();
  17859. // Handling data transfer via drag'n'drop
  17860. if (event && event.dataTransfer && event.dataTransfer.files) {
  17861. this._filesToLoad = event.dataTransfer.files;
  17862. }
  17863. // Handling files from input files
  17864. if (event && event.target && event.target.files) {
  17865. this._filesToLoad = event.target.files;
  17866. }
  17867. if (this._filesToLoad && this._filesToLoad.length > 0) {
  17868. for (var i = 0; i < this._filesToLoad.length; i++) {
  17869. switch (this._filesToLoad[i].type) {
  17870. case "image/jpeg":
  17871. case "image/png":
  17872. case "image/bmp":
  17873. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  17874. break;
  17875. case "image/targa":
  17876. case "image/vnd.ms-dds":
  17877. case "audio/wav":
  17878. case "audio/x-wav":
  17879. case "audio/mp3":
  17880. case "audio/mpeg":
  17881. case "audio/mpeg3":
  17882. case "audio/x-mpeg-3":
  17883. case "audio/ogg":
  17884. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  17885. break;
  17886. default:
  17887. 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) {
  17888. this._sceneFileToLoad = this._filesToLoad[i];
  17889. }
  17890. break;
  17891. }
  17892. }
  17893. this.reload();
  17894. }
  17895. };
  17896. FilesInput.prototype.reload = function () {
  17897. var _this = this;
  17898. var that = this;
  17899. // If a ".babylon" file has been provided
  17900. if (this._sceneFileToLoad) {
  17901. if (this._currentScene) {
  17902. this._engine.stopRenderLoop();
  17903. this._currentScene.dispose();
  17904. }
  17905. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  17906. that._currentScene = newScene;
  17907. // Wait for textures and shaders to be ready
  17908. that._currentScene.executeWhenReady(function () {
  17909. // Attach camera to canvas inputs
  17910. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  17911. that._currentScene.createDefaultCameraOrLight();
  17912. }
  17913. that._currentScene.activeCamera.attachControl(that._canvas);
  17914. if (that._sceneLoadedCallback) {
  17915. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  17916. }
  17917. that._engine.runRenderLoop(function () {
  17918. that.renderFunction();
  17919. });
  17920. });
  17921. }, function (progress) {
  17922. if (_this._progressCallback) {
  17923. _this._progressCallback(progress);
  17924. }
  17925. });
  17926. }
  17927. else {
  17928. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  17929. }
  17930. };
  17931. FilesInput.FilesTextures = new Array();
  17932. FilesInput.FilesToLoad = new Array();
  17933. return FilesInput;
  17934. })();
  17935. BABYLON.FilesInput = FilesInput;
  17936. })(BABYLON || (BABYLON = {}));
  17937. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  17938. (function (BABYLON) {
  17939. var OimoJSPlugin = (function () {
  17940. function OimoJSPlugin() {
  17941. this._registeredMeshes = [];
  17942. /**
  17943. * Update the body position according to the mesh position
  17944. * @param mesh
  17945. */
  17946. this.updateBodyPosition = function (mesh) {
  17947. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17948. var registeredMesh = this._registeredMeshes[index];
  17949. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17950. var body = registeredMesh.body.body;
  17951. mesh.computeWorldMatrix(true);
  17952. var center = mesh.getBoundingInfo().boundingBox.center;
  17953. body.setPosition(center.x, center.y, center.z);
  17954. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  17955. return;
  17956. }
  17957. // Case where the parent has been updated
  17958. if (registeredMesh.mesh.parent === mesh) {
  17959. mesh.computeWorldMatrix(true);
  17960. registeredMesh.mesh.computeWorldMatrix(true);
  17961. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  17962. var absoluteRotation = mesh.rotation;
  17963. body = registeredMesh.body.body;
  17964. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  17965. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  17966. return;
  17967. }
  17968. }
  17969. };
  17970. }
  17971. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  17972. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17973. };
  17974. OimoJSPlugin.prototype.initialize = function (iterations) {
  17975. this._world = new OIMO.World();
  17976. this._world.clear();
  17977. };
  17978. OimoJSPlugin.prototype.setGravity = function (gravity) {
  17979. this._world.gravity = gravity;
  17980. };
  17981. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17982. var body = null;
  17983. this.unregisterMesh(mesh);
  17984. mesh.computeWorldMatrix(true);
  17985. var initialRotation = null;
  17986. if (mesh.rotationQuaternion) {
  17987. initialRotation = mesh.rotationQuaternion.clone();
  17988. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17989. mesh.computeWorldMatrix(true);
  17990. }
  17991. var bbox = mesh.getBoundingInfo().boundingBox;
  17992. // The delta between the mesh position and the mesh bounding box center
  17993. var deltaPosition = mesh.position.subtract(bbox.center);
  17994. // Transform delta position with the rotation
  17995. if (initialRotation) {
  17996. var m = new BABYLON.Matrix();
  17997. initialRotation.toRotationMatrix(m);
  17998. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  17999. }
  18000. switch (impostor) {
  18001. case BABYLON.PhysicsEngine.SphereImpostor:
  18002. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18003. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18004. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18005. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18006. body = new OIMO.Body({
  18007. type: 'sphere',
  18008. size: [size],
  18009. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18010. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18011. move: options.mass != 0,
  18012. config: [options.mass, options.friction, options.restitution],
  18013. world: this._world
  18014. });
  18015. break;
  18016. case BABYLON.PhysicsEngine.PlaneImpostor:
  18017. case BABYLON.PhysicsEngine.CylinderImpostor:
  18018. case BABYLON.PhysicsEngine.BoxImpostor:
  18019. var min = bbox.minimumWorld;
  18020. var max = bbox.maximumWorld;
  18021. var box = max.subtract(min);
  18022. var sizeX = this._checkWithEpsilon(box.x);
  18023. var sizeY = this._checkWithEpsilon(box.y);
  18024. var sizeZ = this._checkWithEpsilon(box.z);
  18025. body = new OIMO.Body({
  18026. type: 'box',
  18027. size: [sizeX, sizeY, sizeZ],
  18028. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18029. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18030. move: options.mass != 0,
  18031. config: [options.mass, options.friction, options.restitution],
  18032. world: this._world
  18033. });
  18034. break;
  18035. }
  18036. //If quaternion was set as the rotation of the object
  18037. if (initialRotation) {
  18038. //We have to access the rigid body's properties to set the quaternion.
  18039. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  18040. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  18041. //update the internal rotation matrix
  18042. body.body.syncShapes();
  18043. }
  18044. this._registeredMeshes.push({
  18045. mesh: mesh,
  18046. body: body,
  18047. delta: deltaPosition
  18048. });
  18049. return body;
  18050. };
  18051. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18052. var types = [], sizes = [], positions = [], rotations = [];
  18053. var initialMesh = parts[0].mesh;
  18054. for (var index = 0; index < parts.length; index++) {
  18055. var part = parts[index];
  18056. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  18057. types.push(bodyParameters.type);
  18058. sizes.push.apply(sizes, bodyParameters.size);
  18059. positions.push.apply(positions, bodyParameters.pos);
  18060. rotations.push.apply(rotations, bodyParameters.rot);
  18061. }
  18062. var body = new OIMO.Body({
  18063. type: types,
  18064. size: sizes,
  18065. pos: positions,
  18066. rot: rotations,
  18067. move: options.mass != 0,
  18068. config: [options.mass, options.friction, options.restitution],
  18069. world: this._world
  18070. });
  18071. this._registeredMeshes.push({
  18072. mesh: initialMesh,
  18073. body: body
  18074. });
  18075. return body;
  18076. };
  18077. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  18078. var bodyParameters = null;
  18079. var mesh = part.mesh;
  18080. // We need the bounding box/sphere info to compute the physics body
  18081. mesh.computeWorldMatrix();
  18082. switch (part.impostor) {
  18083. case BABYLON.PhysicsEngine.SphereImpostor:
  18084. var bbox = mesh.getBoundingInfo().boundingBox;
  18085. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18086. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18087. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18088. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18089. bodyParameters = {
  18090. type: 'sphere',
  18091. /* bug with oimo : sphere needs 3 sizes in this case */
  18092. size: [size, -1, -1],
  18093. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  18094. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18095. };
  18096. break;
  18097. case BABYLON.PhysicsEngine.PlaneImpostor:
  18098. case BABYLON.PhysicsEngine.BoxImpostor:
  18099. bbox = mesh.getBoundingInfo().boundingBox;
  18100. var min = bbox.minimumWorld;
  18101. var max = bbox.maximumWorld;
  18102. var box = max.subtract(min);
  18103. var sizeX = this._checkWithEpsilon(box.x);
  18104. var sizeY = this._checkWithEpsilon(box.y);
  18105. var sizeZ = this._checkWithEpsilon(box.z);
  18106. var relativePosition = mesh.position;
  18107. bodyParameters = {
  18108. type: 'box',
  18109. size: [sizeX, sizeY, sizeZ],
  18110. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  18111. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18112. };
  18113. break;
  18114. }
  18115. return bodyParameters;
  18116. };
  18117. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  18118. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18119. var registeredMesh = this._registeredMeshes[index];
  18120. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18121. if (registeredMesh.body) {
  18122. this._world.removeRigidBody(registeredMesh.body.body);
  18123. this._unbindBody(registeredMesh.body);
  18124. }
  18125. this._registeredMeshes.splice(index, 1);
  18126. return;
  18127. }
  18128. }
  18129. };
  18130. OimoJSPlugin.prototype._unbindBody = function (body) {
  18131. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18132. var registeredMesh = this._registeredMeshes[index];
  18133. if (registeredMesh.body === body) {
  18134. registeredMesh.body = null;
  18135. }
  18136. }
  18137. };
  18138. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  18139. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18140. var registeredMesh = this._registeredMeshes[index];
  18141. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18142. // Get object mass to have a behaviour similar to cannon.js
  18143. var mass = registeredMesh.body.body.massInfo.mass;
  18144. // The force is scaled with the mass of object
  18145. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  18146. return;
  18147. }
  18148. }
  18149. };
  18150. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18151. var body1 = null, body2 = null;
  18152. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18153. var registeredMesh = this._registeredMeshes[index];
  18154. if (registeredMesh.mesh === mesh1) {
  18155. body1 = registeredMesh.body.body;
  18156. }
  18157. else if (registeredMesh.mesh === mesh2) {
  18158. body2 = registeredMesh.body.body;
  18159. }
  18160. }
  18161. if (!body1 || !body2) {
  18162. return false;
  18163. }
  18164. if (!options) {
  18165. options = {};
  18166. }
  18167. new OIMO.Link({
  18168. type: options.type,
  18169. body1: body1,
  18170. body2: body2,
  18171. min: options.min,
  18172. max: options.max,
  18173. axe1: options.axe1,
  18174. axe2: options.axe2,
  18175. pos1: [pivot1.x, pivot1.y, pivot1.z],
  18176. pos2: [pivot2.x, pivot2.y, pivot2.z],
  18177. collision: options.collision,
  18178. spring: options.spring,
  18179. world: this._world
  18180. });
  18181. return true;
  18182. };
  18183. OimoJSPlugin.prototype.dispose = function () {
  18184. this._world.clear();
  18185. while (this._registeredMeshes.length) {
  18186. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18187. }
  18188. };
  18189. OimoJSPlugin.prototype.isSupported = function () {
  18190. return OIMO !== undefined;
  18191. };
  18192. OimoJSPlugin.prototype._getLastShape = function (body) {
  18193. var lastShape = body.shapes;
  18194. while (lastShape.next) {
  18195. lastShape = lastShape.next;
  18196. }
  18197. return lastShape;
  18198. };
  18199. OimoJSPlugin.prototype.runOneStep = function (time) {
  18200. this._world.step();
  18201. // Update the position of all registered meshes
  18202. var i = this._registeredMeshes.length;
  18203. var m;
  18204. while (i--) {
  18205. var body = this._registeredMeshes[i].body.body;
  18206. var mesh = this._registeredMeshes[i].mesh;
  18207. var delta = this._registeredMeshes[i].delta;
  18208. if (!body.sleeping) {
  18209. if (body.shapes.next) {
  18210. var parentShape = this._getLastShape(body);
  18211. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  18212. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  18213. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  18214. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  18215. if (!mesh.rotationQuaternion) {
  18216. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18217. }
  18218. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  18219. mesh.computeWorldMatrix();
  18220. }
  18221. else {
  18222. m = body.getMatrix();
  18223. mtx = BABYLON.Matrix.FromArray(m);
  18224. // Body position
  18225. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  18226. if (!delta) {
  18227. mesh.position.x = bodyX;
  18228. mesh.position.y = bodyY;
  18229. mesh.position.z = bodyZ;
  18230. }
  18231. else {
  18232. mesh.position.x = bodyX + delta.x;
  18233. mesh.position.y = bodyY + delta.y;
  18234. mesh.position.z = bodyZ + delta.z;
  18235. }
  18236. if (!mesh.rotationQuaternion) {
  18237. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18238. }
  18239. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  18240. mesh.computeWorldMatrix();
  18241. }
  18242. }
  18243. }
  18244. };
  18245. return OimoJSPlugin;
  18246. })();
  18247. BABYLON.OimoJSPlugin = OimoJSPlugin;
  18248. })(BABYLON || (BABYLON = {}));
  18249. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  18250. (function (BABYLON) {
  18251. var PhysicsEngine = (function () {
  18252. function PhysicsEngine(plugin) {
  18253. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  18254. }
  18255. PhysicsEngine.prototype._initialize = function (gravity) {
  18256. this._currentPlugin.initialize();
  18257. this._setGravity(gravity);
  18258. };
  18259. PhysicsEngine.prototype._runOneStep = function (delta) {
  18260. if (delta > 0.1) {
  18261. delta = 0.1;
  18262. }
  18263. else if (delta <= 0) {
  18264. delta = 1.0 / 60.0;
  18265. }
  18266. this._currentPlugin.runOneStep(delta);
  18267. };
  18268. PhysicsEngine.prototype._setGravity = function (gravity) {
  18269. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  18270. this._currentPlugin.setGravity(this.gravity);
  18271. };
  18272. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  18273. return this._currentPlugin.registerMesh(mesh, impostor, options);
  18274. };
  18275. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  18276. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  18277. };
  18278. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  18279. this._currentPlugin.unregisterMesh(mesh);
  18280. };
  18281. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  18282. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  18283. };
  18284. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18285. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  18286. };
  18287. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  18288. this._currentPlugin.updateBodyPosition(mesh);
  18289. };
  18290. PhysicsEngine.prototype.dispose = function () {
  18291. this._currentPlugin.dispose();
  18292. };
  18293. PhysicsEngine.prototype.isSupported = function () {
  18294. return this._currentPlugin.isSupported();
  18295. };
  18296. // Statics
  18297. PhysicsEngine.NoImpostor = 0;
  18298. PhysicsEngine.SphereImpostor = 1;
  18299. PhysicsEngine.BoxImpostor = 2;
  18300. PhysicsEngine.PlaneImpostor = 3;
  18301. PhysicsEngine.MeshImpostor = 4;
  18302. PhysicsEngine.CapsuleImpostor = 5;
  18303. PhysicsEngine.ConeImpostor = 6;
  18304. PhysicsEngine.CylinderImpostor = 7;
  18305. PhysicsEngine.ConvexHullImpostor = 8;
  18306. PhysicsEngine.Epsilon = 0.001;
  18307. return PhysicsEngine;
  18308. })();
  18309. BABYLON.PhysicsEngine = PhysicsEngine;
  18310. })(BABYLON || (BABYLON = {}));
  18311. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  18312. (function (BABYLON) {
  18313. var serializeLight = function (light) {
  18314. var serializationObject = {};
  18315. serializationObject.name = light.name;
  18316. serializationObject.id = light.id;
  18317. serializationObject.tags = BABYLON.Tags.GetTags(light);
  18318. if (light instanceof BABYLON.PointLight) {
  18319. serializationObject.type = 0;
  18320. serializationObject.position = light.position.asArray();
  18321. }
  18322. else if (light instanceof BABYLON.DirectionalLight) {
  18323. serializationObject.type = 1;
  18324. var directionalLight = light;
  18325. serializationObject.position = directionalLight.position.asArray();
  18326. serializationObject.direction = directionalLight.direction.asArray();
  18327. }
  18328. else if (light instanceof BABYLON.SpotLight) {
  18329. serializationObject.type = 2;
  18330. var spotLight = light;
  18331. serializationObject.position = spotLight.position.asArray();
  18332. serializationObject.direction = spotLight.position.asArray();
  18333. serializationObject.angle = spotLight.angle;
  18334. serializationObject.exponent = spotLight.exponent;
  18335. }
  18336. else if (light instanceof BABYLON.HemisphericLight) {
  18337. serializationObject.type = 3;
  18338. var hemisphericLight = light;
  18339. serializationObject.direction = hemisphericLight.direction.asArray();
  18340. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  18341. }
  18342. if (light.intensity) {
  18343. serializationObject.intensity = light.intensity;
  18344. }
  18345. serializationObject.range = light.range;
  18346. serializationObject.diffuse = light.diffuse.asArray();
  18347. serializationObject.specular = light.specular.asArray();
  18348. return serializationObject;
  18349. };
  18350. var serializeFresnelParameter = function (fresnelParameter) {
  18351. var serializationObject = {};
  18352. serializationObject.isEnabled = fresnelParameter.isEnabled;
  18353. serializationObject.leftColor = fresnelParameter.leftColor;
  18354. serializationObject.rightColor = fresnelParameter.rightColor;
  18355. serializationObject.bias = fresnelParameter.bias;
  18356. serializationObject.power = fresnelParameter.power;
  18357. return serializationObject;
  18358. };
  18359. var appendAnimations = function (source, destination) {
  18360. if (source.animations) {
  18361. destination.animations = [];
  18362. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  18363. var animation = source.animations[animationIndex];
  18364. destination.animations.push(serializeAnimation(animation));
  18365. }
  18366. }
  18367. };
  18368. var serializeCamera = function (camera) {
  18369. var serializationObject = {};
  18370. serializationObject.name = camera.name;
  18371. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  18372. serializationObject.id = camera.id;
  18373. serializationObject.position = camera.position.asArray();
  18374. // Parent
  18375. if (camera.parent) {
  18376. serializationObject.parentId = camera.parent.id;
  18377. }
  18378. serializationObject.fov = camera.fov;
  18379. serializationObject.minZ = camera.minZ;
  18380. serializationObject.maxZ = camera.maxZ;
  18381. serializationObject.inertia = camera.inertia;
  18382. //setting the type
  18383. if (camera instanceof BABYLON.FreeCamera) {
  18384. serializationObject.type = "FreeCamera";
  18385. }
  18386. else if (camera instanceof BABYLON.ArcRotateCamera) {
  18387. serializationObject.type = "ArcRotateCamera";
  18388. }
  18389. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18390. serializationObject.type = "AnaglyphArcRotateCamera";
  18391. }
  18392. else if (camera instanceof BABYLON.GamepadCamera) {
  18393. serializationObject.type = "GamepadCamera";
  18394. }
  18395. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  18396. serializationObject.type = "AnaglyphFreeCamera";
  18397. }
  18398. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  18399. serializationObject.type = "DeviceOrientationCamera";
  18400. }
  18401. else if (camera instanceof BABYLON.FollowCamera) {
  18402. serializationObject.type = "FollowCamera";
  18403. }
  18404. else if (camera instanceof BABYLON.OculusCamera) {
  18405. serializationObject.type = "OculusCamera";
  18406. }
  18407. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  18408. serializationObject.type = "OculusGamepadCamera";
  18409. }
  18410. else if (camera instanceof BABYLON.TouchCamera) {
  18411. serializationObject.type = "TouchCamera";
  18412. }
  18413. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  18414. serializationObject.type = "VirtualJoysticksCamera";
  18415. }
  18416. else if (camera instanceof BABYLON.WebVRCamera) {
  18417. serializationObject.type = "WebVRCamera";
  18418. }
  18419. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  18420. serializationObject.type = "VRDeviceOrientationCamera";
  18421. }
  18422. //special properties of specific cameras
  18423. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18424. var arcCamera = camera;
  18425. serializationObject.alpha = arcCamera.alpha;
  18426. serializationObject.beta = arcCamera.beta;
  18427. serializationObject.radius = arcCamera.radius;
  18428. if (arcCamera.target && arcCamera.target.id) {
  18429. serializationObject.lockedTargetId = arcCamera.target.id;
  18430. }
  18431. }
  18432. else if (camera instanceof BABYLON.FollowCamera) {
  18433. var followCam = camera;
  18434. serializationObject.radius = followCam.radius;
  18435. serializationObject.heightOffset = followCam.heightOffset;
  18436. serializationObject.rotationOffset = followCam.rotationOffset;
  18437. }
  18438. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18439. //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.
  18440. if (camera['_eyeSpace'] !== undefined) {
  18441. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  18442. }
  18443. }
  18444. //general properties that not all cameras have. The [] is due to typescript's type safety
  18445. if (camera['speed'] !== undefined) {
  18446. serializationObject.speed = camera['speed'];
  18447. }
  18448. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  18449. serializationObject.target = camera['target'].asArray();
  18450. }
  18451. // Target
  18452. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  18453. serializationObject.rotation = camera['rotation'].asArray();
  18454. }
  18455. // Locked target
  18456. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  18457. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  18458. }
  18459. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  18460. serializationObject.applyGravity = camera['applyGravity'] || false;
  18461. if (camera['ellipsoid']) {
  18462. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  18463. }
  18464. // Animations
  18465. appendAnimations(camera, serializationObject);
  18466. // Layer mask
  18467. serializationObject.layerMask = camera.layerMask;
  18468. return serializationObject;
  18469. };
  18470. var serializeAnimation = function (animation) {
  18471. var serializationObject = {};
  18472. serializationObject.name = animation.name;
  18473. serializationObject.property = animation.targetProperty;
  18474. serializationObject.framePerSecond = animation.framePerSecond;
  18475. serializationObject.dataType = animation.dataType;
  18476. serializationObject.loopBehavior = animation.loopMode;
  18477. var dataType = animation.dataType;
  18478. serializationObject.keys = [];
  18479. var keys = animation.getKeys();
  18480. for (var index = 0; index < keys.length; index++) {
  18481. var animationKey = keys[index];
  18482. var key = {};
  18483. key.frame = animationKey.frame;
  18484. switch (dataType) {
  18485. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18486. key.values = [animationKey.value];
  18487. break;
  18488. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18489. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18490. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18491. key.values = animationKey.value.asArray();
  18492. break;
  18493. }
  18494. serializationObject.keys.push(key);
  18495. }
  18496. return serializationObject;
  18497. };
  18498. var serializeMultiMaterial = function (material) {
  18499. var serializationObject = {};
  18500. serializationObject.name = material.name;
  18501. serializationObject.id = material.id;
  18502. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18503. serializationObject.materials = [];
  18504. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  18505. var subMat = material.subMaterials[matIndex];
  18506. if (subMat) {
  18507. serializationObject.materials.push(subMat.id);
  18508. }
  18509. else {
  18510. serializationObject.materials.push(null);
  18511. }
  18512. }
  18513. return serializationObject;
  18514. };
  18515. var serializeMaterial = function (material) {
  18516. var serializationObject = {};
  18517. serializationObject.name = material.name;
  18518. serializationObject.ambient = material.ambientColor.asArray();
  18519. serializationObject.diffuse = material.diffuseColor.asArray();
  18520. serializationObject.specular = material.specularColor.asArray();
  18521. serializationObject.specularPower = material.specularPower;
  18522. serializationObject.emissive = material.emissiveColor.asArray();
  18523. serializationObject.alpha = material.alpha;
  18524. serializationObject.id = material.id;
  18525. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18526. serializationObject.backFaceCulling = material.backFaceCulling;
  18527. if (material.diffuseTexture) {
  18528. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  18529. }
  18530. if (material.diffuseFresnelParameters) {
  18531. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  18532. }
  18533. if (material.ambientTexture) {
  18534. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  18535. }
  18536. if (material.opacityTexture) {
  18537. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  18538. }
  18539. if (material.opacityFresnelParameters) {
  18540. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  18541. }
  18542. if (material.reflectionTexture) {
  18543. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  18544. }
  18545. if (material.reflectionFresnelParameters) {
  18546. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  18547. }
  18548. if (material.emissiveTexture) {
  18549. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  18550. }
  18551. if (material.emissiveFresnelParameters) {
  18552. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  18553. }
  18554. if (material.specularTexture) {
  18555. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  18556. }
  18557. if (material.bumpTexture) {
  18558. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  18559. }
  18560. return serializationObject;
  18561. };
  18562. var serializeTexture = function (texture) {
  18563. var serializationObject = {};
  18564. if (!texture.name) {
  18565. return null;
  18566. }
  18567. if (texture instanceof BABYLON.CubeTexture) {
  18568. serializationObject.name = texture.name;
  18569. serializationObject.hasAlpha = texture.hasAlpha;
  18570. serializationObject.level = texture.level;
  18571. serializationObject.coordinatesMode = texture.coordinatesMode;
  18572. return serializationObject;
  18573. }
  18574. if (texture instanceof BABYLON.MirrorTexture) {
  18575. var mirrorTexture = texture;
  18576. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  18577. serializationObject.renderList = [];
  18578. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  18579. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  18580. }
  18581. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  18582. }
  18583. else if (texture instanceof BABYLON.RenderTargetTexture) {
  18584. var renderTargetTexture = texture;
  18585. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  18586. serializationObject.renderList = [];
  18587. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  18588. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  18589. }
  18590. }
  18591. var regularTexture = texture;
  18592. serializationObject.name = texture.name;
  18593. serializationObject.hasAlpha = texture.hasAlpha;
  18594. serializationObject.level = texture.level;
  18595. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  18596. serializationObject.coordinatesMode = texture.coordinatesMode;
  18597. serializationObject.uOffset = regularTexture.uOffset;
  18598. serializationObject.vOffset = regularTexture.vOffset;
  18599. serializationObject.uScale = regularTexture.uScale;
  18600. serializationObject.vScale = regularTexture.vScale;
  18601. serializationObject.uAng = regularTexture.uAng;
  18602. serializationObject.vAng = regularTexture.vAng;
  18603. serializationObject.wAng = regularTexture.wAng;
  18604. serializationObject.wrapU = texture.wrapU;
  18605. serializationObject.wrapV = texture.wrapV;
  18606. // Animations
  18607. appendAnimations(texture, serializationObject);
  18608. return serializationObject;
  18609. };
  18610. var serializeSkeleton = function (skeleton) {
  18611. var serializationObject = {};
  18612. serializationObject.name = skeleton.name;
  18613. serializationObject.id = skeleton.id;
  18614. serializationObject.bones = [];
  18615. for (var index = 0; index < skeleton.bones.length; index++) {
  18616. var bone = skeleton.bones[index];
  18617. var serializedBone = {
  18618. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  18619. name: bone.name,
  18620. matrix: bone.getLocalMatrix().toArray()
  18621. };
  18622. serializationObject.bones.push(serializedBone);
  18623. if (bone.animations && bone.animations.length > 0) {
  18624. serializedBone.animation = serializeAnimation(bone.animations[0]);
  18625. }
  18626. }
  18627. return serializationObject;
  18628. };
  18629. var serializeParticleSystem = function (particleSystem) {
  18630. var serializationObject = {};
  18631. serializationObject.emitterId = particleSystem.emitter.id;
  18632. serializationObject.capacity = particleSystem.getCapacity();
  18633. if (particleSystem.particleTexture) {
  18634. serializationObject.textureName = particleSystem.particleTexture.name;
  18635. }
  18636. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  18637. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  18638. serializationObject.minSize = particleSystem.minSize;
  18639. serializationObject.maxSize = particleSystem.maxSize;
  18640. serializationObject.minLifeTime = particleSystem.minLifeTime;
  18641. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  18642. serializationObject.emitRate = particleSystem.emitRate;
  18643. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  18644. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  18645. serializationObject.gravity = particleSystem.gravity.asArray();
  18646. serializationObject.direction1 = particleSystem.direction1.asArray();
  18647. serializationObject.direction2 = particleSystem.direction2.asArray();
  18648. serializationObject.color1 = particleSystem.color1.asArray();
  18649. serializationObject.color2 = particleSystem.color2.asArray();
  18650. serializationObject.colorDead = particleSystem.colorDead.asArray();
  18651. serializationObject.updateSpeed = particleSystem.updateSpeed;
  18652. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  18653. serializationObject.textureMask = particleSystem.textureMask.asArray();
  18654. serializationObject.blendMode = particleSystem.blendMode;
  18655. return serializationObject;
  18656. };
  18657. var serializeLensFlareSystem = function (lensFlareSystem) {
  18658. var serializationObject = {};
  18659. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  18660. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  18661. serializationObject.flares = [];
  18662. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  18663. var flare = lensFlareSystem.lensFlares[index];
  18664. serializationObject.flares.push({
  18665. size: flare.size,
  18666. position: flare.position,
  18667. color: flare.color.asArray(),
  18668. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  18669. });
  18670. }
  18671. return serializationObject;
  18672. };
  18673. var serializeShadowGenerator = function (light) {
  18674. var serializationObject = {};
  18675. var shadowGenerator = light.getShadowGenerator();
  18676. serializationObject.lightId = light.id;
  18677. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  18678. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  18679. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  18680. serializationObject.renderList = [];
  18681. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  18682. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  18683. serializationObject.renderList.push(mesh.id);
  18684. }
  18685. return serializationObject;
  18686. };
  18687. var serializedGeometries = [];
  18688. var serializeGeometry = function (geometry, serializationGeometries) {
  18689. if (serializedGeometries[geometry.id]) {
  18690. return;
  18691. }
  18692. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  18693. serializationGeometries.boxes.push(serializeBox(geometry));
  18694. }
  18695. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  18696. serializationGeometries.spheres.push(serializeSphere(geometry));
  18697. }
  18698. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  18699. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  18700. }
  18701. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  18702. serializationGeometries.toruses.push(serializeTorus(geometry));
  18703. }
  18704. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  18705. serializationGeometries.grounds.push(serializeGround(geometry));
  18706. }
  18707. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  18708. serializationGeometries.planes.push(serializePlane(geometry));
  18709. }
  18710. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  18711. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  18712. }
  18713. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  18714. throw new Error("Unknow primitive type");
  18715. }
  18716. else {
  18717. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  18718. }
  18719. serializedGeometries[geometry.id] = true;
  18720. };
  18721. var serializeGeometryBase = function (geometry) {
  18722. var serializationObject = {};
  18723. serializationObject.id = geometry.id;
  18724. if (BABYLON.Tags.HasTags(geometry)) {
  18725. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  18726. }
  18727. return serializationObject;
  18728. };
  18729. var serializeVertexData = function (vertexData) {
  18730. var serializationObject = serializeGeometryBase(vertexData);
  18731. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18732. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18733. }
  18734. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18735. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18736. }
  18737. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18738. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18739. }
  18740. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18741. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  18742. }
  18743. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18744. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  18745. }
  18746. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18747. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18748. serializationObject.matricesIndices._isExpanded = true;
  18749. }
  18750. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18751. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18752. }
  18753. serializationObject.indices = vertexData.getIndices();
  18754. return serializationObject;
  18755. };
  18756. var serializePrimitive = function (primitive) {
  18757. var serializationObject = serializeGeometryBase(primitive);
  18758. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  18759. return serializationObject;
  18760. };
  18761. var serializeBox = function (box) {
  18762. var serializationObject = serializePrimitive(box);
  18763. serializationObject.size = box.size;
  18764. return serializationObject;
  18765. };
  18766. var serializeSphere = function (sphere) {
  18767. var serializationObject = serializePrimitive(sphere);
  18768. serializationObject.segments = sphere.segments;
  18769. serializationObject.diameter = sphere.diameter;
  18770. return serializationObject;
  18771. };
  18772. var serializeCylinder = function (cylinder) {
  18773. var serializationObject = serializePrimitive(cylinder);
  18774. serializationObject.height = cylinder.height;
  18775. serializationObject.diameterTop = cylinder.diameterTop;
  18776. serializationObject.diameterBottom = cylinder.diameterBottom;
  18777. serializationObject.tessellation = cylinder.tessellation;
  18778. return serializationObject;
  18779. };
  18780. var serializeTorus = function (torus) {
  18781. var serializationObject = serializePrimitive(torus);
  18782. serializationObject.diameter = torus.diameter;
  18783. serializationObject.thickness = torus.thickness;
  18784. serializationObject.tessellation = torus.tessellation;
  18785. return serializationObject;
  18786. };
  18787. var serializeGround = function (ground) {
  18788. var serializationObject = serializePrimitive(ground);
  18789. serializationObject.width = ground.width;
  18790. serializationObject.height = ground.height;
  18791. serializationObject.subdivisions = ground.subdivisions;
  18792. return serializationObject;
  18793. };
  18794. var serializePlane = function (plane) {
  18795. var serializationObject = serializePrimitive(plane);
  18796. serializationObject.size = plane.size;
  18797. return serializationObject;
  18798. };
  18799. var serializeTorusKnot = function (torusKnot) {
  18800. var serializationObject = serializePrimitive(torusKnot);
  18801. serializationObject.radius = torusKnot.radius;
  18802. serializationObject.tube = torusKnot.tube;
  18803. serializationObject.radialSegments = torusKnot.radialSegments;
  18804. serializationObject.tubularSegments = torusKnot.tubularSegments;
  18805. serializationObject.p = torusKnot.p;
  18806. serializationObject.q = torusKnot.q;
  18807. return serializationObject;
  18808. };
  18809. var serializeMesh = function (mesh, serializationScene) {
  18810. var serializationObject = {};
  18811. serializationObject.name = mesh.name;
  18812. serializationObject.id = mesh.id;
  18813. if (BABYLON.Tags.HasTags(mesh)) {
  18814. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  18815. }
  18816. serializationObject.position = mesh.position.asArray();
  18817. if (mesh.rotationQuaternion) {
  18818. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  18819. }
  18820. else if (mesh.rotation) {
  18821. serializationObject.rotation = mesh.rotation.asArray();
  18822. }
  18823. serializationObject.scaling = mesh.scaling.asArray();
  18824. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  18825. serializationObject.isEnabled = mesh.isEnabled();
  18826. serializationObject.isVisible = mesh.isVisible;
  18827. serializationObject.infiniteDistance = mesh.infiniteDistance;
  18828. serializationObject.pickable = mesh.isPickable;
  18829. serializationObject.receiveShadows = mesh.receiveShadows;
  18830. serializationObject.billboardMode = mesh.billboardMode;
  18831. serializationObject.visibility = mesh.visibility;
  18832. serializationObject.checkCollisions = mesh.checkCollisions;
  18833. // Parent
  18834. if (mesh.parent) {
  18835. serializationObject.parentId = mesh.parent.id;
  18836. }
  18837. // Geometry
  18838. var geometry = mesh._geometry;
  18839. if (geometry) {
  18840. var geometryId = geometry.id;
  18841. serializationObject.geometryId = geometryId;
  18842. if (!mesh.getScene().getGeometryByID(geometryId)) {
  18843. // 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
  18844. serializeGeometry(geometry, serializationScene.geometries);
  18845. }
  18846. // SubMeshes
  18847. serializationObject.subMeshes = [];
  18848. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  18849. var subMesh = mesh.subMeshes[subIndex];
  18850. serializationObject.subMeshes.push({
  18851. materialIndex: subMesh.materialIndex,
  18852. verticesStart: subMesh.verticesStart,
  18853. verticesCount: subMesh.verticesCount,
  18854. indexStart: subMesh.indexStart,
  18855. indexCount: subMesh.indexCount
  18856. });
  18857. }
  18858. }
  18859. // Material
  18860. if (mesh.material) {
  18861. serializationObject.materialId = mesh.material.id;
  18862. }
  18863. else {
  18864. mesh.material = null;
  18865. }
  18866. // Skeleton
  18867. if (mesh.skeleton) {
  18868. serializationObject.skeletonId = mesh.skeleton.id;
  18869. }
  18870. // Physics
  18871. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  18872. serializationObject.physicsMass = mesh.getPhysicsMass();
  18873. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  18874. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  18875. switch (mesh.getPhysicsImpostor()) {
  18876. case BABYLON.PhysicsEngine.BoxImpostor:
  18877. serializationObject.physicsImpostor = 1;
  18878. break;
  18879. case BABYLON.PhysicsEngine.SphereImpostor:
  18880. serializationObject.physicsImpostor = 2;
  18881. break;
  18882. }
  18883. }
  18884. // Instances
  18885. serializationObject.instances = [];
  18886. for (var index = 0; index < mesh.instances.length; index++) {
  18887. var instance = mesh.instances[index];
  18888. var serializationInstance = {
  18889. name: instance.name,
  18890. position: instance.position,
  18891. rotation: instance.rotation,
  18892. rotationQuaternion: instance.rotationQuaternion,
  18893. scaling: instance.scaling
  18894. };
  18895. serializationObject.instances.push(serializationInstance);
  18896. // Animations
  18897. appendAnimations(instance, serializationInstance);
  18898. }
  18899. // Animations
  18900. appendAnimations(mesh, serializationObject);
  18901. // Layer mask
  18902. serializationObject.layerMask = mesh.layerMask;
  18903. return serializationObject;
  18904. };
  18905. var SceneSerializer = (function () {
  18906. function SceneSerializer() {
  18907. }
  18908. SceneSerializer.Serialize = function (scene) {
  18909. var serializationObject = {};
  18910. // Scene
  18911. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  18912. serializationObject.autoClear = scene.autoClear;
  18913. serializationObject.clearColor = scene.clearColor.asArray();
  18914. serializationObject.ambientColor = scene.ambientColor.asArray();
  18915. serializationObject.gravity = scene.gravity.asArray();
  18916. // Fog
  18917. if (scene.fogMode && scene.fogMode !== 0) {
  18918. serializationObject.fogMode = scene.fogMode;
  18919. serializationObject.fogColor = scene.fogColor.asArray();
  18920. serializationObject.fogStart = scene.fogStart;
  18921. serializationObject.fogEnd = scene.fogEnd;
  18922. serializationObject.fogDensity = scene.fogDensity;
  18923. }
  18924. // Lights
  18925. serializationObject.lights = [];
  18926. for (var index = 0; index < scene.lights.length; index++) {
  18927. var light = scene.lights[index];
  18928. serializationObject.lights.push(serializeLight(light));
  18929. }
  18930. // Cameras
  18931. serializationObject.cameras = [];
  18932. for (index = 0; index < scene.cameras.length; index++) {
  18933. var camera = scene.cameras[index];
  18934. serializationObject.cameras.push(serializeCamera(camera));
  18935. }
  18936. if (scene.activeCamera) {
  18937. serializationObject.activeCameraID = scene.activeCamera.id;
  18938. }
  18939. // Materials
  18940. serializationObject.materials = [];
  18941. serializationObject.multiMaterials = [];
  18942. for (index = 0; index < scene.materials.length; index++) {
  18943. var material = scene.materials[index];
  18944. if (material instanceof BABYLON.StandardMaterial) {
  18945. serializationObject.materials.push(serializeMaterial(material));
  18946. }
  18947. else if (material instanceof BABYLON.MultiMaterial) {
  18948. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  18949. }
  18950. }
  18951. // Skeletons
  18952. serializationObject.skeletons = [];
  18953. for (index = 0; index < scene.skeletons.length; index++) {
  18954. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  18955. }
  18956. // Geometries
  18957. serializationObject.geometries = {};
  18958. serializationObject.geometries.boxes = [];
  18959. serializationObject.geometries.spheres = [];
  18960. serializationObject.geometries.cylinders = [];
  18961. serializationObject.geometries.toruses = [];
  18962. serializationObject.geometries.grounds = [];
  18963. serializationObject.geometries.planes = [];
  18964. serializationObject.geometries.torusKnots = [];
  18965. serializationObject.geometries.vertexData = [];
  18966. serializedGeometries = [];
  18967. var geometries = scene.getGeometries();
  18968. for (index = 0; index < geometries.length; index++) {
  18969. var geometry = geometries[index];
  18970. if (geometry.isReady()) {
  18971. serializeGeometry(geometry, serializationObject.geometries);
  18972. }
  18973. }
  18974. // Meshes
  18975. serializationObject.meshes = [];
  18976. for (index = 0; index < scene.meshes.length; index++) {
  18977. var abstractMesh = scene.meshes[index];
  18978. if (abstractMesh instanceof BABYLON.Mesh) {
  18979. var mesh = abstractMesh;
  18980. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  18981. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  18982. }
  18983. }
  18984. }
  18985. // Particles Systems
  18986. serializationObject.particleSystems = [];
  18987. for (index = 0; index < scene.particleSystems.length; index++) {
  18988. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  18989. }
  18990. // Lens flares
  18991. serializationObject.lensFlareSystems = [];
  18992. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  18993. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  18994. }
  18995. // Shadows
  18996. serializationObject.shadowGenerators = [];
  18997. for (index = 0; index < scene.lights.length; index++) {
  18998. light = scene.lights[index];
  18999. if (light.getShadowGenerator()) {
  19000. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  19001. }
  19002. }
  19003. return serializationObject;
  19004. };
  19005. return SceneSerializer;
  19006. })();
  19007. BABYLON.SceneSerializer = SceneSerializer;
  19008. })(BABYLON || (BABYLON = {}));
  19009. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  19010. (function (BABYLON) {
  19011. var SceneLoader = (function () {
  19012. function SceneLoader() {
  19013. }
  19014. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19015. get: function () {
  19016. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19017. },
  19018. set: function (value) {
  19019. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19020. },
  19021. enumerable: true,
  19022. configurable: true
  19023. });
  19024. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19025. get: function () {
  19026. return SceneLoader._ShowLoadingScreen;
  19027. },
  19028. set: function (value) {
  19029. SceneLoader._ShowLoadingScreen = value;
  19030. },
  19031. enumerable: true,
  19032. configurable: true
  19033. });
  19034. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19035. var dotPosition = sceneFilename.lastIndexOf(".");
  19036. var queryStringPosition = sceneFilename.indexOf("?");
  19037. if (queryStringPosition === -1) {
  19038. queryStringPosition = sceneFilename.length;
  19039. }
  19040. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19041. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19042. var plugin = this._registeredPlugins[index];
  19043. if (plugin.extensions.indexOf(extension) !== -1) {
  19044. return plugin;
  19045. }
  19046. }
  19047. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19048. };
  19049. // Public functions
  19050. SceneLoader.RegisterPlugin = function (plugin) {
  19051. plugin.extensions = plugin.extensions.toLowerCase();
  19052. SceneLoader._registeredPlugins.push(plugin);
  19053. };
  19054. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19055. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19056. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19057. return;
  19058. }
  19059. var manifestChecked = function (success) {
  19060. scene.database = database;
  19061. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19062. var importMeshFromData = function (data) {
  19063. var meshes = [];
  19064. var particleSystems = [];
  19065. var skeletons = [];
  19066. try {
  19067. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19068. if (onerror) {
  19069. onerror(scene, 'unable to load the scene');
  19070. }
  19071. return;
  19072. }
  19073. }
  19074. catch (e) {
  19075. if (onerror) {
  19076. onerror(scene, e);
  19077. }
  19078. return;
  19079. }
  19080. if (onsuccess) {
  19081. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19082. onsuccess(meshes, particleSystems, skeletons);
  19083. }
  19084. };
  19085. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19086. // Direct load
  19087. importMeshFromData(sceneFilename.substr(5));
  19088. return;
  19089. }
  19090. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19091. importMeshFromData(data);
  19092. }, progressCallBack, database);
  19093. };
  19094. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19095. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19096. };
  19097. /**
  19098. * Load a scene
  19099. * @param rootUrl a string that defines the root url for scene and resources
  19100. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19101. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19102. */
  19103. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19104. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19105. };
  19106. /**
  19107. * Append a scene
  19108. * @param rootUrl a string that defines the root url for scene and resources
  19109. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19110. * @param scene is the instance of BABYLON.Scene to append to
  19111. */
  19112. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19113. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19114. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19115. return;
  19116. }
  19117. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19118. var database;
  19119. if (SceneLoader.ShowLoadingScreen) {
  19120. scene.getEngine().displayLoadingUI();
  19121. }
  19122. var loadSceneFromData = function (data) {
  19123. scene.database = database;
  19124. if (!plugin.load(scene, data, rootUrl)) {
  19125. if (onerror) {
  19126. onerror(scene);
  19127. }
  19128. scene.getEngine().hideLoadingUI();
  19129. return;
  19130. }
  19131. if (onsuccess) {
  19132. onsuccess(scene);
  19133. }
  19134. if (SceneLoader.ShowLoadingScreen) {
  19135. scene.executeWhenReady(function () {
  19136. scene.getEngine().hideLoadingUI();
  19137. });
  19138. }
  19139. };
  19140. var manifestChecked = function (success) {
  19141. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19142. };
  19143. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19144. // Direct load
  19145. loadSceneFromData(sceneFilename.substr(5));
  19146. return;
  19147. }
  19148. if (rootUrl.indexOf("file:") === -1) {
  19149. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19150. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19151. }
  19152. else {
  19153. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19154. }
  19155. };
  19156. // Flags
  19157. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19158. SceneLoader._ShowLoadingScreen = true;
  19159. // Members
  19160. SceneLoader._registeredPlugins = new Array();
  19161. return SceneLoader;
  19162. })();
  19163. BABYLON.SceneLoader = SceneLoader;
  19164. ;
  19165. })(BABYLON || (BABYLON = {}));
  19166. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  19167. (function (BABYLON) {
  19168. var Internals;
  19169. (function (Internals) {
  19170. var checkColors4 = function (colors, count) {
  19171. // Check if color3 was used
  19172. if (colors.length === count * 3) {
  19173. var colors4 = [];
  19174. for (var index = 0; index < colors.length; index += 3) {
  19175. var newIndex = (index / 3) * 4;
  19176. colors4[newIndex] = colors[index];
  19177. colors4[newIndex + 1] = colors[index + 1];
  19178. colors4[newIndex + 2] = colors[index + 2];
  19179. colors4[newIndex + 3] = 1.0;
  19180. }
  19181. return colors4;
  19182. }
  19183. return colors;
  19184. };
  19185. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19186. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  19187. texture.name = parsedTexture.name;
  19188. texture.hasAlpha = parsedTexture.hasAlpha;
  19189. texture.level = parsedTexture.level;
  19190. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19191. return texture;
  19192. };
  19193. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19194. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19195. return null;
  19196. }
  19197. if (parsedTexture.isCube) {
  19198. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19199. }
  19200. var texture;
  19201. if (parsedTexture.mirrorPlane) {
  19202. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19203. texture._waitingRenderList = parsedTexture.renderList;
  19204. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19205. }
  19206. else if (parsedTexture.isRenderTarget) {
  19207. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19208. texture._waitingRenderList = parsedTexture.renderList;
  19209. }
  19210. else {
  19211. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19212. }
  19213. texture.name = parsedTexture.name;
  19214. texture.hasAlpha = parsedTexture.hasAlpha;
  19215. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19216. texture.level = parsedTexture.level;
  19217. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19218. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19219. texture.uOffset = parsedTexture.uOffset;
  19220. texture.vOffset = parsedTexture.vOffset;
  19221. texture.uScale = parsedTexture.uScale;
  19222. texture.vScale = parsedTexture.vScale;
  19223. texture.uAng = parsedTexture.uAng;
  19224. texture.vAng = parsedTexture.vAng;
  19225. texture.wAng = parsedTexture.wAng;
  19226. texture.wrapU = parsedTexture.wrapU;
  19227. texture.wrapV = parsedTexture.wrapV;
  19228. // Animations
  19229. if (parsedTexture.animations) {
  19230. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19231. var parsedAnimation = parsedTexture.animations[animationIndex];
  19232. texture.animations.push(parseAnimation(parsedAnimation));
  19233. }
  19234. }
  19235. return texture;
  19236. };
  19237. var parseSkeleton = function (parsedSkeleton, scene) {
  19238. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19239. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19240. var parsedBone = parsedSkeleton.bones[index];
  19241. var parentBone = null;
  19242. if (parsedBone.parentBoneIndex > -1) {
  19243. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19244. }
  19245. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19246. if (parsedBone.animation) {
  19247. bone.animations.push(parseAnimation(parsedBone.animation));
  19248. }
  19249. }
  19250. return skeleton;
  19251. };
  19252. var parseFresnelParameters = function (parsedFresnelParameters) {
  19253. var fresnelParameters = new BABYLON.FresnelParameters();
  19254. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19255. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19256. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19257. fresnelParameters.bias = parsedFresnelParameters.bias;
  19258. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19259. return fresnelParameters;
  19260. };
  19261. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19262. var material;
  19263. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19264. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19265. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19266. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19267. material.specularPower = parsedMaterial.specularPower;
  19268. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19269. material.alpha = parsedMaterial.alpha;
  19270. material.id = parsedMaterial.id;
  19271. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19272. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19273. material.wireframe = parsedMaterial.wireframe;
  19274. if (parsedMaterial.diffuseTexture) {
  19275. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19276. }
  19277. if (parsedMaterial.diffuseFresnelParameters) {
  19278. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19279. }
  19280. if (parsedMaterial.ambientTexture) {
  19281. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19282. }
  19283. if (parsedMaterial.opacityTexture) {
  19284. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19285. }
  19286. if (parsedMaterial.opacityFresnelParameters) {
  19287. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19288. }
  19289. if (parsedMaterial.reflectionTexture) {
  19290. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19291. }
  19292. if (parsedMaterial.reflectionFresnelParameters) {
  19293. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19294. }
  19295. if (parsedMaterial.emissiveTexture) {
  19296. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19297. }
  19298. if (parsedMaterial.emissiveFresnelParameters) {
  19299. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19300. }
  19301. if (parsedMaterial.specularTexture) {
  19302. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19303. }
  19304. if (parsedMaterial.bumpTexture) {
  19305. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19306. }
  19307. return material;
  19308. };
  19309. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19310. for (var index = 0; index < parsedData.materials.length; index++) {
  19311. var parsedMaterial = parsedData.materials[index];
  19312. if (parsedMaterial.id === id) {
  19313. return parseMaterial(parsedMaterial, scene, rootUrl);
  19314. }
  19315. }
  19316. return null;
  19317. };
  19318. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19319. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19320. multiMaterial.id = parsedMultiMaterial.id;
  19321. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19322. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19323. var subMatId = parsedMultiMaterial.materials[matIndex];
  19324. if (subMatId) {
  19325. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19326. }
  19327. else {
  19328. multiMaterial.subMaterials.push(null);
  19329. }
  19330. }
  19331. return multiMaterial;
  19332. };
  19333. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19334. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19335. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19336. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19337. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19338. var parsedFlare = parsedLensFlareSystem.flares[index];
  19339. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19340. }
  19341. return lensFlareSystem;
  19342. };
  19343. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19344. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19345. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19346. if (parsedParticleSystem.textureName) {
  19347. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19348. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19349. }
  19350. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19351. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19352. particleSystem.minSize = parsedParticleSystem.minSize;
  19353. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19354. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19355. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19356. particleSystem.emitter = emitter;
  19357. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19358. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19359. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19360. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19361. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19362. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19363. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19364. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19365. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19366. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19367. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19368. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19369. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19370. particleSystem.start();
  19371. return particleSystem;
  19372. };
  19373. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19374. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19375. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19376. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19377. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19378. shadowGenerator.getShadowMap().renderList.push(mesh);
  19379. }
  19380. if (parsedShadowGenerator.usePoissonSampling) {
  19381. shadowGenerator.usePoissonSampling = true;
  19382. }
  19383. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19384. shadowGenerator.useVarianceShadowMap = true;
  19385. }
  19386. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19387. shadowGenerator.useBlurVarianceShadowMap = true;
  19388. if (parsedShadowGenerator.blurScale) {
  19389. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19390. }
  19391. if (parsedShadowGenerator.blurBoxOffset) {
  19392. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19393. }
  19394. }
  19395. if (parsedShadowGenerator.bias !== undefined) {
  19396. shadowGenerator.bias = parsedShadowGenerator.bias;
  19397. }
  19398. return shadowGenerator;
  19399. };
  19400. var parseAnimation = function (parsedAnimation) {
  19401. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19402. var dataType = parsedAnimation.dataType;
  19403. var keys = [];
  19404. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19405. var key = parsedAnimation.keys[index];
  19406. var data;
  19407. switch (dataType) {
  19408. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19409. data = key.values[0];
  19410. break;
  19411. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19412. data = BABYLON.Quaternion.FromArray(key.values);
  19413. break;
  19414. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19415. data = BABYLON.Matrix.FromArray(key.values);
  19416. break;
  19417. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19418. default:
  19419. data = BABYLON.Vector3.FromArray(key.values);
  19420. break;
  19421. }
  19422. keys.push({
  19423. frame: key.frame,
  19424. value: data
  19425. });
  19426. }
  19427. animation.setKeys(keys);
  19428. return animation;
  19429. };
  19430. var parseLight = function (parsedLight, scene) {
  19431. var light;
  19432. switch (parsedLight.type) {
  19433. case 0:
  19434. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19435. break;
  19436. case 1:
  19437. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19438. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19439. break;
  19440. case 2:
  19441. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19442. break;
  19443. case 3:
  19444. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19445. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19446. break;
  19447. }
  19448. light.id = parsedLight.id;
  19449. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19450. if (parsedLight.intensity !== undefined) {
  19451. light.intensity = parsedLight.intensity;
  19452. }
  19453. if (parsedLight.range) {
  19454. light.range = parsedLight.range;
  19455. }
  19456. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19457. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19458. if (parsedLight.excludedMeshesIds) {
  19459. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19460. }
  19461. // Parent
  19462. if (parsedLight.parentId) {
  19463. light._waitingParentId = parsedLight.parentId;
  19464. }
  19465. if (parsedLight.includedOnlyMeshesIds) {
  19466. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19467. }
  19468. // Animations
  19469. if (parsedLight.animations) {
  19470. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19471. var parsedAnimation = parsedLight.animations[animationIndex];
  19472. light.animations.push(parseAnimation(parsedAnimation));
  19473. }
  19474. }
  19475. if (parsedLight.autoAnimate) {
  19476. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19477. }
  19478. };
  19479. var parseCamera = function (parsedCamera, scene) {
  19480. var camera;
  19481. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19482. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19483. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19484. var alpha = parsedCamera.alpha;
  19485. var beta = parsedCamera.beta;
  19486. var radius = parsedCamera.radius;
  19487. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19488. var eye_space = parsedCamera.eye_space;
  19489. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  19490. }
  19491. else {
  19492. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19493. }
  19494. }
  19495. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19496. eye_space = parsedCamera.eye_space;
  19497. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  19498. }
  19499. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19500. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19501. }
  19502. else if (parsedCamera.type === "FollowCamera") {
  19503. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19504. camera.heightOffset = parsedCamera.heightOffset;
  19505. camera.radius = parsedCamera.radius;
  19506. camera.rotationOffset = parsedCamera.rotationOffset;
  19507. if (lockedTargetMesh)
  19508. camera.target = lockedTargetMesh;
  19509. }
  19510. else if (parsedCamera.type === "GamepadCamera") {
  19511. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19512. }
  19513. else if (parsedCamera.type === "OculusCamera") {
  19514. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  19515. }
  19516. else if (parsedCamera.type === "OculusGamepadCamera") {
  19517. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  19518. }
  19519. else if (parsedCamera.type === "TouchCamera") {
  19520. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19521. }
  19522. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19523. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19524. }
  19525. else if (parsedCamera.type === "WebVRCamera") {
  19526. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  19527. }
  19528. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  19529. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  19530. }
  19531. else {
  19532. // Free Camera is the default value
  19533. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19534. }
  19535. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19536. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19537. camera.lockedTarget = lockedTargetMesh;
  19538. }
  19539. camera.id = parsedCamera.id;
  19540. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19541. // Parent
  19542. if (parsedCamera.parentId) {
  19543. camera._waitingParentId = parsedCamera.parentId;
  19544. }
  19545. // Target
  19546. if (parsedCamera.target) {
  19547. if (camera.setTarget) {
  19548. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19549. }
  19550. else {
  19551. //For ArcRotate
  19552. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19553. }
  19554. }
  19555. else {
  19556. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19557. }
  19558. camera.fov = parsedCamera.fov;
  19559. camera.minZ = parsedCamera.minZ;
  19560. camera.maxZ = parsedCamera.maxZ;
  19561. camera.speed = parsedCamera.speed;
  19562. camera.inertia = parsedCamera.inertia;
  19563. camera.checkCollisions = parsedCamera.checkCollisions;
  19564. camera.applyGravity = parsedCamera.applyGravity;
  19565. if (parsedCamera.ellipsoid) {
  19566. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19567. }
  19568. // Animations
  19569. if (parsedCamera.animations) {
  19570. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19571. var parsedAnimation = parsedCamera.animations[animationIndex];
  19572. camera.animations.push(parseAnimation(parsedAnimation));
  19573. }
  19574. }
  19575. if (parsedCamera.autoAnimate) {
  19576. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19577. }
  19578. // Layer Mask
  19579. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19580. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19581. }
  19582. else {
  19583. camera.layerMask = 0xFFFFFFFF;
  19584. }
  19585. return camera;
  19586. };
  19587. var parseGeometry = function (parsedGeometry, scene) {
  19588. var id = parsedGeometry.id;
  19589. return scene.getGeometryByID(id);
  19590. };
  19591. var parseBox = function (parsedBox, scene) {
  19592. if (parseGeometry(parsedBox, scene)) {
  19593. return null; // null since geometry could be something else than a box...
  19594. }
  19595. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19596. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19597. scene.pushGeometry(box, true);
  19598. return box;
  19599. };
  19600. var parseSphere = function (parsedSphere, scene) {
  19601. if (parseGeometry(parsedSphere, scene)) {
  19602. return null; // null since geometry could be something else than a sphere...
  19603. }
  19604. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19605. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19606. scene.pushGeometry(sphere, true);
  19607. return sphere;
  19608. };
  19609. var parseCylinder = function (parsedCylinder, scene) {
  19610. if (parseGeometry(parsedCylinder, scene)) {
  19611. return null; // null since geometry could be something else than a cylinder...
  19612. }
  19613. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19614. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19615. scene.pushGeometry(cylinder, true);
  19616. return cylinder;
  19617. };
  19618. var parseTorus = function (parsedTorus, scene) {
  19619. if (parseGeometry(parsedTorus, scene)) {
  19620. return null; // null since geometry could be something else than a torus...
  19621. }
  19622. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19623. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19624. scene.pushGeometry(torus, true);
  19625. return torus;
  19626. };
  19627. var parseGround = function (parsedGround, scene) {
  19628. if (parseGeometry(parsedGround, scene)) {
  19629. return null; // null since geometry could be something else than a ground...
  19630. }
  19631. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19632. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19633. scene.pushGeometry(ground, true);
  19634. return ground;
  19635. };
  19636. var parsePlane = function (parsedPlane, scene) {
  19637. if (parseGeometry(parsedPlane, scene)) {
  19638. return null; // null since geometry could be something else than a plane...
  19639. }
  19640. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19641. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19642. scene.pushGeometry(plane, true);
  19643. return plane;
  19644. };
  19645. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19646. if (parseGeometry(parsedTorusKnot, scene)) {
  19647. return null; // null since geometry could be something else than a torusKnot...
  19648. }
  19649. 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);
  19650. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19651. scene.pushGeometry(torusKnot, true);
  19652. return torusKnot;
  19653. };
  19654. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19655. if (parseGeometry(parsedVertexData, scene)) {
  19656. return null; // null since geometry could be a primitive
  19657. }
  19658. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19659. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19660. if (parsedVertexData.delayLoadingFile) {
  19661. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19662. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19663. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19664. geometry._delayInfo = [];
  19665. if (parsedVertexData.hasUVs) {
  19666. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19667. }
  19668. if (parsedVertexData.hasUVs2) {
  19669. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19670. }
  19671. if (parsedVertexData.hasColors) {
  19672. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19673. }
  19674. if (parsedVertexData.hasMatricesIndices) {
  19675. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19676. }
  19677. if (parsedVertexData.hasMatricesWeights) {
  19678. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19679. }
  19680. geometry._delayLoadingFunction = importVertexData;
  19681. }
  19682. else {
  19683. importVertexData(parsedVertexData, geometry);
  19684. }
  19685. scene.pushGeometry(geometry, true);
  19686. return geometry;
  19687. };
  19688. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19689. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19690. mesh.id = parsedMesh.id;
  19691. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19692. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19693. if (parsedMesh.rotationQuaternion) {
  19694. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19695. }
  19696. else if (parsedMesh.rotation) {
  19697. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19698. }
  19699. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19700. if (parsedMesh.localMatrix) {
  19701. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19702. }
  19703. else if (parsedMesh.pivotMatrix) {
  19704. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19705. }
  19706. mesh.setEnabled(parsedMesh.isEnabled);
  19707. mesh.isVisible = parsedMesh.isVisible;
  19708. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19709. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19710. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19711. if (parsedMesh.applyFog !== undefined) {
  19712. mesh.applyFog = parsedMesh.applyFog;
  19713. }
  19714. if (parsedMesh.pickable !== undefined) {
  19715. mesh.isPickable = parsedMesh.pickable;
  19716. }
  19717. if (parsedMesh.alphaIndex !== undefined) {
  19718. mesh.alphaIndex = parsedMesh.alphaIndex;
  19719. }
  19720. mesh.receiveShadows = parsedMesh.receiveShadows;
  19721. mesh.billboardMode = parsedMesh.billboardMode;
  19722. if (parsedMesh.visibility !== undefined) {
  19723. mesh.visibility = parsedMesh.visibility;
  19724. }
  19725. mesh.checkCollisions = parsedMesh.checkCollisions;
  19726. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19727. // Parent
  19728. if (parsedMesh.parentId) {
  19729. mesh._waitingParentId = parsedMesh.parentId;
  19730. }
  19731. // Actions
  19732. if (parsedMesh.actions !== undefined) {
  19733. mesh._waitingActions = parsedMesh.actions;
  19734. }
  19735. // Geometry
  19736. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19737. if (parsedMesh.delayLoadingFile) {
  19738. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19739. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19740. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19741. if (parsedMesh._binaryInfo) {
  19742. mesh._binaryInfo = parsedMesh._binaryInfo;
  19743. }
  19744. mesh._delayInfo = [];
  19745. if (parsedMesh.hasUVs) {
  19746. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19747. }
  19748. if (parsedMesh.hasUVs2) {
  19749. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19750. }
  19751. if (parsedMesh.hasColors) {
  19752. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19753. }
  19754. if (parsedMesh.hasMatricesIndices) {
  19755. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19756. }
  19757. if (parsedMesh.hasMatricesWeights) {
  19758. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19759. }
  19760. mesh._delayLoadingFunction = importGeometry;
  19761. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19762. mesh._checkDelayState();
  19763. }
  19764. }
  19765. else {
  19766. importGeometry(parsedMesh, mesh);
  19767. }
  19768. // Material
  19769. if (parsedMesh.materialId) {
  19770. mesh.setMaterialByID(parsedMesh.materialId);
  19771. }
  19772. else {
  19773. mesh.material = null;
  19774. }
  19775. // Skeleton
  19776. if (parsedMesh.skeletonId > -1) {
  19777. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19778. }
  19779. // Physics
  19780. if (parsedMesh.physicsImpostor) {
  19781. if (!scene.isPhysicsEnabled()) {
  19782. scene.enablePhysics();
  19783. }
  19784. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19785. }
  19786. // Animations
  19787. if (parsedMesh.animations) {
  19788. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19789. var parsedAnimation = parsedMesh.animations[animationIndex];
  19790. mesh.animations.push(parseAnimation(parsedAnimation));
  19791. }
  19792. }
  19793. if (parsedMesh.autoAnimate) {
  19794. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19795. }
  19796. // Layer Mask
  19797. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19798. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19799. }
  19800. else {
  19801. mesh.layerMask = 0xFFFFFFFF;
  19802. }
  19803. // Instances
  19804. if (parsedMesh.instances) {
  19805. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19806. var parsedInstance = parsedMesh.instances[index];
  19807. var instance = mesh.createInstance(parsedInstance.name);
  19808. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19809. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19810. if (parsedInstance.rotationQuaternion) {
  19811. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19812. }
  19813. else if (parsedInstance.rotation) {
  19814. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19815. }
  19816. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19817. instance.checkCollisions = mesh.checkCollisions;
  19818. if (parsedMesh.animations) {
  19819. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19820. parsedAnimation = parsedMesh.animations[animationIndex];
  19821. instance.animations.push(parseAnimation(parsedAnimation));
  19822. }
  19823. }
  19824. }
  19825. }
  19826. return mesh;
  19827. };
  19828. var parseActions = function (parsedActions, object, scene) {
  19829. var actionManager = new BABYLON.ActionManager(scene);
  19830. if (object === null)
  19831. scene.actionManager = actionManager;
  19832. else
  19833. object.actionManager = actionManager;
  19834. // instanciate a new object
  19835. var instanciate = function (name, params) {
  19836. var newInstance = Object.create(BABYLON[name].prototype);
  19837. newInstance.constructor.apply(newInstance, params);
  19838. return newInstance;
  19839. };
  19840. var parseParameter = function (name, value, target, propertyPath) {
  19841. if (propertyPath === null) {
  19842. // String, boolean or float
  19843. var floatValue = parseFloat(value);
  19844. if (value === "true" || value === "false")
  19845. return value === "true";
  19846. else
  19847. return isNaN(floatValue) ? value : floatValue;
  19848. }
  19849. var effectiveTarget = propertyPath.split(".");
  19850. var values = value.split(",");
  19851. for (var i = 0; i < effectiveTarget.length; i++) {
  19852. target = target[effectiveTarget[i]];
  19853. }
  19854. // Return appropriate value with its type
  19855. if (target instanceof Boolean)
  19856. return values[0] === "true";
  19857. if (target instanceof String)
  19858. return values[0];
  19859. // Parameters with multiple values such as Vector3 etc.
  19860. var split = new Array();
  19861. for (var i = 0; i < values.length; i++)
  19862. split.push(parseFloat(values[i]));
  19863. if (target instanceof BABYLON.Vector3)
  19864. return BABYLON.Vector3.FromArray(split);
  19865. if (target instanceof BABYLON.Vector4)
  19866. return BABYLON.Vector4.FromArray(split);
  19867. if (target instanceof BABYLON.Color3)
  19868. return BABYLON.Color3.FromArray(split);
  19869. if (target instanceof BABYLON.Color4)
  19870. return BABYLON.Color4.FromArray(split);
  19871. return parseFloat(values[0]);
  19872. };
  19873. // traverse graph per trigger
  19874. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19875. if (combineArray === void 0) { combineArray = null; }
  19876. if (parsedAction.detached)
  19877. return;
  19878. var parameters = new Array();
  19879. var target = null;
  19880. var propertyPath = null;
  19881. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19882. // Parameters
  19883. if (parsedAction.type === 2)
  19884. parameters.push(actionManager);
  19885. else
  19886. parameters.push(trigger);
  19887. if (combine) {
  19888. var actions = new Array();
  19889. for (var j = 0; j < parsedAction.combine.length; j++) {
  19890. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19891. }
  19892. parameters.push(actions);
  19893. }
  19894. else {
  19895. for (var i = 0; i < parsedAction.properties.length; i++) {
  19896. var value = parsedAction.properties[i].value;
  19897. var name = parsedAction.properties[i].name;
  19898. if (name === "target")
  19899. value = target = scene.getNodeByName(value);
  19900. else if (name === "parent")
  19901. value = scene.getNodeByName(value);
  19902. else if (name === "sound")
  19903. value = scene.getSoundByName(value);
  19904. else if (name !== "propertyPath") {
  19905. if (parsedAction.type === 2 && name === "operator")
  19906. value = BABYLON.ValueCondition[value];
  19907. else
  19908. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19909. }
  19910. else {
  19911. propertyPath = value;
  19912. }
  19913. parameters.push(value);
  19914. }
  19915. }
  19916. parameters.push(condition);
  19917. // If interpolate value action
  19918. if (parsedAction.name === "InterpolateValueAction") {
  19919. var param = parameters[parameters.length - 2];
  19920. parameters[parameters.length - 1] = param;
  19921. parameters[parameters.length - 2] = condition;
  19922. }
  19923. // Action or condition(s) and not CombineAction
  19924. var newAction = instanciate(parsedAction.name, parameters);
  19925. if (combineArray === null) {
  19926. if (newAction instanceof BABYLON.Condition) {
  19927. condition = newAction;
  19928. newAction = action;
  19929. }
  19930. else {
  19931. condition = null;
  19932. if (action)
  19933. action.then(newAction);
  19934. else
  19935. actionManager.registerAction(newAction);
  19936. }
  19937. }
  19938. else {
  19939. combineArray.push(newAction);
  19940. }
  19941. for (var i = 0; i < parsedAction.children.length; i++)
  19942. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19943. };
  19944. for (var i = 0; i < parsedActions.children.length; i++) {
  19945. var triggerParams;
  19946. var trigger = parsedActions.children[i];
  19947. if (trigger.properties.length > 0) {
  19948. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  19949. }
  19950. else
  19951. triggerParams = BABYLON.ActionManager[trigger.name];
  19952. for (var j = 0; j < trigger.children.length; j++) {
  19953. if (!trigger.detached)
  19954. traverse(trigger.children[j], triggerParams, null, null);
  19955. }
  19956. }
  19957. };
  19958. var parseSound = function (parsedSound, scene, rootUrl) {
  19959. var soundName = parsedSound.name;
  19960. var soundUrl = rootUrl + soundName;
  19961. var options = {
  19962. autoplay: parsedSound.autoplay,
  19963. loop: parsedSound.loop,
  19964. volume: parsedSound.volume,
  19965. spatialSound: parsedSound.spatialSound,
  19966. maxDistance: parsedSound.maxDistance,
  19967. rolloffFactor: parsedSound.rolloffFactor,
  19968. refDistance: parsedSound.refDistance,
  19969. distanceModel: parsedSound.distanceModel,
  19970. playbackRate: parsedSound.playbackRate
  19971. };
  19972. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  19973. scene._removePendingData(newSound);
  19974. }, options);
  19975. scene._addPendingData(newSound);
  19976. if (parsedSound.position) {
  19977. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19978. newSound.setPosition(soundPosition);
  19979. }
  19980. if (parsedSound.isDirectional) {
  19981. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19982. if (parsedSound.localDirectionToMesh) {
  19983. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19984. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19985. }
  19986. }
  19987. if (parsedSound.connectedMeshId) {
  19988. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  19989. if (connectedMesh) {
  19990. newSound.attachToMesh(connectedMesh);
  19991. }
  19992. }
  19993. };
  19994. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19995. names = (names instanceof Array) ? names : [names];
  19996. for (var i in names) {
  19997. if (mesh.name === names[i]) {
  19998. hierarchyIds.push(mesh.id);
  19999. return true;
  20000. }
  20001. }
  20002. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20003. hierarchyIds.push(mesh.id);
  20004. return true;
  20005. }
  20006. return false;
  20007. };
  20008. var importVertexData = function (parsedVertexData, geometry) {
  20009. var vertexData = new BABYLON.VertexData();
  20010. // positions
  20011. var positions = parsedVertexData.positions;
  20012. if (positions) {
  20013. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20014. }
  20015. // normals
  20016. var normals = parsedVertexData.normals;
  20017. if (normals) {
  20018. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20019. }
  20020. // uvs
  20021. var uvs = parsedVertexData.uvs;
  20022. if (uvs) {
  20023. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20024. }
  20025. // uv2s
  20026. var uv2s = parsedVertexData.uv2s;
  20027. if (uv2s) {
  20028. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20029. }
  20030. // colors
  20031. var colors = parsedVertexData.colors;
  20032. if (colors) {
  20033. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20034. }
  20035. // matricesIndices
  20036. var matricesIndices = parsedVertexData.matricesIndices;
  20037. if (matricesIndices) {
  20038. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20039. }
  20040. // matricesWeights
  20041. var matricesWeights = parsedVertexData.matricesWeights;
  20042. if (matricesWeights) {
  20043. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20044. }
  20045. // indices
  20046. var indices = parsedVertexData.indices;
  20047. if (indices) {
  20048. vertexData.indices = indices;
  20049. }
  20050. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20051. };
  20052. var importGeometry = function (parsedGeometry, mesh) {
  20053. var scene = mesh.getScene();
  20054. // Geometry
  20055. var geometryId = parsedGeometry.geometryId;
  20056. if (geometryId) {
  20057. var geometry = scene.getGeometryByID(geometryId);
  20058. if (geometry) {
  20059. geometry.applyToMesh(mesh);
  20060. }
  20061. }
  20062. else if (parsedGeometry instanceof ArrayBuffer) {
  20063. var binaryInfo = mesh._binaryInfo;
  20064. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20065. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20066. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20067. }
  20068. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20069. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20070. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20071. }
  20072. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20073. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20074. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20075. }
  20076. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20077. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20078. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20079. }
  20080. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20081. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20082. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  20083. }
  20084. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20085. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20086. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20087. }
  20088. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20089. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20090. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20091. }
  20092. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20093. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20094. mesh.setIndices(indicesData);
  20095. }
  20096. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20097. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20098. mesh.subMeshes = [];
  20099. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20100. var materialIndex = subMeshesData[(i * 5) + 0];
  20101. var verticesStart = subMeshesData[(i * 5) + 1];
  20102. var verticesCount = subMeshesData[(i * 5) + 2];
  20103. var indexStart = subMeshesData[(i * 5) + 3];
  20104. var indexCount = subMeshesData[(i * 5) + 4];
  20105. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20106. }
  20107. }
  20108. }
  20109. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20110. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20111. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20112. if (parsedGeometry.uvs) {
  20113. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20114. }
  20115. if (parsedGeometry.uvs2) {
  20116. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20117. }
  20118. if (parsedGeometry.colors) {
  20119. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20120. }
  20121. if (parsedGeometry.matricesIndices) {
  20122. if (!parsedGeometry.matricesIndices._isExpanded) {
  20123. var floatIndices = [];
  20124. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20125. var matricesIndex = parsedGeometry.matricesIndices[i];
  20126. floatIndices.push(matricesIndex & 0x000000FF);
  20127. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20128. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20129. floatIndices.push(matricesIndex >> 24);
  20130. }
  20131. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20132. }
  20133. else {
  20134. delete parsedGeometry.matricesIndices._isExpanded;
  20135. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20136. }
  20137. }
  20138. if (parsedGeometry.matricesWeights) {
  20139. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20140. }
  20141. mesh.setIndices(parsedGeometry.indices);
  20142. // SubMeshes
  20143. if (parsedGeometry.subMeshes) {
  20144. mesh.subMeshes = [];
  20145. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20146. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20147. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20148. }
  20149. }
  20150. }
  20151. // Flat shading
  20152. if (mesh._shouldGenerateFlatShading) {
  20153. mesh.convertToFlatShadedMesh();
  20154. delete mesh._shouldGenerateFlatShading;
  20155. }
  20156. // Update
  20157. mesh.computeWorldMatrix(true);
  20158. // Octree
  20159. if (scene._selectionOctree) {
  20160. scene._selectionOctree.addMesh(mesh);
  20161. }
  20162. };
  20163. BABYLON.SceneLoader.RegisterPlugin({
  20164. extensions: ".babylon",
  20165. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20166. var parsedData = JSON.parse(data);
  20167. var loadedSkeletonsIds = [];
  20168. var loadedMaterialsIds = [];
  20169. var hierarchyIds = [];
  20170. for (var index = 0; index < parsedData.meshes.length; index++) {
  20171. var parsedMesh = parsedData.meshes[index];
  20172. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20173. if (meshesNames instanceof Array) {
  20174. // Remove found mesh name from list.
  20175. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20176. }
  20177. // Material ?
  20178. if (parsedMesh.materialId) {
  20179. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20180. if (!materialFound) {
  20181. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20182. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20183. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20184. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20185. var subMatId = parsedMultiMaterial.materials[matIndex];
  20186. loadedMaterialsIds.push(subMatId);
  20187. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20188. }
  20189. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20190. parseMultiMaterial(parsedMultiMaterial, scene);
  20191. materialFound = true;
  20192. break;
  20193. }
  20194. }
  20195. }
  20196. if (!materialFound) {
  20197. loadedMaterialsIds.push(parsedMesh.materialId);
  20198. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  20199. }
  20200. }
  20201. // Skeleton ?
  20202. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20203. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20204. if (!skeletonAlreadyLoaded) {
  20205. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20206. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20207. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20208. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20209. loadedSkeletonsIds.push(parsedSkeleton.id);
  20210. }
  20211. }
  20212. }
  20213. }
  20214. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20215. meshes.push(mesh);
  20216. }
  20217. }
  20218. for (index = 0; index < scene.meshes.length; index++) {
  20219. var currentMesh = scene.meshes[index];
  20220. if (currentMesh._waitingParentId) {
  20221. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20222. currentMesh._waitingParentId = undefined;
  20223. }
  20224. }
  20225. // Particles
  20226. if (parsedData.particleSystems) {
  20227. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20228. var parsedParticleSystem = parsedData.particleSystems[index];
  20229. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20230. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20231. }
  20232. }
  20233. }
  20234. return true;
  20235. },
  20236. load: function (scene, data, rootUrl) {
  20237. var parsedData = JSON.parse(data);
  20238. // Scene
  20239. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20240. scene.autoClear = parsedData.autoClear;
  20241. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20242. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20243. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20244. // Fog
  20245. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20246. scene.fogMode = parsedData.fogMode;
  20247. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20248. scene.fogStart = parsedData.fogStart;
  20249. scene.fogEnd = parsedData.fogEnd;
  20250. scene.fogDensity = parsedData.fogDensity;
  20251. }
  20252. for (var index = 0; index < parsedData.lights.length; index++) {
  20253. var parsedLight = parsedData.lights[index];
  20254. parseLight(parsedLight, scene);
  20255. }
  20256. // Materials
  20257. if (parsedData.materials) {
  20258. for (index = 0; index < parsedData.materials.length; index++) {
  20259. var parsedMaterial = parsedData.materials[index];
  20260. parseMaterial(parsedMaterial, scene, rootUrl);
  20261. }
  20262. }
  20263. if (parsedData.multiMaterials) {
  20264. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20265. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20266. parseMultiMaterial(parsedMultiMaterial, scene);
  20267. }
  20268. }
  20269. // Skeletons
  20270. if (parsedData.skeletons) {
  20271. for (index = 0; index < parsedData.skeletons.length; index++) {
  20272. var parsedSkeleton = parsedData.skeletons[index];
  20273. parseSkeleton(parsedSkeleton, scene);
  20274. }
  20275. }
  20276. // Geometries
  20277. var geometries = parsedData.geometries;
  20278. if (geometries) {
  20279. // Boxes
  20280. var boxes = geometries.boxes;
  20281. if (boxes) {
  20282. for (index = 0; index < boxes.length; index++) {
  20283. var parsedBox = boxes[index];
  20284. parseBox(parsedBox, scene);
  20285. }
  20286. }
  20287. // Spheres
  20288. var spheres = geometries.spheres;
  20289. if (spheres) {
  20290. for (index = 0; index < spheres.length; index++) {
  20291. var parsedSphere = spheres[index];
  20292. parseSphere(parsedSphere, scene);
  20293. }
  20294. }
  20295. // Cylinders
  20296. var cylinders = geometries.cylinders;
  20297. if (cylinders) {
  20298. for (index = 0; index < cylinders.length; index++) {
  20299. var parsedCylinder = cylinders[index];
  20300. parseCylinder(parsedCylinder, scene);
  20301. }
  20302. }
  20303. // Toruses
  20304. var toruses = geometries.toruses;
  20305. if (toruses) {
  20306. for (index = 0; index < toruses.length; index++) {
  20307. var parsedTorus = toruses[index];
  20308. parseTorus(parsedTorus, scene);
  20309. }
  20310. }
  20311. // Grounds
  20312. var grounds = geometries.grounds;
  20313. if (grounds) {
  20314. for (index = 0; index < grounds.length; index++) {
  20315. var parsedGround = grounds[index];
  20316. parseGround(parsedGround, scene);
  20317. }
  20318. }
  20319. // Planes
  20320. var planes = geometries.planes;
  20321. if (planes) {
  20322. for (index = 0; index < planes.length; index++) {
  20323. var parsedPlane = planes[index];
  20324. parsePlane(parsedPlane, scene);
  20325. }
  20326. }
  20327. // TorusKnots
  20328. var torusKnots = geometries.torusKnots;
  20329. if (torusKnots) {
  20330. for (index = 0; index < torusKnots.length; index++) {
  20331. var parsedTorusKnot = torusKnots[index];
  20332. parseTorusKnot(parsedTorusKnot, scene);
  20333. }
  20334. }
  20335. // VertexData
  20336. var vertexData = geometries.vertexData;
  20337. if (vertexData) {
  20338. for (index = 0; index < vertexData.length; index++) {
  20339. var parsedVertexData = vertexData[index];
  20340. parseVertexData(parsedVertexData, scene, rootUrl);
  20341. }
  20342. }
  20343. }
  20344. for (index = 0; index < parsedData.meshes.length; index++) {
  20345. var parsedMesh = parsedData.meshes[index];
  20346. parseMesh(parsedMesh, scene, rootUrl);
  20347. }
  20348. for (index = 0; index < parsedData.cameras.length; index++) {
  20349. var parsedCamera = parsedData.cameras[index];
  20350. parseCamera(parsedCamera, scene);
  20351. }
  20352. if (parsedData.activeCameraID) {
  20353. scene.setActiveCameraByID(parsedData.activeCameraID);
  20354. }
  20355. for (index = 0; index < scene.cameras.length; index++) {
  20356. var camera = scene.cameras[index];
  20357. if (camera._waitingParentId) {
  20358. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20359. camera._waitingParentId = undefined;
  20360. }
  20361. }
  20362. for (index = 0; index < scene.lights.length; index++) {
  20363. var light = scene.lights[index];
  20364. if (light._waitingParentId) {
  20365. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20366. light._waitingParentId = undefined;
  20367. }
  20368. }
  20369. // Sounds
  20370. if (parsedData.sounds) {
  20371. for (index = 0; index < parsedData.sounds.length; index++) {
  20372. var parsedSound = parsedData.sounds[index];
  20373. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20374. parseSound(parsedSound, scene, rootUrl);
  20375. }
  20376. else {
  20377. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20378. }
  20379. }
  20380. }
  20381. for (index = 0; index < scene.meshes.length; index++) {
  20382. var mesh = scene.meshes[index];
  20383. if (mesh._waitingParentId) {
  20384. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20385. mesh._waitingParentId = undefined;
  20386. }
  20387. if (mesh._waitingActions) {
  20388. parseActions(mesh._waitingActions, mesh, scene);
  20389. mesh._waitingActions = undefined;
  20390. }
  20391. }
  20392. // Particles Systems
  20393. if (parsedData.particleSystems) {
  20394. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20395. var parsedParticleSystem = parsedData.particleSystems[index];
  20396. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20397. }
  20398. }
  20399. // Lens flares
  20400. if (parsedData.lensFlareSystems) {
  20401. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20402. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20403. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20404. }
  20405. }
  20406. // Shadows
  20407. if (parsedData.shadowGenerators) {
  20408. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20409. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20410. parseShadowGenerator(parsedShadowGenerator, scene);
  20411. }
  20412. }
  20413. // Actions (scene)
  20414. if (parsedData.actions) {
  20415. parseActions(parsedData.actions, null, scene);
  20416. }
  20417. // Finish
  20418. return true;
  20419. }
  20420. });
  20421. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20422. })(BABYLON || (BABYLON = {}));
  20423. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  20424. (function (BABYLON) {
  20425. // Unique ID when we import meshes from Babylon to CSG
  20426. var currentCSGMeshId = 0;
  20427. // # class Vertex
  20428. // Represents a vertex of a polygon. Use your own vertex class instead of this
  20429. // one to provide additional features like texture coordinates and vertex
  20430. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  20431. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  20432. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  20433. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  20434. // is not used anywhere else.
  20435. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  20436. var Vertex = (function () {
  20437. function Vertex(pos, normal, uv) {
  20438. this.pos = pos;
  20439. this.normal = normal;
  20440. this.uv = uv;
  20441. }
  20442. Vertex.prototype.clone = function () {
  20443. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  20444. };
  20445. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  20446. // orientation of a polygon is flipped.
  20447. Vertex.prototype.flip = function () {
  20448. this.normal = this.normal.scale(-1);
  20449. };
  20450. // Create a new vertex between this vertex and `other` by linearly
  20451. // interpolating all properties using a parameter of `t`. Subclasses should
  20452. // override this to interpolate additional properties.
  20453. Vertex.prototype.interpolate = function (other, t) {
  20454. 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));
  20455. };
  20456. return Vertex;
  20457. })();
  20458. // # class Plane
  20459. // Represents a plane in 3D space.
  20460. var Plane = (function () {
  20461. function Plane(normal, w) {
  20462. this.normal = normal;
  20463. this.w = w;
  20464. }
  20465. Plane.FromPoints = function (a, b, c) {
  20466. var v0 = c.subtract(a);
  20467. var v1 = b.subtract(a);
  20468. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  20469. return null;
  20470. }
  20471. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  20472. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  20473. };
  20474. Plane.prototype.clone = function () {
  20475. return new Plane(this.normal.clone(), this.w);
  20476. };
  20477. Plane.prototype.flip = function () {
  20478. this.normal.scaleInPlace(-1);
  20479. this.w = -this.w;
  20480. };
  20481. // Split `polygon` by this plane if needed, then put the polygon or polygon
  20482. // fragments in the appropriate lists. Coplanar polygons go into either
  20483. // `coplanarFront` or `coplanarBack` depending on their orientation with
  20484. // respect to this plane. Polygons in front or in back of this plane go into
  20485. // either `front` or `back`.
  20486. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  20487. var COPLANAR = 0;
  20488. var FRONT = 1;
  20489. var BACK = 2;
  20490. var SPANNING = 3;
  20491. // Classify each point as well as the entire polygon into one of the above
  20492. // four classes.
  20493. var polygonType = 0;
  20494. var types = [];
  20495. for (var i = 0; i < polygon.vertices.length; i++) {
  20496. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  20497. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  20498. polygonType |= type;
  20499. types.push(type);
  20500. }
  20501. switch (polygonType) {
  20502. case COPLANAR:
  20503. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  20504. break;
  20505. case FRONT:
  20506. front.push(polygon);
  20507. break;
  20508. case BACK:
  20509. back.push(polygon);
  20510. break;
  20511. case SPANNING:
  20512. var f = [], b = [];
  20513. for (i = 0; i < polygon.vertices.length; i++) {
  20514. var j = (i + 1) % polygon.vertices.length;
  20515. var ti = types[i], tj = types[j];
  20516. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  20517. if (ti != BACK)
  20518. f.push(vi);
  20519. if (ti != FRONT)
  20520. b.push(ti != BACK ? vi.clone() : vi);
  20521. if ((ti | tj) == SPANNING) {
  20522. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  20523. var v = vi.interpolate(vj, t);
  20524. f.push(v);
  20525. b.push(v.clone());
  20526. }
  20527. }
  20528. if (f.length >= 3) {
  20529. var poly = new Polygon(f, polygon.shared);
  20530. if (poly.plane)
  20531. front.push(poly);
  20532. }
  20533. if (b.length >= 3) {
  20534. poly = new Polygon(b, polygon.shared);
  20535. if (poly.plane)
  20536. back.push(poly);
  20537. }
  20538. break;
  20539. }
  20540. };
  20541. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  20542. // point is on the plane.
  20543. Plane.EPSILON = 1e-5;
  20544. return Plane;
  20545. })();
  20546. // # class Polygon
  20547. // Represents a convex polygon. The vertices used to initialize a polygon must
  20548. // be coplanar and form a convex loop.
  20549. //
  20550. // Each convex polygon has a `shared` property, which is shared between all
  20551. // polygons that are clones of each other or were split from the same polygon.
  20552. // This can be used to define per-polygon properties (such as surface color).
  20553. var Polygon = (function () {
  20554. function Polygon(vertices, shared) {
  20555. this.vertices = vertices;
  20556. this.shared = shared;
  20557. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  20558. }
  20559. Polygon.prototype.clone = function () {
  20560. var vertices = this.vertices.map(function (v) { return v.clone(); });
  20561. return new Polygon(vertices, this.shared);
  20562. };
  20563. Polygon.prototype.flip = function () {
  20564. this.vertices.reverse().map(function (v) {
  20565. v.flip();
  20566. });
  20567. this.plane.flip();
  20568. };
  20569. return Polygon;
  20570. })();
  20571. // # class Node
  20572. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  20573. // by picking a polygon to split along. That polygon (and all other coplanar
  20574. // polygons) are added directly to that node and the other polygons are added to
  20575. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  20576. // no distinction between internal and leaf nodes.
  20577. var Node = (function () {
  20578. function Node(polygons) {
  20579. this.plane = null;
  20580. this.front = null;
  20581. this.back = null;
  20582. this.polygons = [];
  20583. if (polygons) {
  20584. this.build(polygons);
  20585. }
  20586. }
  20587. Node.prototype.clone = function () {
  20588. var node = new Node();
  20589. node.plane = this.plane && this.plane.clone();
  20590. node.front = this.front && this.front.clone();
  20591. node.back = this.back && this.back.clone();
  20592. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  20593. return node;
  20594. };
  20595. // Convert solid space to empty space and empty space to solid space.
  20596. Node.prototype.invert = function () {
  20597. for (var i = 0; i < this.polygons.length; i++) {
  20598. this.polygons[i].flip();
  20599. }
  20600. if (this.plane) {
  20601. this.plane.flip();
  20602. }
  20603. if (this.front) {
  20604. this.front.invert();
  20605. }
  20606. if (this.back) {
  20607. this.back.invert();
  20608. }
  20609. var temp = this.front;
  20610. this.front = this.back;
  20611. this.back = temp;
  20612. };
  20613. // Recursively remove all polygons in `polygons` that are inside this BSP
  20614. // tree.
  20615. Node.prototype.clipPolygons = function (polygons) {
  20616. if (!this.plane)
  20617. return polygons.slice();
  20618. var front = [], back = [];
  20619. for (var i = 0; i < polygons.length; i++) {
  20620. this.plane.splitPolygon(polygons[i], front, back, front, back);
  20621. }
  20622. if (this.front) {
  20623. front = this.front.clipPolygons(front);
  20624. }
  20625. if (this.back) {
  20626. back = this.back.clipPolygons(back);
  20627. }
  20628. else {
  20629. back = [];
  20630. }
  20631. return front.concat(back);
  20632. };
  20633. // Remove all polygons in this BSP tree that are inside the other BSP tree
  20634. // `bsp`.
  20635. Node.prototype.clipTo = function (bsp) {
  20636. this.polygons = bsp.clipPolygons(this.polygons);
  20637. if (this.front)
  20638. this.front.clipTo(bsp);
  20639. if (this.back)
  20640. this.back.clipTo(bsp);
  20641. };
  20642. // Return a list of all polygons in this BSP tree.
  20643. Node.prototype.allPolygons = function () {
  20644. var polygons = this.polygons.slice();
  20645. if (this.front)
  20646. polygons = polygons.concat(this.front.allPolygons());
  20647. if (this.back)
  20648. polygons = polygons.concat(this.back.allPolygons());
  20649. return polygons;
  20650. };
  20651. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  20652. // new polygons are filtered down to the bottom of the tree and become new
  20653. // nodes there. Each set of polygons is partitioned using the first polygon
  20654. // (no heuristic is used to pick a good split).
  20655. Node.prototype.build = function (polygons) {
  20656. if (!polygons.length)
  20657. return;
  20658. if (!this.plane)
  20659. this.plane = polygons[0].plane.clone();
  20660. var front = [], back = [];
  20661. for (var i = 0; i < polygons.length; i++) {
  20662. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  20663. }
  20664. if (front.length) {
  20665. if (!this.front)
  20666. this.front = new Node();
  20667. this.front.build(front);
  20668. }
  20669. if (back.length) {
  20670. if (!this.back)
  20671. this.back = new Node();
  20672. this.back.build(back);
  20673. }
  20674. };
  20675. return Node;
  20676. })();
  20677. var CSG = (function () {
  20678. function CSG() {
  20679. this.polygons = new Array();
  20680. }
  20681. // Convert BABYLON.Mesh to BABYLON.CSG
  20682. CSG.FromMesh = function (mesh) {
  20683. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  20684. if (mesh instanceof BABYLON.Mesh) {
  20685. mesh.computeWorldMatrix(true);
  20686. var matrix = mesh.getWorldMatrix();
  20687. var meshPosition = mesh.position.clone();
  20688. var meshRotation = mesh.rotation.clone();
  20689. var meshScaling = mesh.scaling.clone();
  20690. }
  20691. else {
  20692. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  20693. }
  20694. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20695. var subMeshes = mesh.subMeshes;
  20696. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  20697. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  20698. vertices = [];
  20699. for (var j = 0; j < 3; j++) {
  20700. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  20701. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  20702. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  20703. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  20704. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  20705. vertex = new Vertex(position, normal, uv);
  20706. vertices.push(vertex);
  20707. }
  20708. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  20709. // To handle the case of degenerated triangle
  20710. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  20711. if (polygon.plane)
  20712. polygons.push(polygon);
  20713. }
  20714. }
  20715. var csg = CSG.FromPolygons(polygons);
  20716. csg.matrix = matrix;
  20717. csg.position = meshPosition;
  20718. csg.rotation = meshRotation;
  20719. csg.scaling = meshScaling;
  20720. currentCSGMeshId++;
  20721. return csg;
  20722. };
  20723. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  20724. CSG.FromPolygons = function (polygons) {
  20725. var csg = new BABYLON.CSG();
  20726. csg.polygons = polygons;
  20727. return csg;
  20728. };
  20729. CSG.prototype.clone = function () {
  20730. var csg = new BABYLON.CSG();
  20731. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  20732. csg.copyTransformAttributes(this);
  20733. return csg;
  20734. };
  20735. CSG.prototype.toPolygons = function () {
  20736. return this.polygons;
  20737. };
  20738. CSG.prototype.union = function (csg) {
  20739. var a = new Node(this.clone().polygons);
  20740. var b = new Node(csg.clone().polygons);
  20741. a.clipTo(b);
  20742. b.clipTo(a);
  20743. b.invert();
  20744. b.clipTo(a);
  20745. b.invert();
  20746. a.build(b.allPolygons());
  20747. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20748. };
  20749. CSG.prototype.unionInPlace = function (csg) {
  20750. var a = new Node(this.polygons);
  20751. var b = new Node(csg.polygons);
  20752. a.clipTo(b);
  20753. b.clipTo(a);
  20754. b.invert();
  20755. b.clipTo(a);
  20756. b.invert();
  20757. a.build(b.allPolygons());
  20758. this.polygons = a.allPolygons();
  20759. };
  20760. CSG.prototype.subtract = function (csg) {
  20761. var a = new Node(this.clone().polygons);
  20762. var b = new Node(csg.clone().polygons);
  20763. a.invert();
  20764. a.clipTo(b);
  20765. b.clipTo(a);
  20766. b.invert();
  20767. b.clipTo(a);
  20768. b.invert();
  20769. a.build(b.allPolygons());
  20770. a.invert();
  20771. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20772. };
  20773. CSG.prototype.subtractInPlace = function (csg) {
  20774. var a = new Node(this.polygons);
  20775. var b = new Node(csg.polygons);
  20776. a.invert();
  20777. a.clipTo(b);
  20778. b.clipTo(a);
  20779. b.invert();
  20780. b.clipTo(a);
  20781. b.invert();
  20782. a.build(b.allPolygons());
  20783. a.invert();
  20784. this.polygons = a.allPolygons();
  20785. };
  20786. CSG.prototype.intersect = function (csg) {
  20787. var a = new Node(this.clone().polygons);
  20788. var b = new Node(csg.clone().polygons);
  20789. a.invert();
  20790. b.clipTo(a);
  20791. b.invert();
  20792. a.clipTo(b);
  20793. b.clipTo(a);
  20794. a.build(b.allPolygons());
  20795. a.invert();
  20796. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20797. };
  20798. CSG.prototype.intersectInPlace = function (csg) {
  20799. var a = new Node(this.polygons);
  20800. var b = new Node(csg.polygons);
  20801. a.invert();
  20802. b.clipTo(a);
  20803. b.invert();
  20804. a.clipTo(b);
  20805. b.clipTo(a);
  20806. a.build(b.allPolygons());
  20807. a.invert();
  20808. this.polygons = a.allPolygons();
  20809. };
  20810. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  20811. // not modified.
  20812. CSG.prototype.inverse = function () {
  20813. var csg = this.clone();
  20814. csg.inverseInPlace();
  20815. return csg;
  20816. };
  20817. CSG.prototype.inverseInPlace = function () {
  20818. this.polygons.map(function (p) {
  20819. p.flip();
  20820. });
  20821. };
  20822. // This is used to keep meshes transformations so they can be restored
  20823. // when we build back a Babylon Mesh
  20824. // NB : All CSG operations are performed in world coordinates
  20825. CSG.prototype.copyTransformAttributes = function (csg) {
  20826. this.matrix = csg.matrix;
  20827. this.position = csg.position;
  20828. this.rotation = csg.rotation;
  20829. this.scaling = csg.scaling;
  20830. return this;
  20831. };
  20832. // Build Raw mesh from CSG
  20833. // Coordinates here are in world space
  20834. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  20835. var matrix = this.matrix.clone();
  20836. matrix.invert();
  20837. 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;
  20838. if (keepSubMeshes) {
  20839. // Sort Polygons, since subMeshes are indices range
  20840. polygons.sort(function (a, b) {
  20841. if (a.shared.meshId === b.shared.meshId) {
  20842. return a.shared.subMeshId - b.shared.subMeshId;
  20843. }
  20844. else {
  20845. return a.shared.meshId - b.shared.meshId;
  20846. }
  20847. });
  20848. }
  20849. for (var i = 0, il = polygons.length; i < il; i++) {
  20850. polygon = polygons[i];
  20851. // Building SubMeshes
  20852. if (!subMesh_dict[polygon.shared.meshId]) {
  20853. subMesh_dict[polygon.shared.meshId] = {};
  20854. }
  20855. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  20856. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  20857. indexStart: +Infinity,
  20858. indexEnd: -Infinity,
  20859. materialIndex: polygon.shared.materialIndex
  20860. };
  20861. }
  20862. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  20863. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  20864. polygonIndices[0] = 0;
  20865. polygonIndices[1] = j - 1;
  20866. polygonIndices[2] = j;
  20867. for (var k = 0; k < 3; k++) {
  20868. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  20869. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  20870. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  20871. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  20872. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  20873. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  20874. // Check if 2 points can be merged
  20875. 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)) {
  20876. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  20877. uvs.push(uv.x, uv.y);
  20878. normals.push(normal.x, normal.y, normal.z);
  20879. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  20880. }
  20881. indices.push(vertex_idx);
  20882. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  20883. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  20884. currentIndex++;
  20885. }
  20886. }
  20887. }
  20888. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  20889. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20890. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  20891. mesh.setIndices(indices);
  20892. if (keepSubMeshes) {
  20893. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  20894. var materialIndexOffset = 0, materialMaxIndex;
  20895. mesh.subMeshes.length = 0;
  20896. for (var m in subMesh_dict) {
  20897. materialMaxIndex = -1;
  20898. for (var sm in subMesh_dict[m]) {
  20899. subMesh_obj = subMesh_dict[m][sm];
  20900. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  20901. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  20902. }
  20903. materialIndexOffset += ++materialMaxIndex;
  20904. }
  20905. }
  20906. return mesh;
  20907. };
  20908. // Build Mesh from CSG taking material and transforms into account
  20909. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  20910. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  20911. mesh.material = material;
  20912. mesh.position.copyFrom(this.position);
  20913. mesh.rotation.copyFrom(this.rotation);
  20914. mesh.scaling.copyFrom(this.scaling);
  20915. mesh.computeWorldMatrix(true);
  20916. return mesh;
  20917. };
  20918. return CSG;
  20919. })();
  20920. BABYLON.CSG = CSG;
  20921. })(BABYLON || (BABYLON = {}));
  20922. //# sourceMappingURL=babylon.csg.js.map
  20923. var BABYLON;
  20924. (function (BABYLON) {
  20925. var OculusDistortionCorrectionPostProcess = (function (_super) {
  20926. __extends(OculusDistortionCorrectionPostProcess, _super);
  20927. //ANY
  20928. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  20929. var _this = this;
  20930. _super.call(this, name, "oculusDistortionCorrection", [
  20931. 'LensCenter',
  20932. 'Scale',
  20933. 'ScaleIn',
  20934. 'HmdWarpParam'
  20935. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  20936. this._isRightEye = isRightEye;
  20937. this._distortionFactors = cameraSettings.DistortionK;
  20938. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  20939. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  20940. this.onSizeChanged = function () {
  20941. _this.aspectRatio = _this.width * .5 / _this.height;
  20942. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  20943. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  20944. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  20945. };
  20946. this.onApply = function (effect) {
  20947. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  20948. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  20949. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  20950. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  20951. };
  20952. }
  20953. return OculusDistortionCorrectionPostProcess;
  20954. })(BABYLON.PostProcess);
  20955. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  20956. })(BABYLON || (BABYLON = {}));
  20957. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  20958. // 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
  20959. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  20960. var BABYLON;
  20961. (function (BABYLON) {
  20962. (function (JoystickAxis) {
  20963. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  20964. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  20965. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  20966. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  20967. var JoystickAxis = BABYLON.JoystickAxis;
  20968. var VirtualJoystick = (function () {
  20969. function VirtualJoystick(leftJoystick) {
  20970. var _this = this;
  20971. if (leftJoystick) {
  20972. this._leftJoystick = true;
  20973. }
  20974. else {
  20975. this._leftJoystick = false;
  20976. }
  20977. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  20978. VirtualJoystick._globalJoystickIndex++;
  20979. // By default left & right arrow keys are moving the X
  20980. // and up & down keys are moving the Y
  20981. this._axisTargetedByLeftAndRight = 0 /* X */;
  20982. this._axisTargetedByUpAndDown = 1 /* Y */;
  20983. this.reverseLeftRight = false;
  20984. this.reverseUpDown = false;
  20985. // collections of pointers
  20986. this._touches = new BABYLON.VirtualJoystick.Collection();
  20987. this.deltaPosition = BABYLON.Vector3.Zero();
  20988. this._joystickSensibility = 25;
  20989. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20990. this._rotationSpeed = 25;
  20991. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  20992. this._rotateOnAxisRelativeToMesh = false;
  20993. // injecting a canvas element on top of the canvas 3D game
  20994. if (!VirtualJoystick.vjCanvas) {
  20995. window.addEventListener("resize", function () {
  20996. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20997. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20998. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  20999. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  21000. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  21001. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  21002. }, false);
  21003. VirtualJoystick.vjCanvas = document.createElement("canvas");
  21004. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21005. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21006. VirtualJoystick.vjCanvas.width = window.innerWidth;
  21007. VirtualJoystick.vjCanvas.height = window.innerHeight;
  21008. VirtualJoystick.vjCanvas.style.width = "100%";
  21009. VirtualJoystick.vjCanvas.style.height = "100%";
  21010. VirtualJoystick.vjCanvas.style.position = "absolute";
  21011. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  21012. VirtualJoystick.vjCanvas.style.top = "0px";
  21013. VirtualJoystick.vjCanvas.style.left = "0px";
  21014. VirtualJoystick.vjCanvas.style.zIndex = "5";
  21015. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  21016. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  21017. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  21018. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21019. document.body.appendChild(VirtualJoystick.vjCanvas);
  21020. }
  21021. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  21022. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  21023. this.pressed = false;
  21024. // default joystick color
  21025. this._joystickColor = "cyan";
  21026. this._joystickPointerID = -1;
  21027. // current joystick position
  21028. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  21029. // origin joystick position
  21030. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  21031. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  21032. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  21033. _this._onPointerDown(evt);
  21034. }, false);
  21035. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  21036. _this._onPointerMove(evt);
  21037. }, false);
  21038. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  21039. _this._onPointerUp(evt);
  21040. }, false);
  21041. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  21042. _this._onPointerUp(evt);
  21043. }, false);
  21044. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  21045. evt.preventDefault(); // Disables system menu
  21046. }, false);
  21047. requestAnimationFrame(function () {
  21048. _this._drawVirtualJoystick();
  21049. });
  21050. }
  21051. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  21052. this._joystickSensibility = newJoystickSensibility;
  21053. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21054. };
  21055. VirtualJoystick.prototype._onPointerDown = function (e) {
  21056. var positionOnScreenCondition;
  21057. e.preventDefault();
  21058. if (this._leftJoystick === true) {
  21059. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  21060. }
  21061. else {
  21062. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  21063. }
  21064. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  21065. // First contact will be dedicated to the virtual joystick
  21066. this._joystickPointerID = e.pointerId;
  21067. this._joystickPointerStartPos.x = e.clientX;
  21068. this._joystickPointerStartPos.y = e.clientY;
  21069. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  21070. this._deltaJoystickVector.x = 0;
  21071. this._deltaJoystickVector.y = 0;
  21072. this.pressed = true;
  21073. this._touches.add(e.pointerId.toString(), e);
  21074. }
  21075. else {
  21076. // You can only trigger the action buttons with a joystick declared
  21077. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  21078. this._action();
  21079. this._touches.add(e.pointerId.toString(), e);
  21080. }
  21081. }
  21082. };
  21083. VirtualJoystick.prototype._onPointerMove = function (e) {
  21084. // If the current pointer is the one associated to the joystick (first touch contact)
  21085. if (this._joystickPointerID == e.pointerId) {
  21086. this._joystickPointerPos.x = e.clientX;
  21087. this._joystickPointerPos.y = e.clientY;
  21088. this._deltaJoystickVector = this._joystickPointerPos.clone();
  21089. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  21090. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  21091. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  21092. switch (this._axisTargetedByLeftAndRight) {
  21093. case 0 /* X */:
  21094. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  21095. break;
  21096. case 1 /* Y */:
  21097. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  21098. break;
  21099. case 2 /* Z */:
  21100. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  21101. break;
  21102. }
  21103. var directionUpDown = this.reverseUpDown ? 1 : -1;
  21104. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  21105. switch (this._axisTargetedByUpAndDown) {
  21106. case 0 /* X */:
  21107. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  21108. break;
  21109. case 1 /* Y */:
  21110. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  21111. break;
  21112. case 2 /* Z */:
  21113. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  21114. break;
  21115. }
  21116. }
  21117. else {
  21118. if (this._touches.item(e.pointerId.toString())) {
  21119. this._touches.item(e.pointerId.toString()).x = e.clientX;
  21120. this._touches.item(e.pointerId.toString()).y = e.clientY;
  21121. }
  21122. }
  21123. };
  21124. VirtualJoystick.prototype._onPointerUp = function (e) {
  21125. this._clearCanvas();
  21126. if (this._joystickPointerID == e.pointerId) {
  21127. this._joystickPointerID = -1;
  21128. this.pressed = false;
  21129. }
  21130. this._deltaJoystickVector.x = 0;
  21131. this._deltaJoystickVector.y = 0;
  21132. this._touches.remove(e.pointerId.toString());
  21133. };
  21134. /**
  21135. * Change the color of the virtual joystick
  21136. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  21137. */
  21138. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  21139. this._joystickColor = newColor;
  21140. };
  21141. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  21142. this._action = action;
  21143. };
  21144. // Define which axis you'd like to control for left & right
  21145. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  21146. switch (axis) {
  21147. case 0 /* X */:
  21148. case 1 /* Y */:
  21149. case 2 /* Z */:
  21150. this._axisTargetedByLeftAndRight = axis;
  21151. break;
  21152. default:
  21153. this._axisTargetedByLeftAndRight = 0 /* X */;
  21154. break;
  21155. }
  21156. };
  21157. // Define which axis you'd like to control for up & down
  21158. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  21159. switch (axis) {
  21160. case 0 /* X */:
  21161. case 1 /* Y */:
  21162. case 2 /* Z */:
  21163. this._axisTargetedByUpAndDown = axis;
  21164. break;
  21165. default:
  21166. this._axisTargetedByUpAndDown = 1 /* Y */;
  21167. break;
  21168. }
  21169. };
  21170. VirtualJoystick.prototype._clearCanvas = function () {
  21171. if (this._leftJoystick) {
  21172. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  21173. }
  21174. else {
  21175. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  21176. }
  21177. };
  21178. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  21179. var _this = this;
  21180. if (this.pressed) {
  21181. this._clearCanvas();
  21182. this._touches.forEach(function (touch) {
  21183. if (touch.pointerId === _this._joystickPointerID) {
  21184. VirtualJoystick.vjCanvasContext.beginPath();
  21185. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21186. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21187. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  21188. VirtualJoystick.vjCanvasContext.stroke();
  21189. VirtualJoystick.vjCanvasContext.beginPath();
  21190. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21191. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21192. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  21193. VirtualJoystick.vjCanvasContext.stroke();
  21194. VirtualJoystick.vjCanvasContext.beginPath();
  21195. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21196. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  21197. VirtualJoystick.vjCanvasContext.stroke();
  21198. }
  21199. else {
  21200. VirtualJoystick.vjCanvasContext.beginPath();
  21201. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  21202. VirtualJoystick.vjCanvasContext.beginPath();
  21203. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  21204. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21205. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  21206. VirtualJoystick.vjCanvasContext.stroke();
  21207. }
  21208. ;
  21209. });
  21210. }
  21211. requestAnimationFrame(function () {
  21212. _this._drawVirtualJoystick();
  21213. });
  21214. };
  21215. VirtualJoystick.prototype.releaseCanvas = function () {
  21216. if (VirtualJoystick.vjCanvas) {
  21217. document.body.removeChild(VirtualJoystick.vjCanvas);
  21218. VirtualJoystick.vjCanvas = null;
  21219. }
  21220. };
  21221. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  21222. VirtualJoystick._globalJoystickIndex = 0;
  21223. return VirtualJoystick;
  21224. })();
  21225. BABYLON.VirtualJoystick = VirtualJoystick;
  21226. })(BABYLON || (BABYLON = {}));
  21227. var BABYLON;
  21228. (function (BABYLON) {
  21229. var VirtualJoystick;
  21230. (function (VirtualJoystick) {
  21231. var Collection = (function () {
  21232. function Collection() {
  21233. this._count = 0;
  21234. this._collection = new Array();
  21235. }
  21236. Collection.prototype.Count = function () {
  21237. return this._count;
  21238. };
  21239. Collection.prototype.add = function (key, item) {
  21240. if (this._collection[key] != undefined) {
  21241. return undefined;
  21242. }
  21243. this._collection[key] = item;
  21244. return ++this._count;
  21245. };
  21246. Collection.prototype.remove = function (key) {
  21247. if (this._collection[key] == undefined) {
  21248. return undefined;
  21249. }
  21250. delete this._collection[key];
  21251. return --this._count;
  21252. };
  21253. Collection.prototype.item = function (key) {
  21254. return this._collection[key];
  21255. };
  21256. Collection.prototype.forEach = function (block) {
  21257. var key;
  21258. for (key in this._collection) {
  21259. if (this._collection.hasOwnProperty(key)) {
  21260. block(this._collection[key]);
  21261. }
  21262. }
  21263. };
  21264. return Collection;
  21265. })();
  21266. VirtualJoystick.Collection = Collection;
  21267. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  21268. })(BABYLON || (BABYLON = {}));
  21269. //# sourceMappingURL=babylon.virtualJoystick.js.map
  21270. var BABYLON;
  21271. (function (BABYLON) {
  21272. var OculusRiftDevKit2013_Metric = {
  21273. HResolution: 1280,
  21274. VResolution: 800,
  21275. HScreenSize: 0.149759993,
  21276. VScreenSize: 0.0935999975,
  21277. VScreenCenter: 0.0467999987,
  21278. EyeToScreenDistance: 0.0410000011,
  21279. LensSeparationDistance: 0.0635000020,
  21280. InterpupillaryDistance: 0.0640000030,
  21281. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21282. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21283. PostProcessScaleFactor: 1.714605507808412,
  21284. LensCenterOffset: 0.151976421
  21285. };
  21286. var _OculusInnerCamera = (function (_super) {
  21287. __extends(_OculusInnerCamera, _super);
  21288. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  21289. _super.call(this, name, position, scene);
  21290. this._workMatrix = new BABYLON.Matrix();
  21291. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21292. // Constants
  21293. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21294. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21295. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21296. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21297. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21298. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21299. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21300. // Postprocess
  21301. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21302. }
  21303. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  21304. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21305. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21306. return this._projectionMatrix;
  21307. };
  21308. _OculusInnerCamera.prototype._getViewMatrix = function () {
  21309. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21310. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21311. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21312. // Computing target and final matrix
  21313. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21314. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21315. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21316. return this._viewMatrix;
  21317. };
  21318. return _OculusInnerCamera;
  21319. })(BABYLON.FreeCamera);
  21320. var OculusCamera = (function (_super) {
  21321. __extends(OculusCamera, _super);
  21322. function OculusCamera(name, position, scene) {
  21323. _super.call(this, name, position, scene);
  21324. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  21325. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  21326. this.subCameras.push(this._leftCamera);
  21327. this.subCameras.push(this._rightCamera);
  21328. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21329. }
  21330. OculusCamera.prototype._update = function () {
  21331. this._leftCamera.position.copyFrom(this.position);
  21332. this._rightCamera.position.copyFrom(this.position);
  21333. this._updateCamera(this._leftCamera);
  21334. this._updateCamera(this._rightCamera);
  21335. _super.prototype._update.call(this);
  21336. };
  21337. OculusCamera.prototype._updateCamera = function (camera) {
  21338. camera.minZ = this.minZ;
  21339. camera.maxZ = this.maxZ;
  21340. camera.rotation.x = this.rotation.x;
  21341. camera.rotation.y = this.rotation.y;
  21342. camera.rotation.z = this.rotation.z;
  21343. };
  21344. // Oculus events
  21345. OculusCamera.prototype._onOrientationEvent = function (evt) {
  21346. var yaw = evt.alpha / 180 * Math.PI;
  21347. var pitch = evt.beta / 180 * Math.PI;
  21348. var roll = evt.gamma / 180 * Math.PI;
  21349. if (!this._offsetOrientation) {
  21350. this._offsetOrientation = {
  21351. yaw: yaw,
  21352. pitch: pitch,
  21353. roll: roll
  21354. };
  21355. return;
  21356. }
  21357. else {
  21358. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21359. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21360. this.rotation.z += this._offsetOrientation.roll - roll;
  21361. this._offsetOrientation.yaw = yaw;
  21362. this._offsetOrientation.pitch = pitch;
  21363. this._offsetOrientation.roll = roll;
  21364. }
  21365. };
  21366. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  21367. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21368. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21369. };
  21370. OculusCamera.prototype.detachControl = function (element) {
  21371. _super.prototype.detachControl.call(this, element);
  21372. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21373. };
  21374. return OculusCamera;
  21375. })(BABYLON.FreeCamera);
  21376. BABYLON.OculusCamera = OculusCamera;
  21377. })(BABYLON || (BABYLON = {}));
  21378. //# sourceMappingURL=babylon.oculusCamera.js.map
  21379. var BABYLON;
  21380. (function (BABYLON) {
  21381. var OculusRiftDevKit2013_Metric = {
  21382. HResolution: 1280,
  21383. VResolution: 800,
  21384. HScreenSize: 0.149759993,
  21385. VScreenSize: 0.0935999975,
  21386. VScreenCenter: 0.0467999987,
  21387. EyeToScreenDistance: 0.0410000011,
  21388. LensSeparationDistance: 0.0635000020,
  21389. InterpupillaryDistance: 0.0640000030,
  21390. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21391. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21392. PostProcessScaleFactor: 1.714605507808412,
  21393. LensCenterOffset: 0.151976421
  21394. };
  21395. var _OculusInnerGamepadCamera = (function (_super) {
  21396. __extends(_OculusInnerGamepadCamera, _super);
  21397. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  21398. _super.call(this, name, position, scene);
  21399. this._workMatrix = new BABYLON.Matrix();
  21400. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21401. // Constants
  21402. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21403. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21404. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21405. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21406. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21407. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21408. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21409. // Postprocess
  21410. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21411. }
  21412. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  21413. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21414. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21415. return this._projectionMatrix;
  21416. };
  21417. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  21418. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21419. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21420. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21421. // Computing target and final matrix
  21422. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21423. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21424. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21425. return this._viewMatrix;
  21426. };
  21427. return _OculusInnerGamepadCamera;
  21428. })(BABYLON.FreeCamera);
  21429. var OculusGamepadCamera = (function (_super) {
  21430. __extends(OculusGamepadCamera, _super);
  21431. function OculusGamepadCamera(name, position, scene) {
  21432. var _this = this;
  21433. _super.call(this, name, position, scene);
  21434. this.angularSensibility = 200;
  21435. this.moveSensibility = 75;
  21436. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  21437. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  21438. this.subCameras.push(this._leftCamera);
  21439. this.subCameras.push(this._rightCamera);
  21440. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21441. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21442. _this._onNewGameConnected(gamepad);
  21443. });
  21444. }
  21445. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21446. // Only the first gamepad can control the camera
  21447. if (gamepad.index === 0) {
  21448. this._gamepad = gamepad;
  21449. }
  21450. };
  21451. OculusGamepadCamera.prototype._update = function () {
  21452. this._leftCamera.position.copyFrom(this.position);
  21453. this._rightCamera.position.copyFrom(this.position);
  21454. this._updateCamera(this._leftCamera);
  21455. this._updateCamera(this._rightCamera);
  21456. _super.prototype._update.call(this);
  21457. };
  21458. OculusGamepadCamera.prototype._checkInputs = function () {
  21459. if (!this._gamepad) {
  21460. return;
  21461. }
  21462. var LSValues = this._gamepad.leftStick;
  21463. var normalizedLX = LSValues.x / this.moveSensibility;
  21464. var normalizedLY = LSValues.y / this.moveSensibility;
  21465. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  21466. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  21467. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21468. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  21469. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21470. };
  21471. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  21472. camera.minZ = this.minZ;
  21473. camera.maxZ = this.maxZ;
  21474. camera.rotation.x = this.rotation.x;
  21475. camera.rotation.y = this.rotation.y;
  21476. camera.rotation.z = this.rotation.z;
  21477. };
  21478. // Oculus events
  21479. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  21480. var yaw = evt.alpha / 180 * Math.PI;
  21481. var pitch = evt.beta / 180 * Math.PI;
  21482. var roll = evt.gamma / 180 * Math.PI;
  21483. if (!this._offsetOrientation) {
  21484. this._offsetOrientation = {
  21485. yaw: yaw,
  21486. pitch: pitch,
  21487. roll: roll
  21488. };
  21489. return;
  21490. }
  21491. else {
  21492. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21493. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21494. this.rotation.z += this._offsetOrientation.roll - roll;
  21495. this._offsetOrientation.yaw = yaw;
  21496. this._offsetOrientation.pitch = pitch;
  21497. this._offsetOrientation.roll = roll;
  21498. }
  21499. };
  21500. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  21501. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21502. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21503. };
  21504. OculusGamepadCamera.prototype.detachControl = function (element) {
  21505. _super.prototype.detachControl.call(this, element);
  21506. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21507. };
  21508. OculusGamepadCamera.prototype.dispose = function () {
  21509. this._gamepads.dispose();
  21510. _super.prototype.dispose.call(this);
  21511. };
  21512. return OculusGamepadCamera;
  21513. })(BABYLON.FreeCamera);
  21514. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  21515. })(BABYLON || (BABYLON = {}));
  21516. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  21517. var BABYLON;
  21518. (function (BABYLON) {
  21519. // We're mainly based on the logic defined into the FreeCamera code
  21520. var VirtualJoysticksCamera = (function (_super) {
  21521. __extends(VirtualJoysticksCamera, _super);
  21522. function VirtualJoysticksCamera(name, position, scene) {
  21523. _super.call(this, name, position, scene);
  21524. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  21525. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  21526. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  21527. this._leftjoystick.setJoystickSensibility(0.15);
  21528. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  21529. this._rightjoystick.setAxisForUpDown(0 /* X */);
  21530. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  21531. this._rightjoystick.reverseUpDown = true;
  21532. this._rightjoystick.setJoystickSensibility(0.05);
  21533. this._rightjoystick.setJoystickColor("yellow");
  21534. }
  21535. VirtualJoysticksCamera.prototype._checkInputs = function () {
  21536. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21537. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  21538. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21539. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  21540. if (!this._leftjoystick.pressed) {
  21541. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  21542. }
  21543. if (!this._rightjoystick.pressed) {
  21544. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  21545. }
  21546. };
  21547. VirtualJoysticksCamera.prototype.dispose = function () {
  21548. this._leftjoystick.releaseCanvas();
  21549. _super.prototype.dispose.call(this);
  21550. };
  21551. return VirtualJoysticksCamera;
  21552. })(BABYLON.FreeCamera);
  21553. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  21554. })(BABYLON || (BABYLON = {}));
  21555. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  21556. var BABYLON;
  21557. (function (BABYLON) {
  21558. var ShaderMaterial = (function (_super) {
  21559. __extends(ShaderMaterial, _super);
  21560. function ShaderMaterial(name, scene, shaderPath, options) {
  21561. _super.call(this, name, scene);
  21562. this._textures = new Array();
  21563. this._floats = new Array();
  21564. this._floatsArrays = {};
  21565. this._colors3 = new Array();
  21566. this._colors4 = new Array();
  21567. this._vectors2 = new Array();
  21568. this._vectors3 = new Array();
  21569. this._matrices = new Array();
  21570. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  21571. this._shaderPath = shaderPath;
  21572. options.needAlphaBlending = options.needAlphaBlending || false;
  21573. options.needAlphaTesting = options.needAlphaTesting || false;
  21574. options.attributes = options.attributes || ["position", "normal", "uv"];
  21575. options.uniforms = options.uniforms || ["worldViewProjection"];
  21576. options.samplers = options.samplers || [];
  21577. this._options = options;
  21578. }
  21579. ShaderMaterial.prototype.needAlphaBlending = function () {
  21580. return this._options.needAlphaBlending;
  21581. };
  21582. ShaderMaterial.prototype.needAlphaTesting = function () {
  21583. return this._options.needAlphaTesting;
  21584. };
  21585. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  21586. if (this._options.uniforms.indexOf(uniformName) === -1) {
  21587. this._options.uniforms.push(uniformName);
  21588. }
  21589. };
  21590. ShaderMaterial.prototype.setTexture = function (name, texture) {
  21591. if (this._options.samplers.indexOf(name) === -1) {
  21592. this._options.samplers.push(name);
  21593. }
  21594. this._textures[name] = texture;
  21595. return this;
  21596. };
  21597. ShaderMaterial.prototype.setFloat = function (name, value) {
  21598. this._checkUniform(name);
  21599. this._floats[name] = value;
  21600. return this;
  21601. };
  21602. ShaderMaterial.prototype.setFloats = function (name, value) {
  21603. this._checkUniform(name);
  21604. this._floatsArrays[name] = value;
  21605. return this;
  21606. };
  21607. ShaderMaterial.prototype.setColor3 = function (name, value) {
  21608. this._checkUniform(name);
  21609. this._colors3[name] = value;
  21610. return this;
  21611. };
  21612. ShaderMaterial.prototype.setColor4 = function (name, value) {
  21613. this._checkUniform(name);
  21614. this._colors4[name] = value;
  21615. return this;
  21616. };
  21617. ShaderMaterial.prototype.setVector2 = function (name, value) {
  21618. this._checkUniform(name);
  21619. this._vectors2[name] = value;
  21620. return this;
  21621. };
  21622. ShaderMaterial.prototype.setVector3 = function (name, value) {
  21623. this._checkUniform(name);
  21624. this._vectors3[name] = value;
  21625. return this;
  21626. };
  21627. ShaderMaterial.prototype.setMatrix = function (name, value) {
  21628. this._checkUniform(name);
  21629. this._matrices[name] = value;
  21630. return this;
  21631. };
  21632. ShaderMaterial.prototype.isReady = function () {
  21633. var scene = this.getScene();
  21634. var engine = scene.getEngine();
  21635. if (!this.checkReadyOnEveryCall) {
  21636. if (this._renderId === scene.getRenderId()) {
  21637. return true;
  21638. }
  21639. }
  21640. var previousEffect = this._effect;
  21641. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  21642. if (!this._effect.isReady()) {
  21643. return false;
  21644. }
  21645. if (previousEffect !== this._effect) {
  21646. scene.resetCachedMaterial();
  21647. }
  21648. this._renderId = scene.getRenderId();
  21649. return true;
  21650. };
  21651. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  21652. var scene = this.getScene();
  21653. if (this._options.uniforms.indexOf("world") !== -1) {
  21654. this._effect.setMatrix("world", world);
  21655. }
  21656. if (this._options.uniforms.indexOf("worldView") !== -1) {
  21657. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  21658. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  21659. }
  21660. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  21661. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  21662. }
  21663. };
  21664. ShaderMaterial.prototype.bind = function (world) {
  21665. // Std values
  21666. this.bindOnlyWorldMatrix(world);
  21667. if (this.getScene().getCachedMaterial() !== this) {
  21668. if (this._options.uniforms.indexOf("view") !== -1) {
  21669. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  21670. }
  21671. if (this._options.uniforms.indexOf("projection") !== -1) {
  21672. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  21673. }
  21674. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  21675. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  21676. }
  21677. for (var name in this._textures) {
  21678. this._effect.setTexture(name, this._textures[name]);
  21679. }
  21680. for (name in this._floats) {
  21681. this._effect.setFloat(name, this._floats[name]);
  21682. }
  21683. for (name in this._floatsArrays) {
  21684. this._effect.setArray(name, this._floatsArrays[name]);
  21685. }
  21686. for (name in this._colors3) {
  21687. this._effect.setColor3(name, this._colors3[name]);
  21688. }
  21689. for (name in this._colors4) {
  21690. var color = this._colors4[name];
  21691. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21692. }
  21693. for (name in this._vectors2) {
  21694. this._effect.setVector2(name, this._vectors2[name]);
  21695. }
  21696. for (name in this._vectors3) {
  21697. this._effect.setVector3(name, this._vectors3[name]);
  21698. }
  21699. for (name in this._matrices) {
  21700. this._effect.setMatrix(name, this._matrices[name]);
  21701. }
  21702. }
  21703. _super.prototype.bind.call(this, world, null);
  21704. };
  21705. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  21706. for (var name in this._textures) {
  21707. this._textures[name].dispose();
  21708. }
  21709. this._textures = [];
  21710. _super.prototype.dispose.call(this, forceDisposeEffect);
  21711. };
  21712. return ShaderMaterial;
  21713. })(BABYLON.Material);
  21714. BABYLON.ShaderMaterial = ShaderMaterial;
  21715. })(BABYLON || (BABYLON = {}));
  21716. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  21717. (function (BABYLON) {
  21718. var VertexData = (function () {
  21719. function VertexData() {
  21720. }
  21721. VertexData.prototype.set = function (data, kind) {
  21722. switch (kind) {
  21723. case BABYLON.VertexBuffer.PositionKind:
  21724. this.positions = data;
  21725. break;
  21726. case BABYLON.VertexBuffer.NormalKind:
  21727. this.normals = data;
  21728. break;
  21729. case BABYLON.VertexBuffer.UVKind:
  21730. this.uvs = data;
  21731. break;
  21732. case BABYLON.VertexBuffer.UV2Kind:
  21733. this.uv2s = data;
  21734. break;
  21735. case BABYLON.VertexBuffer.ColorKind:
  21736. this.colors = data;
  21737. break;
  21738. case BABYLON.VertexBuffer.MatricesIndicesKind:
  21739. this.matricesIndices = data;
  21740. break;
  21741. case BABYLON.VertexBuffer.MatricesWeightsKind:
  21742. this.matricesWeights = data;
  21743. break;
  21744. }
  21745. };
  21746. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  21747. this._applyTo(mesh, updatable);
  21748. };
  21749. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  21750. this._applyTo(geometry, updatable);
  21751. };
  21752. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  21753. this._update(mesh);
  21754. };
  21755. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  21756. this._update(geometry);
  21757. };
  21758. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  21759. if (this.positions) {
  21760. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  21761. }
  21762. if (this.normals) {
  21763. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  21764. }
  21765. if (this.uvs) {
  21766. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  21767. }
  21768. if (this.uv2s) {
  21769. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  21770. }
  21771. if (this.colors) {
  21772. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  21773. }
  21774. if (this.matricesIndices) {
  21775. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  21776. }
  21777. if (this.matricesWeights) {
  21778. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  21779. }
  21780. if (this.indices) {
  21781. meshOrGeometry.setIndices(this.indices);
  21782. }
  21783. };
  21784. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  21785. if (this.positions) {
  21786. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  21787. }
  21788. if (this.normals) {
  21789. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  21790. }
  21791. if (this.uvs) {
  21792. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  21793. }
  21794. if (this.uv2s) {
  21795. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  21796. }
  21797. if (this.colors) {
  21798. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  21799. }
  21800. if (this.matricesIndices) {
  21801. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  21802. }
  21803. if (this.matricesWeights) {
  21804. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  21805. }
  21806. if (this.indices) {
  21807. meshOrGeometry.setIndices(this.indices);
  21808. }
  21809. };
  21810. VertexData.prototype.transform = function (matrix) {
  21811. var transformed = BABYLON.Vector3.Zero();
  21812. if (this.positions) {
  21813. var position = BABYLON.Vector3.Zero();
  21814. for (var index = 0; index < this.positions.length; index += 3) {
  21815. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  21816. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  21817. this.positions[index] = transformed.x;
  21818. this.positions[index + 1] = transformed.y;
  21819. this.positions[index + 2] = transformed.z;
  21820. }
  21821. }
  21822. if (this.normals) {
  21823. var normal = BABYLON.Vector3.Zero();
  21824. for (index = 0; index < this.normals.length; index += 3) {
  21825. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  21826. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  21827. this.normals[index] = transformed.x;
  21828. this.normals[index + 1] = transformed.y;
  21829. this.normals[index + 2] = transformed.z;
  21830. }
  21831. }
  21832. };
  21833. VertexData.prototype.merge = function (other) {
  21834. if (other.indices) {
  21835. if (!this.indices) {
  21836. this.indices = [];
  21837. }
  21838. var offset = this.positions ? this.positions.length / 3 : 0;
  21839. for (var index = 0; index < other.indices.length; index++) {
  21840. this.indices.push(other.indices[index] + offset);
  21841. }
  21842. }
  21843. if (other.positions) {
  21844. if (!this.positions) {
  21845. this.positions = [];
  21846. }
  21847. for (index = 0; index < other.positions.length; index++) {
  21848. this.positions.push(other.positions[index]);
  21849. }
  21850. }
  21851. if (other.normals) {
  21852. if (!this.normals) {
  21853. this.normals = [];
  21854. }
  21855. for (index = 0; index < other.normals.length; index++) {
  21856. this.normals.push(other.normals[index]);
  21857. }
  21858. }
  21859. if (other.uvs) {
  21860. if (!this.uvs) {
  21861. this.uvs = [];
  21862. }
  21863. for (index = 0; index < other.uvs.length; index++) {
  21864. this.uvs.push(other.uvs[index]);
  21865. }
  21866. }
  21867. if (other.uv2s) {
  21868. if (!this.uv2s) {
  21869. this.uv2s = [];
  21870. }
  21871. for (index = 0; index < other.uv2s.length; index++) {
  21872. this.uv2s.push(other.uv2s[index]);
  21873. }
  21874. }
  21875. if (other.matricesIndices) {
  21876. if (!this.matricesIndices) {
  21877. this.matricesIndices = [];
  21878. }
  21879. for (index = 0; index < other.matricesIndices.length; index++) {
  21880. this.matricesIndices.push(other.matricesIndices[index]);
  21881. }
  21882. }
  21883. if (other.matricesWeights) {
  21884. if (!this.matricesWeights) {
  21885. this.matricesWeights = [];
  21886. }
  21887. for (index = 0; index < other.matricesWeights.length; index++) {
  21888. this.matricesWeights.push(other.matricesWeights[index]);
  21889. }
  21890. }
  21891. if (other.colors) {
  21892. if (!this.colors) {
  21893. this.colors = [];
  21894. }
  21895. for (index = 0; index < other.colors.length; index++) {
  21896. this.colors.push(other.colors[index]);
  21897. }
  21898. }
  21899. };
  21900. // Statics
  21901. VertexData.ExtractFromMesh = function (mesh) {
  21902. return VertexData._ExtractFrom(mesh);
  21903. };
  21904. VertexData.ExtractFromGeometry = function (geometry) {
  21905. return VertexData._ExtractFrom(geometry);
  21906. };
  21907. VertexData._ExtractFrom = function (meshOrGeometry) {
  21908. var result = new VertexData();
  21909. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21910. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21911. }
  21912. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21913. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21914. }
  21915. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21916. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21917. }
  21918. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  21919. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  21920. }
  21921. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  21922. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  21923. }
  21924. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21925. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21926. }
  21927. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21928. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21929. }
  21930. result.indices = meshOrGeometry.getIndices();
  21931. return result;
  21932. };
  21933. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  21934. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21935. closeArray = closeArray || false;
  21936. closePath = closePath || false;
  21937. var defaultOffset = Math.floor(pathArray[0].length / 2);
  21938. offset = offset || defaultOffset;
  21939. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  21940. var positions = [];
  21941. var indices = [];
  21942. var normals = [];
  21943. var uvs = [];
  21944. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  21945. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  21946. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  21947. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  21948. var minlg; // minimal length among all paths from pathArray
  21949. var lg = []; // array of path lengths : nb of vertex per path
  21950. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  21951. var p; // path iterator
  21952. var i; // point iterator
  21953. var j; // point iterator
  21954. // if single path in pathArray
  21955. if (pathArray.length < 2) {
  21956. var ar1 = [];
  21957. var ar2 = [];
  21958. for (i = 0; i < pathArray[0].length - offset; i++) {
  21959. ar1.push(pathArray[0][i]);
  21960. ar2.push(pathArray[0][i + offset]);
  21961. }
  21962. pathArray = [ar1, ar2];
  21963. }
  21964. // positions and horizontal distances (u)
  21965. var idc = 0;
  21966. minlg = pathArray[0].length;
  21967. for (p = 0; p < pathArray.length; p++) {
  21968. uTotalDistance[p] = 0;
  21969. us[p] = [0];
  21970. var path = pathArray[p];
  21971. var l = path.length;
  21972. minlg = (minlg < l) ? minlg : l;
  21973. lg[p] = l;
  21974. idx[p] = idc;
  21975. j = 0;
  21976. while (j < l) {
  21977. positions.push(path[j].x, path[j].y, path[j].z);
  21978. if (j > 0) {
  21979. var vectlg = path[j].subtract(path[j - 1]).length();
  21980. var dist = vectlg + uTotalDistance[p];
  21981. us[p].push(dist);
  21982. uTotalDistance[p] = dist;
  21983. }
  21984. j++;
  21985. }
  21986. if (closePath) {
  21987. vectlg = path[0].subtract(path[j - 1]).length();
  21988. dist = vectlg + uTotalDistance[p];
  21989. uTotalDistance[p] = dist;
  21990. }
  21991. idc += l;
  21992. }
  21993. for (i = 0; i < minlg; i++) {
  21994. vTotalDistance[i] = 0;
  21995. vs[i] = [0];
  21996. var path1;
  21997. var path2;
  21998. for (p = 0; p < pathArray.length - 1; p++) {
  21999. path1 = pathArray[p];
  22000. path2 = pathArray[p + 1];
  22001. vectlg = path2[i].subtract(path1[i]).length();
  22002. dist = vectlg + vTotalDistance[i];
  22003. vs[i].push(dist);
  22004. vTotalDistance[i] = dist;
  22005. }
  22006. if (closeArray) {
  22007. path1 = pathArray[p];
  22008. path2 = pathArray[0];
  22009. vectlg = path2[i].subtract(path1[i]).length();
  22010. dist = vectlg + vTotalDistance[i];
  22011. vTotalDistance[i] = dist;
  22012. }
  22013. }
  22014. // uvs
  22015. var u;
  22016. var v;
  22017. for (p = 0; p < pathArray.length; p++) {
  22018. for (i = 0; i < minlg; i++) {
  22019. u = us[p][i] / uTotalDistance[p];
  22020. v = vs[i][p] / vTotalDistance[i];
  22021. uvs.push(u, v);
  22022. }
  22023. }
  22024. // indices
  22025. p = 0; // path index
  22026. var pi = 0; // positions array index
  22027. var l1 = lg[p] - 1; // path1 length
  22028. var l2 = lg[p + 1] - 1; // path2 length
  22029. var min = (l1 < l2) ? l1 : l2; // current path stop index
  22030. var shft = idx[1] - idx[0]; // shift
  22031. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  22032. var t1; // two consecutive triangles, so 4 points : point1
  22033. var t2; // point2
  22034. var t3; // point3
  22035. var t4; // point4
  22036. while (pi <= min && p < path1nb) {
  22037. // 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
  22038. t1 = pi;
  22039. t2 = pi + shft;
  22040. t3 = pi + 1;
  22041. t4 = pi + shft + 1;
  22042. indices.push(pi, pi + shft, pi + 1);
  22043. indices.push(pi + shft + 1, pi + 1, pi + shft);
  22044. pi += 1;
  22045. if (pi === min) {
  22046. if (closePath) {
  22047. indices.push(pi, pi + shft, idx[p]);
  22048. indices.push(idx[p] + shft, idx[p], pi + shft);
  22049. t3 = idx[p];
  22050. t4 = idx[p] + shft;
  22051. }
  22052. p++;
  22053. if (p === lg.length - 1) {
  22054. shft = idx[0] - idx[p];
  22055. l1 = lg[p] - 1;
  22056. l2 = lg[0] - 1;
  22057. }
  22058. else {
  22059. shft = idx[p + 1] - idx[p];
  22060. l1 = lg[p] - 1;
  22061. l2 = lg[p + 1] - 1;
  22062. }
  22063. pi = idx[p];
  22064. min = (l1 < l2) ? l1 + pi : l2 + pi;
  22065. }
  22066. }
  22067. // normals
  22068. VertexData.ComputeNormals(positions, indices, normals);
  22069. // sides
  22070. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22071. // Result
  22072. var vertexData = new VertexData();
  22073. vertexData.indices = indices;
  22074. vertexData.positions = positions;
  22075. vertexData.normals = normals;
  22076. vertexData.uvs = uvs;
  22077. return vertexData;
  22078. };
  22079. VertexData.CreateBox = function (size, sideOrientation) {
  22080. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22081. var normalsSource = [
  22082. new BABYLON.Vector3(0, 0, 1),
  22083. new BABYLON.Vector3(0, 0, -1),
  22084. new BABYLON.Vector3(1, 0, 0),
  22085. new BABYLON.Vector3(-1, 0, 0),
  22086. new BABYLON.Vector3(0, 1, 0),
  22087. new BABYLON.Vector3(0, -1, 0)
  22088. ];
  22089. var indices = [];
  22090. var positions = [];
  22091. var normals = [];
  22092. var uvs = [];
  22093. size = size || 1;
  22094. for (var index = 0; index < normalsSource.length; index++) {
  22095. var normal = normalsSource[index];
  22096. // Get two vectors perpendicular to the face normal and to each other.
  22097. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  22098. var side2 = BABYLON.Vector3.Cross(normal, side1);
  22099. // Six indices (two triangles) per face.
  22100. var verticesLength = positions.length / 3;
  22101. indices.push(verticesLength);
  22102. indices.push(verticesLength + 1);
  22103. indices.push(verticesLength + 2);
  22104. indices.push(verticesLength);
  22105. indices.push(verticesLength + 2);
  22106. indices.push(verticesLength + 3);
  22107. // Four vertices per face.
  22108. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  22109. positions.push(vertex.x, vertex.y, vertex.z);
  22110. normals.push(normal.x, normal.y, normal.z);
  22111. uvs.push(1.0, 1.0);
  22112. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  22113. positions.push(vertex.x, vertex.y, vertex.z);
  22114. normals.push(normal.x, normal.y, normal.z);
  22115. uvs.push(0.0, 1.0);
  22116. vertex = normal.add(side1).add(side2).scale(size / 2);
  22117. positions.push(vertex.x, vertex.y, vertex.z);
  22118. normals.push(normal.x, normal.y, normal.z);
  22119. uvs.push(0.0, 0.0);
  22120. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  22121. positions.push(vertex.x, vertex.y, vertex.z);
  22122. normals.push(normal.x, normal.y, normal.z);
  22123. uvs.push(1.0, 0.0);
  22124. }
  22125. // sides
  22126. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22127. // Result
  22128. var vertexData = new VertexData();
  22129. vertexData.indices = indices;
  22130. vertexData.positions = positions;
  22131. vertexData.normals = normals;
  22132. vertexData.uvs = uvs;
  22133. return vertexData;
  22134. };
  22135. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  22136. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22137. segments = segments || 32;
  22138. diameter = diameter || 1;
  22139. var radius = diameter / 2;
  22140. var totalZRotationSteps = 2 + segments;
  22141. var totalYRotationSteps = 2 * totalZRotationSteps;
  22142. var indices = [];
  22143. var positions = [];
  22144. var normals = [];
  22145. var uvs = [];
  22146. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  22147. var normalizedZ = zRotationStep / totalZRotationSteps;
  22148. var angleZ = (normalizedZ * Math.PI);
  22149. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  22150. var normalizedY = yRotationStep / totalYRotationSteps;
  22151. var angleY = normalizedY * Math.PI * 2;
  22152. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  22153. var rotationY = BABYLON.Matrix.RotationY(angleY);
  22154. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  22155. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  22156. var vertex = complete.scale(radius);
  22157. var normal = BABYLON.Vector3.Normalize(vertex);
  22158. positions.push(vertex.x, vertex.y, vertex.z);
  22159. normals.push(normal.x, normal.y, normal.z);
  22160. uvs.push(normalizedZ, normalizedY);
  22161. }
  22162. if (zRotationStep > 0) {
  22163. var verticesCount = positions.length / 3;
  22164. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  22165. indices.push((firstIndex));
  22166. indices.push((firstIndex + 1));
  22167. indices.push(firstIndex + totalYRotationSteps + 1);
  22168. indices.push((firstIndex + totalYRotationSteps + 1));
  22169. indices.push((firstIndex + 1));
  22170. indices.push((firstIndex + totalYRotationSteps + 2));
  22171. }
  22172. }
  22173. }
  22174. // Sides
  22175. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22176. // Result
  22177. var vertexData = new VertexData();
  22178. vertexData.indices = indices;
  22179. vertexData.positions = positions;
  22180. vertexData.normals = normals;
  22181. vertexData.uvs = uvs;
  22182. return vertexData;
  22183. };
  22184. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  22185. if (subdivisions === void 0) { subdivisions = 1; }
  22186. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22187. var radiusTop = diameterTop / 2;
  22188. var radiusBottom = diameterBottom / 2;
  22189. var indices = [];
  22190. var positions = [];
  22191. var normals = [];
  22192. var uvs = [];
  22193. height = height || 1;
  22194. diameterTop = diameterTop || 0.5;
  22195. diameterBottom = diameterBottom || 1;
  22196. tessellation = tessellation || 16;
  22197. subdivisions = subdivisions || 1;
  22198. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  22199. var getCircleVector = function (i) {
  22200. var angle = (i * 2.0 * Math.PI / tessellation);
  22201. var dx = Math.cos(angle);
  22202. var dz = Math.sin(angle);
  22203. return new BABYLON.Vector3(dx, 0, dz);
  22204. };
  22205. var createCylinderCap = function (isTop) {
  22206. var radius = isTop ? radiusTop : radiusBottom;
  22207. if (radius === 0) {
  22208. return;
  22209. }
  22210. var vbase = positions.length / 3;
  22211. var offset = new BABYLON.Vector3(0, height / 2, 0);
  22212. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  22213. if (!isTop) {
  22214. offset.scaleInPlace(-1);
  22215. textureScale.x = -textureScale.x;
  22216. }
  22217. for (var i = 0; i < tessellation; i++) {
  22218. var circleVector = getCircleVector(i);
  22219. var position = circleVector.scale(radius).add(offset);
  22220. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  22221. positions.push(position.x, position.y, position.z);
  22222. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22223. }
  22224. for (i = 0; i < tessellation - 2; i++) {
  22225. if (!isTop) {
  22226. indices.push(vbase);
  22227. indices.push(vbase + (i + 2) % tessellation);
  22228. indices.push(vbase + (i + 1) % tessellation);
  22229. }
  22230. else {
  22231. indices.push(vbase);
  22232. indices.push(vbase + (i + 1) % tessellation);
  22233. indices.push(vbase + (i + 2) % tessellation);
  22234. }
  22235. }
  22236. };
  22237. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  22238. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  22239. var stride = tessellation + 1;
  22240. for (var i = 0; i <= tessellation; i++) {
  22241. var circleVector = getCircleVector(i);
  22242. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  22243. var position, radius = radiusBottom;
  22244. for (var s = 0; s <= subdivisions; s++) {
  22245. // Update variables
  22246. position = circleVector.scale(radius);
  22247. position.addInPlace(base.add(offset.scale(s)));
  22248. textureCoordinate.y += 1 / subdivisions;
  22249. radius += (radiusTop - radiusBottom) / subdivisions;
  22250. // Push in arrays
  22251. positions.push(position.x, position.y, position.z);
  22252. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22253. }
  22254. }
  22255. subdivisions += 1;
  22256. for (s = 0; s < subdivisions - 1; s++) {
  22257. for (i = 0; i <= tessellation; i++) {
  22258. indices.push(i * subdivisions + s);
  22259. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22260. indices.push(i * subdivisions + (s + 1));
  22261. indices.push(i * subdivisions + (s + 1));
  22262. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22263. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  22264. }
  22265. }
  22266. // Create flat triangle fan caps to seal the top and bottom.
  22267. createCylinderCap(true);
  22268. createCylinderCap(false);
  22269. // Normals
  22270. VertexData.ComputeNormals(positions, indices, normals);
  22271. // Sides
  22272. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22273. // Result
  22274. var vertexData = new VertexData();
  22275. vertexData.indices = indices;
  22276. vertexData.positions = positions;
  22277. vertexData.normals = normals;
  22278. vertexData.uvs = uvs;
  22279. return vertexData;
  22280. };
  22281. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  22282. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22283. var indices = [];
  22284. var positions = [];
  22285. var normals = [];
  22286. var uvs = [];
  22287. diameter = diameter || 1;
  22288. thickness = thickness || 0.5;
  22289. tessellation = tessellation || 16;
  22290. var stride = tessellation + 1;
  22291. for (var i = 0; i <= tessellation; i++) {
  22292. var u = i / tessellation;
  22293. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  22294. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  22295. for (var j = 0; j <= tessellation; j++) {
  22296. var v = 1 - j / tessellation;
  22297. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  22298. var dx = Math.cos(innerAngle);
  22299. var dy = Math.sin(innerAngle);
  22300. // Create a vertex.
  22301. var normal = new BABYLON.Vector3(dx, dy, 0);
  22302. var position = normal.scale(thickness / 2);
  22303. var textureCoordinate = new BABYLON.Vector2(u, v);
  22304. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  22305. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  22306. positions.push(position.x, position.y, position.z);
  22307. normals.push(normal.x, normal.y, normal.z);
  22308. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22309. // And create indices for two triangles.
  22310. var nextI = (i + 1) % stride;
  22311. var nextJ = (j + 1) % stride;
  22312. indices.push(i * stride + j);
  22313. indices.push(i * stride + nextJ);
  22314. indices.push(nextI * stride + j);
  22315. indices.push(i * stride + nextJ);
  22316. indices.push(nextI * stride + nextJ);
  22317. indices.push(nextI * stride + j);
  22318. }
  22319. }
  22320. // Sides
  22321. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22322. // Result
  22323. var vertexData = new VertexData();
  22324. vertexData.indices = indices;
  22325. vertexData.positions = positions;
  22326. vertexData.normals = normals;
  22327. vertexData.uvs = uvs;
  22328. return vertexData;
  22329. };
  22330. VertexData.CreateLines = function (points) {
  22331. var indices = [];
  22332. var positions = [];
  22333. for (var index = 0; index < points.length; index++) {
  22334. positions.push(points[index].x, points[index].y, points[index].z);
  22335. if (index > 0) {
  22336. indices.push(index - 1);
  22337. indices.push(index);
  22338. }
  22339. }
  22340. // Result
  22341. var vertexData = new VertexData();
  22342. vertexData.indices = indices;
  22343. vertexData.positions = positions;
  22344. return vertexData;
  22345. };
  22346. VertexData.CreateGround = function (width, height, subdivisions) {
  22347. var indices = [];
  22348. var positions = [];
  22349. var normals = [];
  22350. var uvs = [];
  22351. var row, col;
  22352. width = width || 1;
  22353. height = height || 1;
  22354. subdivisions = subdivisions || 1;
  22355. for (row = 0; row <= subdivisions; row++) {
  22356. for (col = 0; col <= subdivisions; col++) {
  22357. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22358. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22359. positions.push(position.x, position.y, position.z);
  22360. normals.push(normal.x, normal.y, normal.z);
  22361. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22362. }
  22363. }
  22364. for (row = 0; row < subdivisions; row++) {
  22365. for (col = 0; col < subdivisions; col++) {
  22366. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22367. indices.push(col + 1 + row * (subdivisions + 1));
  22368. indices.push(col + row * (subdivisions + 1));
  22369. indices.push(col + (row + 1) * (subdivisions + 1));
  22370. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22371. indices.push(col + row * (subdivisions + 1));
  22372. }
  22373. }
  22374. // Result
  22375. var vertexData = new VertexData();
  22376. vertexData.indices = indices;
  22377. vertexData.positions = positions;
  22378. vertexData.normals = normals;
  22379. vertexData.uvs = uvs;
  22380. return vertexData;
  22381. };
  22382. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  22383. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  22384. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  22385. var indices = [];
  22386. var positions = [];
  22387. var normals = [];
  22388. var uvs = [];
  22389. var row, col, tileRow, tileCol;
  22390. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  22391. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  22392. precision.w = (precision.w < 1) ? 1 : precision.w;
  22393. precision.h = (precision.h < 1) ? 1 : precision.h;
  22394. var tileSize = {
  22395. 'w': (xmax - xmin) / subdivisions.w,
  22396. 'h': (zmax - zmin) / subdivisions.h
  22397. };
  22398. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  22399. // Indices
  22400. var base = positions.length / 3;
  22401. var rowLength = precision.w + 1;
  22402. for (row = 0; row < precision.h; row++) {
  22403. for (col = 0; col < precision.w; col++) {
  22404. var square = [
  22405. base + col + row * rowLength,
  22406. base + (col + 1) + row * rowLength,
  22407. base + (col + 1) + (row + 1) * rowLength,
  22408. base + col + (row + 1) * rowLength
  22409. ];
  22410. indices.push(square[1]);
  22411. indices.push(square[2]);
  22412. indices.push(square[3]);
  22413. indices.push(square[0]);
  22414. indices.push(square[1]);
  22415. indices.push(square[3]);
  22416. }
  22417. }
  22418. // Position, normals and uvs
  22419. var position = BABYLON.Vector3.Zero();
  22420. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22421. for (row = 0; row <= precision.h; row++) {
  22422. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  22423. for (col = 0; col <= precision.w; col++) {
  22424. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  22425. position.y = 0;
  22426. positions.push(position.x, position.y, position.z);
  22427. normals.push(normal.x, normal.y, normal.z);
  22428. uvs.push(col / precision.w, row / precision.h);
  22429. }
  22430. }
  22431. }
  22432. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  22433. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  22434. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  22435. }
  22436. }
  22437. // Result
  22438. var vertexData = new VertexData();
  22439. vertexData.indices = indices;
  22440. vertexData.positions = positions;
  22441. vertexData.normals = normals;
  22442. vertexData.uvs = uvs;
  22443. return vertexData;
  22444. };
  22445. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  22446. var indices = [];
  22447. var positions = [];
  22448. var normals = [];
  22449. var uvs = [];
  22450. var row, col;
  22451. for (row = 0; row <= subdivisions; row++) {
  22452. for (col = 0; col <= subdivisions; col++) {
  22453. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22454. // Compute height
  22455. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  22456. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  22457. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  22458. var r = buffer[pos] / 255.0;
  22459. var g = buffer[pos + 1] / 255.0;
  22460. var b = buffer[pos + 2] / 255.0;
  22461. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22462. position.y = minHeight + (maxHeight - minHeight) * gradient;
  22463. // Add vertex
  22464. positions.push(position.x, position.y, position.z);
  22465. normals.push(0, 0, 0);
  22466. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22467. }
  22468. }
  22469. for (row = 0; row < subdivisions; row++) {
  22470. for (col = 0; col < subdivisions; col++) {
  22471. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22472. indices.push(col + 1 + row * (subdivisions + 1));
  22473. indices.push(col + row * (subdivisions + 1));
  22474. indices.push(col + (row + 1) * (subdivisions + 1));
  22475. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22476. indices.push(col + row * (subdivisions + 1));
  22477. }
  22478. }
  22479. // Normals
  22480. VertexData.ComputeNormals(positions, indices, normals);
  22481. // Result
  22482. var vertexData = new VertexData();
  22483. vertexData.indices = indices;
  22484. vertexData.positions = positions;
  22485. vertexData.normals = normals;
  22486. vertexData.uvs = uvs;
  22487. return vertexData;
  22488. };
  22489. VertexData.CreatePlane = function (size, sideOrientation) {
  22490. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22491. var indices = [];
  22492. var positions = [];
  22493. var normals = [];
  22494. var uvs = [];
  22495. size = size || 1;
  22496. // Vertices
  22497. var halfSize = size / 2.0;
  22498. positions.push(-halfSize, -halfSize, 0);
  22499. normals.push(0, 0, -1.0);
  22500. uvs.push(0.0, 0.0);
  22501. positions.push(halfSize, -halfSize, 0);
  22502. normals.push(0, 0, -1.0);
  22503. uvs.push(1.0, 0.0);
  22504. positions.push(halfSize, halfSize, 0);
  22505. normals.push(0, 0, -1.0);
  22506. uvs.push(1.0, 1.0);
  22507. positions.push(-halfSize, halfSize, 0);
  22508. normals.push(0, 0, -1.0);
  22509. uvs.push(0.0, 1.0);
  22510. // Indices
  22511. indices.push(0);
  22512. indices.push(1);
  22513. indices.push(2);
  22514. indices.push(0);
  22515. indices.push(2);
  22516. indices.push(3);
  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. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  22528. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  22529. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22530. var indices = [];
  22531. var positions = [];
  22532. var normals = [];
  22533. var uvs = [];
  22534. radius = radius || 2;
  22535. tube = tube || 0.5;
  22536. radialSegments = radialSegments || 32;
  22537. tubularSegments = tubularSegments || 32;
  22538. p = p || 2;
  22539. q = q || 3;
  22540. // Helper
  22541. var getPos = function (angle) {
  22542. var cu = Math.cos(angle);
  22543. var su = Math.sin(angle);
  22544. var quOverP = q / p * angle;
  22545. var cs = Math.cos(quOverP);
  22546. var tx = radius * (2 + cs) * 0.5 * cu;
  22547. var ty = radius * (2 + cs) * su * 0.5;
  22548. var tz = radius * Math.sin(quOverP) * 0.5;
  22549. return new BABYLON.Vector3(tx, ty, tz);
  22550. };
  22551. for (var i = 0; i <= radialSegments; i++) {
  22552. var modI = i % radialSegments;
  22553. var u = modI / radialSegments * 2 * p * Math.PI;
  22554. var p1 = getPos(u);
  22555. var p2 = getPos(u + 0.01);
  22556. var tang = p2.subtract(p1);
  22557. var n = p2.add(p1);
  22558. var bitan = BABYLON.Vector3.Cross(tang, n);
  22559. n = BABYLON.Vector3.Cross(bitan, tang);
  22560. bitan.normalize();
  22561. n.normalize();
  22562. for (var j = 0; j < tubularSegments; j++) {
  22563. var modJ = j % tubularSegments;
  22564. var v = modJ / tubularSegments * 2 * Math.PI;
  22565. var cx = -tube * Math.cos(v);
  22566. var cy = tube * Math.sin(v);
  22567. positions.push(p1.x + cx * n.x + cy * bitan.x);
  22568. positions.push(p1.y + cx * n.y + cy * bitan.y);
  22569. positions.push(p1.z + cx * n.z + cy * bitan.z);
  22570. uvs.push(i / radialSegments);
  22571. uvs.push(j / tubularSegments);
  22572. }
  22573. }
  22574. for (i = 0; i < radialSegments; i++) {
  22575. for (j = 0; j < tubularSegments; j++) {
  22576. var jNext = (j + 1) % tubularSegments;
  22577. var a = i * tubularSegments + j;
  22578. var b = (i + 1) * tubularSegments + j;
  22579. var c = (i + 1) * tubularSegments + jNext;
  22580. var d = i * tubularSegments + jNext;
  22581. indices.push(d);
  22582. indices.push(b);
  22583. indices.push(a);
  22584. indices.push(d);
  22585. indices.push(c);
  22586. indices.push(b);
  22587. }
  22588. }
  22589. // Normals
  22590. VertexData.ComputeNormals(positions, indices, normals);
  22591. // Sides
  22592. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22593. // Result
  22594. var vertexData = new VertexData();
  22595. vertexData.indices = indices;
  22596. vertexData.positions = positions;
  22597. vertexData.normals = normals;
  22598. vertexData.uvs = uvs;
  22599. return vertexData;
  22600. };
  22601. // Tools
  22602. VertexData.ComputeNormals = function (positions, indices, normals) {
  22603. var positionVectors = [];
  22604. var facesOfVertices = [];
  22605. var index;
  22606. for (index = 0; index < positions.length; index += 3) {
  22607. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  22608. positionVectors.push(vector3);
  22609. facesOfVertices.push([]);
  22610. }
  22611. // Compute normals
  22612. var facesNormals = [];
  22613. for (index = 0; index < indices.length / 3; index++) {
  22614. var i1 = indices[index * 3];
  22615. var i2 = indices[index * 3 + 1];
  22616. var i3 = indices[index * 3 + 2];
  22617. var p1 = positionVectors[i1];
  22618. var p2 = positionVectors[i2];
  22619. var p3 = positionVectors[i3];
  22620. var p1p2 = p1.subtract(p2);
  22621. var p3p2 = p3.subtract(p2);
  22622. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22623. facesOfVertices[i1].push(index);
  22624. facesOfVertices[i2].push(index);
  22625. facesOfVertices[i3].push(index);
  22626. }
  22627. for (index = 0; index < positionVectors.length; index++) {
  22628. var faces = facesOfVertices[index];
  22629. var normal = BABYLON.Vector3.Zero();
  22630. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  22631. normal.addInPlace(facesNormals[faces[faceIndex]]);
  22632. }
  22633. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  22634. normals[index * 3] = normal.x;
  22635. normals[index * 3 + 1] = normal.y;
  22636. normals[index * 3 + 2] = normal.z;
  22637. }
  22638. };
  22639. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  22640. var li = indices.length;
  22641. var ln = normals.length;
  22642. var i;
  22643. var n;
  22644. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  22645. switch (sideOrientation) {
  22646. case BABYLON.Mesh.FRONTSIDE:
  22647. break;
  22648. case BABYLON.Mesh.BACKSIDE:
  22649. var tmp;
  22650. for (i = 0; i < li; i += 3) {
  22651. tmp = indices[i];
  22652. indices[i] = indices[i + 2];
  22653. indices[i + 2] = tmp;
  22654. }
  22655. for (n = 0; n < ln; n++) {
  22656. normals[n] = -normals[n];
  22657. }
  22658. break;
  22659. case BABYLON.Mesh.DOUBLESIDE:
  22660. // positions
  22661. var lp = positions.length;
  22662. var l = lp / 3;
  22663. for (var p = 0; p < lp; p++) {
  22664. positions[lp + p] = positions[p];
  22665. }
  22666. for (i = 0; i < li; i += 3) {
  22667. indices[i + li] = indices[i + 2] + l;
  22668. indices[i + 1 + li] = indices[i + 1] + l;
  22669. indices[i + 2 + li] = indices[i] + l;
  22670. }
  22671. for (n = 0; n < ln; n++) {
  22672. normals[ln + n] = -normals[n];
  22673. }
  22674. // uvs
  22675. var lu = uvs.length;
  22676. for (var u = 0; u < lu; u++) {
  22677. uvs[u + lu] = uvs[u];
  22678. }
  22679. break;
  22680. }
  22681. };
  22682. return VertexData;
  22683. })();
  22684. BABYLON.VertexData = VertexData;
  22685. })(BABYLON || (BABYLON = {}));
  22686. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  22687. var BABYLON;
  22688. (function (BABYLON) {
  22689. var buildCamera = function (that, name) {
  22690. that._leftCamera.isIntermediate = true;
  22691. that.subCameras.push(that._leftCamera);
  22692. that.subCameras.push(that._rightCamera);
  22693. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  22694. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  22695. that._anaglyphPostProcess.onApply = function (effect) {
  22696. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  22697. };
  22698. that._update();
  22699. };
  22700. var AnaglyphArcRotateCamera = (function (_super) {
  22701. __extends(AnaglyphArcRotateCamera, _super);
  22702. // ANY
  22703. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  22704. _super.call(this, name, alpha, beta, radius, target, scene);
  22705. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22706. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  22707. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  22708. buildCamera(this, name);
  22709. }
  22710. AnaglyphArcRotateCamera.prototype._update = function () {
  22711. this._updateCamera(this._leftCamera);
  22712. this._updateCamera(this._rightCamera);
  22713. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  22714. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  22715. _super.prototype._update.call(this);
  22716. };
  22717. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  22718. camera.beta = this.beta;
  22719. camera.radius = this.radius;
  22720. camera.minZ = this.minZ;
  22721. camera.maxZ = this.maxZ;
  22722. camera.fov = this.fov;
  22723. camera.target = this.target;
  22724. };
  22725. return AnaglyphArcRotateCamera;
  22726. })(BABYLON.ArcRotateCamera);
  22727. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  22728. var AnaglyphFreeCamera = (function (_super) {
  22729. __extends(AnaglyphFreeCamera, _super);
  22730. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  22731. _super.call(this, name, position, scene);
  22732. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22733. this._transformMatrix = new BABYLON.Matrix();
  22734. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  22735. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  22736. buildCamera(this, name);
  22737. }
  22738. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  22739. var target = this.getTarget();
  22740. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  22741. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  22742. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  22743. };
  22744. AnaglyphFreeCamera.prototype._update = function () {
  22745. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  22746. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  22747. this._updateCamera(this._leftCamera);
  22748. this._updateCamera(this._rightCamera);
  22749. _super.prototype._update.call(this);
  22750. };
  22751. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  22752. camera.minZ = this.minZ;
  22753. camera.maxZ = this.maxZ;
  22754. camera.fov = this.fov;
  22755. camera.viewport = this.viewport;
  22756. camera.setTarget(this.getTarget());
  22757. };
  22758. return AnaglyphFreeCamera;
  22759. })(BABYLON.FreeCamera);
  22760. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  22761. })(BABYLON || (BABYLON = {}));
  22762. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  22763. var BABYLON;
  22764. (function (BABYLON) {
  22765. var AnaglyphPostProcess = (function (_super) {
  22766. __extends(AnaglyphPostProcess, _super);
  22767. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22768. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  22769. }
  22770. return AnaglyphPostProcess;
  22771. })(BABYLON.PostProcess);
  22772. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  22773. })(BABYLON || (BABYLON = {}));
  22774. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  22775. (function (BABYLON) {
  22776. var Tags = (function () {
  22777. function Tags() {
  22778. }
  22779. Tags.EnableFor = function (obj) {
  22780. obj._tags = obj._tags || {};
  22781. obj.hasTags = function () {
  22782. return Tags.HasTags(obj);
  22783. };
  22784. obj.addTags = function (tagsString) {
  22785. return Tags.AddTagsTo(obj, tagsString);
  22786. };
  22787. obj.removeTags = function (tagsString) {
  22788. return Tags.RemoveTagsFrom(obj, tagsString);
  22789. };
  22790. obj.matchesTagsQuery = function (tagsQuery) {
  22791. return Tags.MatchesQuery(obj, tagsQuery);
  22792. };
  22793. };
  22794. Tags.DisableFor = function (obj) {
  22795. delete obj._tags;
  22796. delete obj.hasTags;
  22797. delete obj.addTags;
  22798. delete obj.removeTags;
  22799. delete obj.matchesTagsQuery;
  22800. };
  22801. Tags.HasTags = function (obj) {
  22802. if (!obj._tags) {
  22803. return false;
  22804. }
  22805. return !BABYLON.Tools.IsEmpty(obj._tags);
  22806. };
  22807. Tags.GetTags = function (obj) {
  22808. if (!obj._tags) {
  22809. return null;
  22810. }
  22811. return obj._tags;
  22812. };
  22813. // the tags 'true' and 'false' are reserved and cannot be used as tags
  22814. // a tag cannot start with '||', '&&', and '!'
  22815. // it cannot contain whitespaces
  22816. Tags.AddTagsTo = function (obj, tagsString) {
  22817. if (!tagsString) {
  22818. return;
  22819. }
  22820. var tags = tagsString.split(" ");
  22821. for (var t in tags) {
  22822. Tags._AddTagTo(obj, tags[t]);
  22823. }
  22824. };
  22825. Tags._AddTagTo = function (obj, tag) {
  22826. tag = tag.trim();
  22827. if (tag === "" || tag === "true" || tag === "false") {
  22828. return;
  22829. }
  22830. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  22831. return;
  22832. }
  22833. Tags.EnableFor(obj);
  22834. obj._tags[tag] = true;
  22835. };
  22836. Tags.RemoveTagsFrom = function (obj, tagsString) {
  22837. if (!Tags.HasTags(obj)) {
  22838. return;
  22839. }
  22840. var tags = tagsString.split(" ");
  22841. for (var t in tags) {
  22842. Tags._RemoveTagFrom(obj, tags[t]);
  22843. }
  22844. };
  22845. Tags._RemoveTagFrom = function (obj, tag) {
  22846. delete obj._tags[tag];
  22847. };
  22848. Tags.MatchesQuery = function (obj, tagsQuery) {
  22849. if (tagsQuery === undefined) {
  22850. return true;
  22851. }
  22852. if (tagsQuery === "") {
  22853. return Tags.HasTags(obj);
  22854. }
  22855. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  22856. };
  22857. return Tags;
  22858. })();
  22859. BABYLON.Tags = Tags;
  22860. })(BABYLON || (BABYLON = {}));
  22861. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  22862. (function (BABYLON) {
  22863. var Internals;
  22864. (function (Internals) {
  22865. var AndOrNotEvaluator = (function () {
  22866. function AndOrNotEvaluator() {
  22867. }
  22868. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  22869. if (!query.match(/\([^\(\)]*\)/g)) {
  22870. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  22871. }
  22872. else {
  22873. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  22874. // remove parenthesis
  22875. r = r.slice(1, r.length - 1);
  22876. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  22877. });
  22878. }
  22879. if (query === "true") {
  22880. return true;
  22881. }
  22882. if (query === "false") {
  22883. return false;
  22884. }
  22885. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  22886. };
  22887. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  22888. evaluateCallback = evaluateCallback || (function (r) {
  22889. return r === "true" ? true : false;
  22890. });
  22891. var result;
  22892. var or = parenthesisContent.split("||");
  22893. for (var i in or) {
  22894. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  22895. var and = ori.split("&&");
  22896. if (and.length > 1) {
  22897. for (var j = 0; j < and.length; ++j) {
  22898. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  22899. if (andj !== "true" && andj !== "false") {
  22900. if (andj[0] === "!") {
  22901. result = !evaluateCallback(andj.substring(1));
  22902. }
  22903. else {
  22904. result = evaluateCallback(andj);
  22905. }
  22906. }
  22907. else {
  22908. result = andj === "true" ? true : false;
  22909. }
  22910. if (!result) {
  22911. ori = "false";
  22912. break;
  22913. }
  22914. }
  22915. }
  22916. if (result || ori === "true") {
  22917. result = true;
  22918. break;
  22919. }
  22920. // result equals false (or undefined)
  22921. if (ori !== "true" && ori !== "false") {
  22922. if (ori[0] === "!") {
  22923. result = !evaluateCallback(ori.substring(1));
  22924. }
  22925. else {
  22926. result = evaluateCallback(ori);
  22927. }
  22928. }
  22929. else {
  22930. result = ori === "true" ? true : false;
  22931. }
  22932. }
  22933. // the whole parenthesis scope is replaced by 'true' or 'false'
  22934. return result ? "true" : "false";
  22935. };
  22936. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  22937. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  22938. // remove whitespaces
  22939. r = r.replace(/[\s]/g, function () { return ""; });
  22940. return r.length % 2 ? "!" : "";
  22941. });
  22942. booleanString = booleanString.trim();
  22943. if (booleanString === "!true") {
  22944. booleanString = "false";
  22945. }
  22946. else if (booleanString === "!false") {
  22947. booleanString = "true";
  22948. }
  22949. return booleanString;
  22950. };
  22951. return AndOrNotEvaluator;
  22952. })();
  22953. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  22954. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22955. })(BABYLON || (BABYLON = {}));
  22956. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  22957. (function (BABYLON) {
  22958. var PostProcessRenderPass = (function () {
  22959. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  22960. this._enabled = true;
  22961. this._refCount = 0;
  22962. this._name = name;
  22963. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  22964. this.setRenderList(renderList);
  22965. this._renderTexture.onBeforeRender = beforeRender;
  22966. this._renderTexture.onAfterRender = afterRender;
  22967. this._scene = scene;
  22968. this._renderList = renderList;
  22969. }
  22970. // private
  22971. PostProcessRenderPass.prototype._incRefCount = function () {
  22972. if (this._refCount === 0) {
  22973. this._scene.customRenderTargets.push(this._renderTexture);
  22974. }
  22975. return ++this._refCount;
  22976. };
  22977. PostProcessRenderPass.prototype._decRefCount = function () {
  22978. this._refCount--;
  22979. if (this._refCount <= 0) {
  22980. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  22981. }
  22982. return this._refCount;
  22983. };
  22984. PostProcessRenderPass.prototype._update = function () {
  22985. this.setRenderList(this._renderList);
  22986. };
  22987. // public
  22988. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  22989. this._renderTexture.renderList = renderList;
  22990. };
  22991. PostProcessRenderPass.prototype.getRenderTexture = function () {
  22992. return this._renderTexture;
  22993. };
  22994. return PostProcessRenderPass;
  22995. })();
  22996. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  22997. })(BABYLON || (BABYLON = {}));
  22998. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  22999. (function (BABYLON) {
  23000. var PostProcessRenderEffect = (function () {
  23001. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  23002. this._engine = engine;
  23003. this._name = name;
  23004. this._singleInstance = singleInstance || true;
  23005. this._getPostProcess = getPostProcess;
  23006. this._cameras = [];
  23007. this._indicesForCamera = [];
  23008. this._postProcesses = {};
  23009. this._renderPasses = {};
  23010. this._renderEffectAsPasses = {};
  23011. }
  23012. PostProcessRenderEffect.prototype._update = function () {
  23013. for (var renderPassName in this._renderPasses) {
  23014. this._renderPasses[renderPassName]._update();
  23015. }
  23016. };
  23017. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  23018. this._renderPasses[renderPass._name] = renderPass;
  23019. this._linkParameters();
  23020. };
  23021. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  23022. delete this._renderPasses[renderPass._name];
  23023. this._linkParameters();
  23024. };
  23025. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  23026. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  23027. this._linkParameters();
  23028. };
  23029. PostProcessRenderEffect.prototype.getPass = function (passName) {
  23030. for (var renderPassName in this._renderPasses) {
  23031. if (renderPassName === passName) {
  23032. return this._renderPasses[passName];
  23033. }
  23034. }
  23035. };
  23036. PostProcessRenderEffect.prototype.emptyPasses = function () {
  23037. this._renderPasses = {};
  23038. this._linkParameters();
  23039. };
  23040. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  23041. var cameraKey;
  23042. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23043. for (var i = 0; i < _cam.length; i++) {
  23044. var camera = _cam[i];
  23045. var cameraName = camera.name;
  23046. if (this._singleInstance) {
  23047. cameraKey = 0;
  23048. }
  23049. else {
  23050. cameraKey = cameraName;
  23051. }
  23052. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  23053. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  23054. if (!this._indicesForCamera[cameraName]) {
  23055. this._indicesForCamera[cameraName] = [];
  23056. }
  23057. this._indicesForCamera[cameraName].push(index);
  23058. if (this._cameras.indexOf(camera) === -1) {
  23059. this._cameras[cameraName] = camera;
  23060. }
  23061. for (var passName in this._renderPasses) {
  23062. this._renderPasses[passName]._incRefCount();
  23063. }
  23064. }
  23065. this._linkParameters();
  23066. };
  23067. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  23068. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23069. for (var i = 0; i < _cam.length; i++) {
  23070. var camera = _cam[i];
  23071. var cameraName = camera.name;
  23072. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23073. var index = this._cameras.indexOf(cameraName);
  23074. this._indicesForCamera.splice(index, 1);
  23075. this._cameras.splice(index, 1);
  23076. for (var passName in this._renderPasses) {
  23077. this._renderPasses[passName]._decRefCount();
  23078. }
  23079. }
  23080. };
  23081. PostProcessRenderEffect.prototype._enable = function (cameras) {
  23082. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23083. for (var i = 0; i < _cam.length; i++) {
  23084. var camera = _cam[i];
  23085. var cameraName = camera.name;
  23086. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  23087. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  23088. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  23089. }
  23090. }
  23091. for (var passName in this._renderPasses) {
  23092. this._renderPasses[passName]._incRefCount();
  23093. }
  23094. }
  23095. };
  23096. PostProcessRenderEffect.prototype._disable = function (cameras) {
  23097. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23098. for (var i = 0; i < _cam.length; i++) {
  23099. var camera = _cam[i];
  23100. var cameraName = camera.Name;
  23101. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23102. for (var passName in this._renderPasses) {
  23103. this._renderPasses[passName]._decRefCount();
  23104. }
  23105. }
  23106. };
  23107. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  23108. if (this._singleInstance) {
  23109. return this._postProcesses[0];
  23110. }
  23111. else {
  23112. return this._postProcesses[camera.name];
  23113. }
  23114. };
  23115. PostProcessRenderEffect.prototype._linkParameters = function () {
  23116. var _this = this;
  23117. for (var index in this._postProcesses) {
  23118. if (this.applyParameters) {
  23119. this.applyParameters(this._postProcesses[index]);
  23120. }
  23121. this._postProcesses[index].onBeforeRender = function (effect) {
  23122. _this._linkTextures(effect);
  23123. };
  23124. }
  23125. };
  23126. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  23127. for (var renderPassName in this._renderPasses) {
  23128. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  23129. }
  23130. for (var renderEffectName in this._renderEffectAsPasses) {
  23131. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  23132. }
  23133. };
  23134. return PostProcessRenderEffect;
  23135. })();
  23136. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  23137. })(BABYLON || (BABYLON = {}));
  23138. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  23139. (function (BABYLON) {
  23140. var PostProcessRenderPipeline = (function () {
  23141. function PostProcessRenderPipeline(engine, name) {
  23142. this._engine = engine;
  23143. this._name = name;
  23144. this._renderEffects = {};
  23145. this._renderEffectsForIsolatedPass = {};
  23146. this._cameras = [];
  23147. }
  23148. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  23149. this._renderEffects[renderEffect._name] = renderEffect;
  23150. };
  23151. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  23152. var renderEffects = this._renderEffects[renderEffectName];
  23153. if (!renderEffects) {
  23154. return;
  23155. }
  23156. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23157. };
  23158. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  23159. var renderEffects = this._renderEffects[renderEffectName];
  23160. if (!renderEffects) {
  23161. return;
  23162. }
  23163. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23164. };
  23165. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  23166. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23167. var indicesToDelete = [];
  23168. for (var i = 0; i < _cam.length; i++) {
  23169. var camera = _cam[i];
  23170. var cameraName = camera.name;
  23171. if (this._cameras.indexOf(camera) === -1) {
  23172. this._cameras[cameraName] = camera;
  23173. }
  23174. else if (unique) {
  23175. indicesToDelete.push(i);
  23176. }
  23177. }
  23178. for (var i = 0; i < indicesToDelete.length; i++) {
  23179. cameras.splice(indicesToDelete[i], 1);
  23180. }
  23181. for (var renderEffectName in this._renderEffects) {
  23182. this._renderEffects[renderEffectName]._attachCameras(_cam);
  23183. }
  23184. };
  23185. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  23186. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23187. for (var renderEffectName in this._renderEffects) {
  23188. this._renderEffects[renderEffectName]._detachCameras(_cam);
  23189. }
  23190. for (var i = 0; i < _cam.length; i++) {
  23191. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  23192. }
  23193. };
  23194. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  23195. var _this = this;
  23196. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23197. var pass = null;
  23198. for (var renderEffectName in this._renderEffects) {
  23199. pass = this._renderEffects[renderEffectName].getPass(passName);
  23200. if (pass != null) {
  23201. break;
  23202. }
  23203. }
  23204. if (pass === null) {
  23205. return;
  23206. }
  23207. for (var renderEffectName in this._renderEffects) {
  23208. this._renderEffects[renderEffectName]._disable(_cam);
  23209. }
  23210. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  23211. for (var i = 0; i < _cam.length; i++) {
  23212. var camera = _cam[i];
  23213. var cameraName = camera.name;
  23214. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23215. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23216. });
  23217. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  23218. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  23219. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  23220. }
  23221. };
  23222. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  23223. var _this = this;
  23224. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23225. for (var i = 0; i < _cam.length; i++) {
  23226. var camera = _cam[i];
  23227. var cameraName = camera.name;
  23228. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23229. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23230. });
  23231. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  23232. }
  23233. for (var renderEffectName in this._renderEffects) {
  23234. this._renderEffects[renderEffectName]._enable(_cam);
  23235. }
  23236. };
  23237. PostProcessRenderPipeline.prototype._update = function () {
  23238. for (var renderEffectName in this._renderEffects) {
  23239. this._renderEffects[renderEffectName]._update();
  23240. }
  23241. for (var i = 0; i < this._cameras.length; i++) {
  23242. var cameraName = this._cameras[i].name;
  23243. if (this._renderEffectsForIsolatedPass[cameraName]) {
  23244. this._renderEffectsForIsolatedPass[cameraName]._update();
  23245. }
  23246. }
  23247. };
  23248. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  23249. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  23250. return PostProcessRenderPipeline;
  23251. })();
  23252. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  23253. })(BABYLON || (BABYLON = {}));
  23254. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  23255. (function (BABYLON) {
  23256. var PostProcessRenderPipelineManager = (function () {
  23257. function PostProcessRenderPipelineManager() {
  23258. this._renderPipelines = {};
  23259. }
  23260. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  23261. this._renderPipelines[renderPipeline._name] = renderPipeline;
  23262. };
  23263. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  23264. var renderPipeline = this._renderPipelines[renderPipelineName];
  23265. if (!renderPipeline) {
  23266. return;
  23267. }
  23268. renderPipeline._attachCameras(cameras, unique);
  23269. };
  23270. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  23271. var renderPipeline = this._renderPipelines[renderPipelineName];
  23272. if (!renderPipeline) {
  23273. return;
  23274. }
  23275. renderPipeline._detachCameras(cameras);
  23276. };
  23277. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23278. var renderPipeline = this._renderPipelines[renderPipelineName];
  23279. if (!renderPipeline) {
  23280. return;
  23281. }
  23282. renderPipeline._enableEffect(renderEffectName, cameras);
  23283. };
  23284. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23285. var renderPipeline = this._renderPipelines[renderPipelineName];
  23286. if (!renderPipeline) {
  23287. return;
  23288. }
  23289. renderPipeline._disableEffect(renderEffectName, cameras);
  23290. };
  23291. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  23292. var renderPipeline = this._renderPipelines[renderPipelineName];
  23293. if (!renderPipeline) {
  23294. return;
  23295. }
  23296. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  23297. };
  23298. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  23299. var renderPipeline = this._renderPipelines[renderPipelineName];
  23300. if (!renderPipeline) {
  23301. return;
  23302. }
  23303. renderPipeline._disableDisplayOnlyPass(cameras);
  23304. };
  23305. PostProcessRenderPipelineManager.prototype.update = function () {
  23306. for (var renderPipelineName in this._renderPipelines) {
  23307. this._renderPipelines[renderPipelineName]._update();
  23308. }
  23309. };
  23310. return PostProcessRenderPipelineManager;
  23311. })();
  23312. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  23313. })(BABYLON || (BABYLON = {}));
  23314. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  23315. var BABYLON;
  23316. (function (BABYLON) {
  23317. var DisplayPassPostProcess = (function (_super) {
  23318. __extends(DisplayPassPostProcess, _super);
  23319. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23320. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  23321. }
  23322. return DisplayPassPostProcess;
  23323. })(BABYLON.PostProcess);
  23324. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  23325. })(BABYLON || (BABYLON = {}));
  23326. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  23327. (function (BABYLON) {
  23328. var BoundingBoxRenderer = (function () {
  23329. function BoundingBoxRenderer(scene) {
  23330. this.frontColor = new BABYLON.Color3(1, 1, 1);
  23331. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  23332. this.showBackLines = true;
  23333. this.renderList = new BABYLON.SmartArray(32);
  23334. this._scene = scene;
  23335. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  23336. attributes: ["position"],
  23337. uniforms: ["worldViewProjection", "color"]
  23338. });
  23339. var engine = this._scene.getEngine();
  23340. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  23341. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  23342. 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]);
  23343. }
  23344. BoundingBoxRenderer.prototype.reset = function () {
  23345. this.renderList.reset();
  23346. };
  23347. BoundingBoxRenderer.prototype.render = function () {
  23348. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  23349. return;
  23350. }
  23351. var engine = this._scene.getEngine();
  23352. engine.setDepthWrite(false);
  23353. this._colorShader._preBind();
  23354. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  23355. var boundingBox = this.renderList.data[boundingBoxIndex];
  23356. var min = boundingBox.minimum;
  23357. var max = boundingBox.maximum;
  23358. var diff = max.subtract(min);
  23359. var median = min.add(diff.scale(0.5));
  23360. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  23361. // VBOs
  23362. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  23363. if (this.showBackLines) {
  23364. // Back
  23365. engine.setDepthFunctionToGreaterOrEqual();
  23366. this._scene.resetCachedMaterial();
  23367. this._colorShader.setColor4("color", this.backColor.toColor4());
  23368. this._colorShader.bind(worldMatrix);
  23369. // Draw order
  23370. engine.draw(false, 0, 24);
  23371. }
  23372. // Front
  23373. engine.setDepthFunctionToLess();
  23374. this._scene.resetCachedMaterial();
  23375. this._colorShader.setColor4("color", this.frontColor.toColor4());
  23376. this._colorShader.bind(worldMatrix);
  23377. // Draw order
  23378. engine.draw(false, 0, 24);
  23379. }
  23380. this._colorShader.unbind();
  23381. engine.setDepthFunctionToLessOrEqual();
  23382. engine.setDepthWrite(true);
  23383. };
  23384. BoundingBoxRenderer.prototype.dispose = function () {
  23385. this._colorShader.dispose();
  23386. this._vb.dispose();
  23387. this._scene.getEngine()._releaseBuffer(this._ib);
  23388. };
  23389. return BoundingBoxRenderer;
  23390. })();
  23391. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  23392. })(BABYLON || (BABYLON = {}));
  23393. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  23394. (function (BABYLON) {
  23395. var Internals;
  23396. (function (Internals) {
  23397. /*
  23398. * Based on jsTGALoader - Javascript loader for TGA file
  23399. * By Vincent Thibault
  23400. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  23401. */
  23402. var TGATools = (function () {
  23403. function TGATools() {
  23404. }
  23405. TGATools.GetTGAHeader = function (data) {
  23406. var offset = 0;
  23407. var header = {
  23408. id_length: data[offset++],
  23409. colormap_type: data[offset++],
  23410. image_type: data[offset++],
  23411. colormap_index: data[offset++] | data[offset++] << 8,
  23412. colormap_length: data[offset++] | data[offset++] << 8,
  23413. colormap_size: data[offset++],
  23414. origin: [
  23415. data[offset++] | data[offset++] << 8,
  23416. data[offset++] | data[offset++] << 8
  23417. ],
  23418. width: data[offset++] | data[offset++] << 8,
  23419. height: data[offset++] | data[offset++] << 8,
  23420. pixel_size: data[offset++],
  23421. flags: data[offset++]
  23422. };
  23423. return header;
  23424. };
  23425. TGATools.UploadContent = function (gl, data) {
  23426. // Not enough data to contain header ?
  23427. if (data.length < 19) {
  23428. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  23429. return;
  23430. }
  23431. // Read Header
  23432. var offset = 18;
  23433. var header = TGATools.GetTGAHeader(data);
  23434. // Assume it's a valid Targa file.
  23435. if (header.id_length + offset > data.length) {
  23436. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  23437. return;
  23438. }
  23439. // Skip not needed data
  23440. offset += header.id_length;
  23441. var use_rle = false;
  23442. var use_pal = false;
  23443. var use_rgb = false;
  23444. var use_grey = false;
  23445. switch (header.image_type) {
  23446. case TGATools._TYPE_RLE_INDEXED:
  23447. use_rle = true;
  23448. case TGATools._TYPE_INDEXED:
  23449. use_pal = true;
  23450. break;
  23451. case TGATools._TYPE_RLE_RGB:
  23452. use_rle = true;
  23453. case TGATools._TYPE_RGB:
  23454. use_rgb = true;
  23455. break;
  23456. case TGATools._TYPE_RLE_GREY:
  23457. use_rle = true;
  23458. case TGATools._TYPE_GREY:
  23459. use_grey = true;
  23460. break;
  23461. }
  23462. var pixel_data;
  23463. var numAlphaBits = header.flags & 0xf;
  23464. var pixel_size = header.pixel_size >> 3;
  23465. var pixel_total = header.width * header.height * pixel_size;
  23466. // Read palettes
  23467. var palettes;
  23468. if (use_pal) {
  23469. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  23470. }
  23471. // Read LRE
  23472. if (use_rle) {
  23473. pixel_data = new Uint8Array(pixel_total);
  23474. var c, count, i;
  23475. var localOffset = 0;
  23476. var pixels = new Uint8Array(pixel_size);
  23477. while (offset < pixel_total && localOffset < pixel_total) {
  23478. c = data[offset++];
  23479. count = (c & 0x7f) + 1;
  23480. // RLE pixels
  23481. if (c & 0x80) {
  23482. for (i = 0; i < pixel_size; ++i) {
  23483. pixels[i] = data[offset++];
  23484. }
  23485. for (i = 0; i < count; ++i) {
  23486. pixel_data.set(pixels, localOffset + i * pixel_size);
  23487. }
  23488. localOffset += pixel_size * count;
  23489. }
  23490. else {
  23491. count *= pixel_size;
  23492. for (i = 0; i < count; ++i) {
  23493. pixel_data[localOffset + i] = data[offset++];
  23494. }
  23495. localOffset += count;
  23496. }
  23497. }
  23498. }
  23499. else {
  23500. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  23501. }
  23502. // Load to texture
  23503. var x_start, y_start, x_step, y_step, y_end, x_end;
  23504. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  23505. default:
  23506. case TGATools._ORIGIN_UL:
  23507. x_start = 0;
  23508. x_step = 1;
  23509. x_end = header.width;
  23510. y_start = 0;
  23511. y_step = 1;
  23512. y_end = header.height;
  23513. break;
  23514. case TGATools._ORIGIN_BL:
  23515. x_start = 0;
  23516. x_step = 1;
  23517. x_end = header.width;
  23518. y_start = header.height - 1;
  23519. y_step = -1;
  23520. y_end = -1;
  23521. break;
  23522. case TGATools._ORIGIN_UR:
  23523. x_start = header.width - 1;
  23524. x_step = -1;
  23525. x_end = -1;
  23526. y_start = 0;
  23527. y_step = 1;
  23528. y_end = header.height;
  23529. break;
  23530. case TGATools._ORIGIN_BR:
  23531. x_start = header.width - 1;
  23532. x_step = -1;
  23533. x_end = -1;
  23534. y_start = header.height - 1;
  23535. y_step = -1;
  23536. y_end = -1;
  23537. break;
  23538. }
  23539. // Load the specify method
  23540. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  23541. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  23542. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  23543. };
  23544. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23545. var image = pixel_data, colormap = palettes;
  23546. var width = header.width, height = header.height;
  23547. var color, i = 0, x, y;
  23548. var imageData = new Uint8Array(width * height * 4);
  23549. for (y = y_start; y !== y_end; y += y_step) {
  23550. for (x = x_start; x !== x_end; x += x_step, i++) {
  23551. color = image[i];
  23552. imageData[(x + width * y) * 4 + 3] = 255;
  23553. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  23554. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  23555. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  23556. }
  23557. }
  23558. return imageData;
  23559. };
  23560. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23561. var image = pixel_data;
  23562. var width = header.width, height = header.height;
  23563. var color, i = 0, x, y;
  23564. var imageData = new Uint8Array(width * height * 4);
  23565. for (y = y_start; y !== y_end; y += y_step) {
  23566. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23567. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  23568. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  23569. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  23570. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  23571. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  23572. }
  23573. }
  23574. return imageData;
  23575. };
  23576. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23577. var image = pixel_data;
  23578. var width = header.width, height = header.height;
  23579. var i = 0, x, y;
  23580. var imageData = new Uint8Array(width * height * 4);
  23581. for (y = y_start; y !== y_end; y += y_step) {
  23582. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  23583. imageData[(x + width * y) * 4 + 3] = 255;
  23584. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23585. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23586. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23587. }
  23588. }
  23589. return imageData;
  23590. };
  23591. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23592. var image = pixel_data;
  23593. var width = header.width, height = header.height;
  23594. var i = 0, x, y;
  23595. var imageData = new Uint8Array(width * height * 4);
  23596. for (y = y_start; y !== y_end; y += y_step) {
  23597. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  23598. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23599. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23600. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23601. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  23602. }
  23603. }
  23604. return imageData;
  23605. };
  23606. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23607. var image = pixel_data;
  23608. var width = header.width, height = header.height;
  23609. var color, i = 0, x, y;
  23610. var imageData = new Uint8Array(width * height * 4);
  23611. for (y = y_start; y !== y_end; y += y_step) {
  23612. for (x = x_start; x !== x_end; x += x_step, i++) {
  23613. color = image[i];
  23614. imageData[(x + width * y) * 4 + 0] = color;
  23615. imageData[(x + width * y) * 4 + 1] = color;
  23616. imageData[(x + width * y) * 4 + 2] = color;
  23617. imageData[(x + width * y) * 4 + 3] = 255;
  23618. }
  23619. }
  23620. return imageData;
  23621. };
  23622. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23623. var image = pixel_data;
  23624. var width = header.width, height = header.height;
  23625. var i = 0, x, y;
  23626. var imageData = new Uint8Array(width * height * 4);
  23627. for (y = y_start; y !== y_end; y += y_step) {
  23628. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23629. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  23630. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  23631. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23632. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  23633. }
  23634. }
  23635. return imageData;
  23636. };
  23637. TGATools._TYPE_NO_DATA = 0;
  23638. TGATools._TYPE_INDEXED = 1;
  23639. TGATools._TYPE_RGB = 2;
  23640. TGATools._TYPE_GREY = 3;
  23641. TGATools._TYPE_RLE_INDEXED = 9;
  23642. TGATools._TYPE_RLE_RGB = 10;
  23643. TGATools._TYPE_RLE_GREY = 11;
  23644. TGATools._ORIGIN_MASK = 0x30;
  23645. TGATools._ORIGIN_SHIFT = 0x04;
  23646. TGATools._ORIGIN_BL = 0x00;
  23647. TGATools._ORIGIN_BR = 0x01;
  23648. TGATools._ORIGIN_UL = 0x02;
  23649. TGATools._ORIGIN_UR = 0x03;
  23650. return TGATools;
  23651. })();
  23652. Internals.TGATools = TGATools;
  23653. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23654. })(BABYLON || (BABYLON = {}));
  23655. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  23656. (function (BABYLON) {
  23657. var Internals;
  23658. (function (Internals) {
  23659. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  23660. // All values and structures referenced from:
  23661. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  23662. var DDS_MAGIC = 0x20534444;
  23663. 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;
  23664. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  23665. 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;
  23666. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  23667. function FourCCToInt32(value) {
  23668. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  23669. }
  23670. function Int32ToFourCC(value) {
  23671. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  23672. }
  23673. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  23674. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  23675. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  23676. var headerLengthInt = 31; // The header length in 32 bit ints
  23677. // Offsets into the header array
  23678. var off_magic = 0;
  23679. var off_size = 1;
  23680. var off_flags = 2;
  23681. var off_height = 3;
  23682. var off_width = 4;
  23683. var off_mipmapCount = 7;
  23684. var off_pfFlags = 20;
  23685. var off_pfFourCC = 21;
  23686. var off_RGBbpp = 22;
  23687. var off_RMask = 23;
  23688. var off_GMask = 24;
  23689. var off_BMask = 25;
  23690. var off_AMask = 26;
  23691. var off_caps1 = 27;
  23692. var off_caps2 = 28;
  23693. ;
  23694. var DDSTools = (function () {
  23695. function DDSTools() {
  23696. }
  23697. DDSTools.GetDDSInfo = function (arrayBuffer) {
  23698. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  23699. var mipmapCount = 1;
  23700. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  23701. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23702. }
  23703. return {
  23704. width: header[off_width],
  23705. height: header[off_height],
  23706. mipmapCount: mipmapCount,
  23707. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  23708. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  23709. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  23710. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  23711. };
  23712. };
  23713. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23714. var byteArray = new Uint8Array(dataLength);
  23715. var srcData = new Uint8Array(arrayBuffer);
  23716. var index = 0;
  23717. for (var y = height - 1; y >= 0; y--) {
  23718. for (var x = 0; x < width; x++) {
  23719. var srcPos = dataOffset + (x + y * width) * 4;
  23720. byteArray[index + 2] = srcData[srcPos];
  23721. byteArray[index + 1] = srcData[srcPos + 1];
  23722. byteArray[index] = srcData[srcPos + 2];
  23723. byteArray[index + 3] = srcData[srcPos + 3];
  23724. index += 4;
  23725. }
  23726. }
  23727. return byteArray;
  23728. };
  23729. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23730. var byteArray = new Uint8Array(dataLength);
  23731. var srcData = new Uint8Array(arrayBuffer);
  23732. var index = 0;
  23733. for (var y = height - 1; y >= 0; y--) {
  23734. for (var x = 0; x < width; x++) {
  23735. var srcPos = dataOffset + (x + y * width) * 3;
  23736. byteArray[index + 2] = srcData[srcPos];
  23737. byteArray[index + 1] = srcData[srcPos + 1];
  23738. byteArray[index] = srcData[srcPos + 2];
  23739. index += 3;
  23740. }
  23741. }
  23742. return byteArray;
  23743. };
  23744. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23745. var byteArray = new Uint8Array(dataLength);
  23746. var srcData = new Uint8Array(arrayBuffer);
  23747. var index = 0;
  23748. for (var y = height - 1; y >= 0; y--) {
  23749. for (var x = 0; x < width; x++) {
  23750. var srcPos = dataOffset + (x + y * width);
  23751. byteArray[index] = srcData[srcPos];
  23752. index++;
  23753. }
  23754. }
  23755. return byteArray;
  23756. };
  23757. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  23758. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  23759. if (header[off_magic] != DDS_MAGIC) {
  23760. BABYLON.Tools.Error("Invalid magic number in DDS header");
  23761. return;
  23762. }
  23763. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  23764. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  23765. return;
  23766. }
  23767. if (info.isFourCC) {
  23768. fourCC = header[off_pfFourCC];
  23769. switch (fourCC) {
  23770. case FOURCC_DXT1:
  23771. blockBytes = 8;
  23772. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  23773. break;
  23774. case FOURCC_DXT3:
  23775. blockBytes = 16;
  23776. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  23777. break;
  23778. case FOURCC_DXT5:
  23779. blockBytes = 16;
  23780. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  23781. break;
  23782. default:
  23783. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  23784. return;
  23785. }
  23786. }
  23787. mipmapCount = 1;
  23788. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  23789. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23790. }
  23791. var bpp = header[off_RGBbpp];
  23792. for (var face = 0; face < faces; face++) {
  23793. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  23794. width = header[off_width];
  23795. height = header[off_height];
  23796. dataOffset = header[off_size] + 4;
  23797. for (i = 0; i < mipmapCount; ++i) {
  23798. if (info.isRGB) {
  23799. if (bpp == 24) {
  23800. dataLength = width * height * 3;
  23801. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23802. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  23803. }
  23804. else {
  23805. dataLength = width * height * 4;
  23806. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23807. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  23808. }
  23809. }
  23810. else if (info.isLuminance) {
  23811. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  23812. var unpaddedRowSize = width;
  23813. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  23814. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  23815. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23816. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  23817. }
  23818. else {
  23819. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  23820. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  23821. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  23822. }
  23823. dataOffset += dataLength;
  23824. width *= 0.5;
  23825. height *= 0.5;
  23826. width = Math.max(1.0, width);
  23827. height = Math.max(1.0, height);
  23828. }
  23829. }
  23830. };
  23831. return DDSTools;
  23832. })();
  23833. Internals.DDSTools = DDSTools;
  23834. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23835. })(BABYLON || (BABYLON = {}));
  23836. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  23837. (function (BABYLON) {
  23838. var SmartArray = (function () {
  23839. function SmartArray(capacity) {
  23840. this.length = 0;
  23841. this._duplicateId = 0;
  23842. this.data = new Array(capacity);
  23843. this._id = SmartArray._GlobalId++;
  23844. }
  23845. SmartArray.prototype.push = function (value) {
  23846. this.data[this.length++] = value;
  23847. if (this.length > this.data.length) {
  23848. this.data.length *= 2;
  23849. }
  23850. if (!value.__smartArrayFlags) {
  23851. value.__smartArrayFlags = {};
  23852. }
  23853. value.__smartArrayFlags[this._id] = this._duplicateId;
  23854. };
  23855. SmartArray.prototype.pushNoDuplicate = function (value) {
  23856. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  23857. return;
  23858. }
  23859. this.push(value);
  23860. };
  23861. SmartArray.prototype.sort = function (compareFn) {
  23862. this.data.sort(compareFn);
  23863. };
  23864. SmartArray.prototype.reset = function () {
  23865. this.length = 0;
  23866. this._duplicateId++;
  23867. };
  23868. SmartArray.prototype.concat = function (array) {
  23869. if (array.length === 0) {
  23870. return;
  23871. }
  23872. if (this.length + array.length > this.data.length) {
  23873. this.data.length = (this.length + array.length) * 2;
  23874. }
  23875. for (var index = 0; index < array.length; index++) {
  23876. this.data[this.length++] = (array.data || array)[index];
  23877. }
  23878. };
  23879. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  23880. if (array.length === 0) {
  23881. return;
  23882. }
  23883. if (this.length + array.length > this.data.length) {
  23884. this.data.length = (this.length + array.length) * 2;
  23885. }
  23886. for (var index = 0; index < array.length; index++) {
  23887. var item = (array.data || array)[index];
  23888. this.pushNoDuplicate(item);
  23889. }
  23890. };
  23891. SmartArray.prototype.indexOf = function (value) {
  23892. var position = this.data.indexOf(value);
  23893. if (position >= this.length) {
  23894. return -1;
  23895. }
  23896. return position;
  23897. };
  23898. // Statics
  23899. SmartArray._GlobalId = 0;
  23900. return SmartArray;
  23901. })();
  23902. BABYLON.SmartArray = SmartArray;
  23903. })(BABYLON || (BABYLON = {}));
  23904. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  23905. (function (BABYLON) {
  23906. var CannonJSPlugin = (function () {
  23907. function CannonJSPlugin() {
  23908. this._registeredMeshes = [];
  23909. this._physicsMaterials = [];
  23910. this.updateBodyPosition = function (mesh) {
  23911. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23912. var registeredMesh = this._registeredMeshes[index];
  23913. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23914. var body = registeredMesh.body;
  23915. var center = mesh.getBoundingInfo().boundingBox.center;
  23916. body.position.set(center.x, center.z, center.y);
  23917. body.quaternion.x = mesh.rotationQuaternion.x;
  23918. body.quaternion.z = mesh.rotationQuaternion.y;
  23919. body.quaternion.y = mesh.rotationQuaternion.z;
  23920. body.quaternion.w = -mesh.rotationQuaternion.w;
  23921. return;
  23922. }
  23923. }
  23924. };
  23925. }
  23926. CannonJSPlugin.prototype.initialize = function (iterations) {
  23927. if (iterations === void 0) { iterations = 10; }
  23928. this._world = new CANNON.World();
  23929. this._world.broadphase = new CANNON.NaiveBroadphase();
  23930. this._world.solver.iterations = iterations;
  23931. };
  23932. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23933. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23934. };
  23935. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23936. this._world.step(delta);
  23937. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23938. var registeredMesh = this._registeredMeshes[index];
  23939. if (registeredMesh.isChild) {
  23940. continue;
  23941. }
  23942. // Body position
  23943. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23944. var deltaPos = registeredMesh.delta;
  23945. if (deltaPos) {
  23946. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23947. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23948. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23949. }
  23950. else {
  23951. registeredMesh.mesh.position.x = bodyX;
  23952. registeredMesh.mesh.position.y = bodyZ;
  23953. registeredMesh.mesh.position.z = bodyY;
  23954. }
  23955. if (!registeredMesh.mesh.rotationQuaternion) {
  23956. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23957. }
  23958. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23959. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23960. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23961. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23962. }
  23963. };
  23964. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23965. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23966. };
  23967. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23968. this.unregisterMesh(mesh);
  23969. mesh.computeWorldMatrix(true);
  23970. switch (impostor) {
  23971. case BABYLON.PhysicsEngine.SphereImpostor:
  23972. var bbox = mesh.getBoundingInfo().boundingBox;
  23973. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23974. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23975. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23976. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23977. case BABYLON.PhysicsEngine.BoxImpostor:
  23978. bbox = mesh.getBoundingInfo().boundingBox;
  23979. var min = bbox.minimumWorld;
  23980. var max = bbox.maximumWorld;
  23981. var box = max.subtract(min).scale(0.5);
  23982. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23983. case BABYLON.PhysicsEngine.PlaneImpostor:
  23984. return this._createPlane(mesh, options);
  23985. case BABYLON.PhysicsEngine.MeshImpostor:
  23986. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23987. var rawFaces = mesh.getIndices();
  23988. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23989. }
  23990. return null;
  23991. };
  23992. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23993. var shape = new CANNON.Sphere(radius);
  23994. if (!options) {
  23995. return shape;
  23996. }
  23997. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23998. };
  23999. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  24000. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  24001. if (!options) {
  24002. return shape;
  24003. }
  24004. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24005. };
  24006. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  24007. var shape = new CANNON.Plane();
  24008. if (!options) {
  24009. return shape;
  24010. }
  24011. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24012. };
  24013. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  24014. var verts = [], faces = [];
  24015. mesh.computeWorldMatrix(true);
  24016. for (var i = 0; i < rawVerts.length; i += 3) {
  24017. var transformed = BABYLON.Vector3.Zero();
  24018. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  24019. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  24020. }
  24021. for (var j = 0; j < rawFaces.length; j += 3) {
  24022. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  24023. }
  24024. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  24025. if (!options) {
  24026. return shape;
  24027. }
  24028. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24029. };
  24030. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  24031. var index;
  24032. var mat;
  24033. for (index = 0; index < this._physicsMaterials.length; index++) {
  24034. mat = this._physicsMaterials[index];
  24035. if (mat.friction === friction && mat.restitution === restitution) {
  24036. return mat;
  24037. }
  24038. }
  24039. var currentMat = new CANNON.Material();
  24040. currentMat.friction = friction;
  24041. currentMat.restitution = restitution;
  24042. this._physicsMaterials.push(currentMat);
  24043. for (index = 0; index < this._physicsMaterials.length; index++) {
  24044. mat = this._physicsMaterials[index];
  24045. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  24046. contactMaterial.contactEquationStiffness = 1e10;
  24047. contactMaterial.contactEquationRegularizationTime = 10;
  24048. this._world.addContactMaterial(contactMaterial);
  24049. }
  24050. return currentMat;
  24051. };
  24052. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  24053. var initialRotation = null;
  24054. if (mesh.rotationQuaternion) {
  24055. initialRotation = mesh.rotationQuaternion.clone();
  24056. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24057. }
  24058. // The delta between the mesh position and the mesh bounding box center
  24059. var bbox = mesh.getBoundingInfo().boundingBox;
  24060. var deltaPosition = mesh.position.subtract(bbox.center);
  24061. var material = this._addMaterial(friction, restitution);
  24062. var body = new CANNON.RigidBody(mass, shape, material);
  24063. if (initialRotation) {
  24064. body.quaternion.x = initialRotation.x;
  24065. body.quaternion.z = initialRotation.y;
  24066. body.quaternion.y = initialRotation.z;
  24067. body.quaternion.w = -initialRotation.w;
  24068. }
  24069. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  24070. this._world.add(body);
  24071. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  24072. return body;
  24073. };
  24074. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  24075. var compoundShape = new CANNON.Compound();
  24076. for (var index = 0; index < parts.length; index++) {
  24077. var mesh = parts[index].mesh;
  24078. var shape = this.registerMesh(mesh, parts[index].impostor);
  24079. if (index == 0) {
  24080. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  24081. }
  24082. else {
  24083. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  24084. }
  24085. }
  24086. var initialMesh = parts[0].mesh;
  24087. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  24088. body.parts = parts;
  24089. return body;
  24090. };
  24091. CannonJSPlugin.prototype._unbindBody = function (body) {
  24092. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24093. var registeredMesh = this._registeredMeshes[index];
  24094. if (registeredMesh.body === body) {
  24095. registeredMesh.body = null;
  24096. registeredMesh.delta = 0;
  24097. }
  24098. }
  24099. };
  24100. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  24101. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24102. var registeredMesh = this._registeredMeshes[index];
  24103. if (registeredMesh.mesh === mesh) {
  24104. // Remove body
  24105. if (registeredMesh.body) {
  24106. this._world.remove(registeredMesh.body);
  24107. this._unbindBody(registeredMesh.body);
  24108. }
  24109. this._registeredMeshes.splice(index, 1);
  24110. return;
  24111. }
  24112. }
  24113. };
  24114. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  24115. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  24116. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  24117. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24118. var registeredMesh = this._registeredMeshes[index];
  24119. if (registeredMesh.mesh === mesh) {
  24120. registeredMesh.body.applyImpulse(impulse, worldPoint);
  24121. return;
  24122. }
  24123. }
  24124. };
  24125. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  24126. var body1 = null, body2 = null;
  24127. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24128. var registeredMesh = this._registeredMeshes[index];
  24129. if (registeredMesh.mesh === mesh1) {
  24130. body1 = registeredMesh.body;
  24131. }
  24132. else if (registeredMesh.mesh === mesh2) {
  24133. body2 = registeredMesh.body;
  24134. }
  24135. }
  24136. if (!body1 || !body2) {
  24137. return false;
  24138. }
  24139. 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));
  24140. this._world.addConstraint(constraint);
  24141. return true;
  24142. };
  24143. CannonJSPlugin.prototype.dispose = function () {
  24144. while (this._registeredMeshes.length) {
  24145. this.unregisterMesh(this._registeredMeshes[0].mesh);
  24146. }
  24147. };
  24148. CannonJSPlugin.prototype.isSupported = function () {
  24149. return window.CANNON !== undefined;
  24150. };
  24151. return CannonJSPlugin;
  24152. })();
  24153. BABYLON.CannonJSPlugin = CannonJSPlugin;
  24154. })(BABYLON || (BABYLON = {}));
  24155. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  24156. var BABYLON;
  24157. (function (BABYLON) {
  24158. var Condition = (function () {
  24159. function Condition(actionManager) {
  24160. this._actionManager = actionManager;
  24161. }
  24162. Condition.prototype.isValid = function () {
  24163. return true;
  24164. };
  24165. Condition.prototype._getProperty = function (propertyPath) {
  24166. return this._actionManager._getProperty(propertyPath);
  24167. };
  24168. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  24169. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24170. };
  24171. return Condition;
  24172. })();
  24173. BABYLON.Condition = Condition;
  24174. var ValueCondition = (function (_super) {
  24175. __extends(ValueCondition, _super);
  24176. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  24177. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  24178. _super.call(this, actionManager);
  24179. this.propertyPath = propertyPath;
  24180. this.value = value;
  24181. this.operator = operator;
  24182. this._target = this._getEffectiveTarget(target, this.propertyPath);
  24183. this._property = this._getProperty(this.propertyPath);
  24184. }
  24185. Object.defineProperty(ValueCondition, "IsEqual", {
  24186. get: function () {
  24187. return ValueCondition._IsEqual;
  24188. },
  24189. enumerable: true,
  24190. configurable: true
  24191. });
  24192. Object.defineProperty(ValueCondition, "IsDifferent", {
  24193. get: function () {
  24194. return ValueCondition._IsDifferent;
  24195. },
  24196. enumerable: true,
  24197. configurable: true
  24198. });
  24199. Object.defineProperty(ValueCondition, "IsGreater", {
  24200. get: function () {
  24201. return ValueCondition._IsGreater;
  24202. },
  24203. enumerable: true,
  24204. configurable: true
  24205. });
  24206. Object.defineProperty(ValueCondition, "IsLesser", {
  24207. get: function () {
  24208. return ValueCondition._IsLesser;
  24209. },
  24210. enumerable: true,
  24211. configurable: true
  24212. });
  24213. // Methods
  24214. ValueCondition.prototype.isValid = function () {
  24215. switch (this.operator) {
  24216. case ValueCondition.IsGreater:
  24217. return this._target[this._property] > this.value;
  24218. case ValueCondition.IsLesser:
  24219. return this._target[this._property] < this.value;
  24220. case ValueCondition.IsEqual:
  24221. case ValueCondition.IsDifferent:
  24222. var check;
  24223. if (this.value.equals) {
  24224. check = this.value.equals(this._target[this._property]);
  24225. }
  24226. else {
  24227. check = this.value === this._target[this._property];
  24228. }
  24229. return this.operator === ValueCondition.IsEqual ? check : !check;
  24230. }
  24231. return false;
  24232. };
  24233. // Statics
  24234. ValueCondition._IsEqual = 0;
  24235. ValueCondition._IsDifferent = 1;
  24236. ValueCondition._IsGreater = 2;
  24237. ValueCondition._IsLesser = 3;
  24238. return ValueCondition;
  24239. })(Condition);
  24240. BABYLON.ValueCondition = ValueCondition;
  24241. var PredicateCondition = (function (_super) {
  24242. __extends(PredicateCondition, _super);
  24243. function PredicateCondition(actionManager, predicate) {
  24244. _super.call(this, actionManager);
  24245. this.predicate = predicate;
  24246. }
  24247. PredicateCondition.prototype.isValid = function () {
  24248. return this.predicate();
  24249. };
  24250. return PredicateCondition;
  24251. })(Condition);
  24252. BABYLON.PredicateCondition = PredicateCondition;
  24253. var StateCondition = (function (_super) {
  24254. __extends(StateCondition, _super);
  24255. function StateCondition(actionManager, target, value) {
  24256. _super.call(this, actionManager);
  24257. this.value = value;
  24258. this._target = target;
  24259. }
  24260. // Methods
  24261. StateCondition.prototype.isValid = function () {
  24262. return this._target.state === this.value;
  24263. };
  24264. return StateCondition;
  24265. })(Condition);
  24266. BABYLON.StateCondition = StateCondition;
  24267. })(BABYLON || (BABYLON = {}));
  24268. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  24269. (function (BABYLON) {
  24270. var Action = (function () {
  24271. function Action(triggerOptions, condition) {
  24272. this.triggerOptions = triggerOptions;
  24273. if (triggerOptions.parameter) {
  24274. this.trigger = triggerOptions.trigger;
  24275. this._triggerParameter = triggerOptions.parameter;
  24276. }
  24277. else {
  24278. this.trigger = triggerOptions;
  24279. }
  24280. this._nextActiveAction = this;
  24281. this._condition = condition;
  24282. }
  24283. // Methods
  24284. Action.prototype._prepare = function () {
  24285. };
  24286. Action.prototype.getTriggerParameter = function () {
  24287. return this._triggerParameter;
  24288. };
  24289. Action.prototype._executeCurrent = function (evt) {
  24290. if (this._nextActiveAction._condition) {
  24291. var condition = this._nextActiveAction._condition;
  24292. var currentRenderId = this._actionManager.getScene().getRenderId();
  24293. // We cache the current evaluation for the current frame
  24294. if (condition._evaluationId === currentRenderId) {
  24295. if (!condition._currentResult) {
  24296. return;
  24297. }
  24298. }
  24299. else {
  24300. condition._evaluationId = currentRenderId;
  24301. if (!condition.isValid()) {
  24302. condition._currentResult = false;
  24303. return;
  24304. }
  24305. condition._currentResult = true;
  24306. }
  24307. }
  24308. this._nextActiveAction.execute(evt);
  24309. if (this._nextActiveAction._child) {
  24310. if (!this._nextActiveAction._child._actionManager) {
  24311. this._nextActiveAction._child._actionManager = this._actionManager;
  24312. }
  24313. this._nextActiveAction = this._nextActiveAction._child;
  24314. }
  24315. else {
  24316. this._nextActiveAction = this;
  24317. }
  24318. };
  24319. Action.prototype.execute = function (evt) {
  24320. };
  24321. Action.prototype.then = function (action) {
  24322. this._child = action;
  24323. action._actionManager = this._actionManager;
  24324. action._prepare();
  24325. return action;
  24326. };
  24327. Action.prototype._getProperty = function (propertyPath) {
  24328. return this._actionManager._getProperty(propertyPath);
  24329. };
  24330. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  24331. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24332. };
  24333. return Action;
  24334. })();
  24335. BABYLON.Action = Action;
  24336. })(BABYLON || (BABYLON = {}));
  24337. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  24338. (function (BABYLON) {
  24339. /**
  24340. * ActionEvent is the event beint sent when an action is triggered.
  24341. */
  24342. var ActionEvent = (function () {
  24343. /**
  24344. * @constructor
  24345. * @param source The mesh that triggered the action.
  24346. * @param pointerX the X mouse cursor position at the time of the event
  24347. * @param pointerY the Y mouse cursor position at the time of the event
  24348. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  24349. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  24350. */
  24351. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  24352. this.source = source;
  24353. this.pointerX = pointerX;
  24354. this.pointerY = pointerY;
  24355. this.meshUnderPointer = meshUnderPointer;
  24356. this.sourceEvent = sourceEvent;
  24357. }
  24358. /**
  24359. * Helper function to auto-create an ActionEvent from a source mesh.
  24360. * @param source the source mesh that triggered the event
  24361. * @param evt {Event} The original (browser) event
  24362. */
  24363. ActionEvent.CreateNew = function (source, evt) {
  24364. var scene = source.getScene();
  24365. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24366. };
  24367. /**
  24368. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  24369. * @param scene the scene where the event occurred
  24370. * @param evt {Event} The original (browser) event
  24371. */
  24372. ActionEvent.CreateNewFromScene = function (scene, evt) {
  24373. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24374. };
  24375. return ActionEvent;
  24376. })();
  24377. BABYLON.ActionEvent = ActionEvent;
  24378. /**
  24379. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  24380. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  24381. */
  24382. var ActionManager = (function () {
  24383. function ActionManager(scene) {
  24384. // Members
  24385. this.actions = new Array();
  24386. this._scene = scene;
  24387. scene._actionManagers.push(this);
  24388. }
  24389. Object.defineProperty(ActionManager, "NothingTrigger", {
  24390. get: function () {
  24391. return ActionManager._NothingTrigger;
  24392. },
  24393. enumerable: true,
  24394. configurable: true
  24395. });
  24396. Object.defineProperty(ActionManager, "OnPickTrigger", {
  24397. get: function () {
  24398. return ActionManager._OnPickTrigger;
  24399. },
  24400. enumerable: true,
  24401. configurable: true
  24402. });
  24403. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  24404. get: function () {
  24405. return ActionManager._OnLeftPickTrigger;
  24406. },
  24407. enumerable: true,
  24408. configurable: true
  24409. });
  24410. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  24411. get: function () {
  24412. return ActionManager._OnRightPickTrigger;
  24413. },
  24414. enumerable: true,
  24415. configurable: true
  24416. });
  24417. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  24418. get: function () {
  24419. return ActionManager._OnCenterPickTrigger;
  24420. },
  24421. enumerable: true,
  24422. configurable: true
  24423. });
  24424. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  24425. get: function () {
  24426. return ActionManager._OnPointerOverTrigger;
  24427. },
  24428. enumerable: true,
  24429. configurable: true
  24430. });
  24431. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  24432. get: function () {
  24433. return ActionManager._OnPointerOutTrigger;
  24434. },
  24435. enumerable: true,
  24436. configurable: true
  24437. });
  24438. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  24439. get: function () {
  24440. return ActionManager._OnEveryFrameTrigger;
  24441. },
  24442. enumerable: true,
  24443. configurable: true
  24444. });
  24445. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  24446. get: function () {
  24447. return ActionManager._OnIntersectionEnterTrigger;
  24448. },
  24449. enumerable: true,
  24450. configurable: true
  24451. });
  24452. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  24453. get: function () {
  24454. return ActionManager._OnIntersectionExitTrigger;
  24455. },
  24456. enumerable: true,
  24457. configurable: true
  24458. });
  24459. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  24460. get: function () {
  24461. return ActionManager._OnKeyDownTrigger;
  24462. },
  24463. enumerable: true,
  24464. configurable: true
  24465. });
  24466. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  24467. get: function () {
  24468. return ActionManager._OnKeyUpTrigger;
  24469. },
  24470. enumerable: true,
  24471. configurable: true
  24472. });
  24473. // Methods
  24474. ActionManager.prototype.dispose = function () {
  24475. var index = this._scene._actionManagers.indexOf(this);
  24476. if (index > -1) {
  24477. this._scene._actionManagers.splice(index, 1);
  24478. }
  24479. };
  24480. ActionManager.prototype.getScene = function () {
  24481. return this._scene;
  24482. };
  24483. /**
  24484. * Does this action manager handles actions of any of the given triggers
  24485. * @param {number[]} triggers - the triggers to be tested
  24486. * @return {boolean} whether one (or more) of the triggers is handeled
  24487. */
  24488. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  24489. for (var index = 0; index < this.actions.length; index++) {
  24490. var action = this.actions[index];
  24491. if (triggers.indexOf(action.trigger) > -1) {
  24492. return true;
  24493. }
  24494. }
  24495. return false;
  24496. };
  24497. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  24498. /**
  24499. * Does this action manager has pointer triggers
  24500. * @return {boolean} whether or not it has pointer triggers
  24501. */
  24502. get: function () {
  24503. for (var index = 0; index < this.actions.length; index++) {
  24504. var action = this.actions[index];
  24505. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  24506. return true;
  24507. }
  24508. }
  24509. return false;
  24510. },
  24511. enumerable: true,
  24512. configurable: true
  24513. });
  24514. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  24515. /**
  24516. * Does this action manager has pick triggers
  24517. * @return {boolean} whether or not it has pick triggers
  24518. */
  24519. get: function () {
  24520. for (var index = 0; index < this.actions.length; index++) {
  24521. var action = this.actions[index];
  24522. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  24523. return true;
  24524. }
  24525. }
  24526. return false;
  24527. },
  24528. enumerable: true,
  24529. configurable: true
  24530. });
  24531. /**
  24532. * Registers an action to this action manager
  24533. * @param {BABYLON.Action} action - the action to be registered
  24534. * @return {BABYLON.Action} the action amended (prepared) after registration
  24535. */
  24536. ActionManager.prototype.registerAction = function (action) {
  24537. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  24538. if (this.getScene().actionManager !== this) {
  24539. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  24540. return null;
  24541. }
  24542. }
  24543. this.actions.push(action);
  24544. action._actionManager = this;
  24545. action._prepare();
  24546. return action;
  24547. };
  24548. /**
  24549. * Process a specific trigger
  24550. * @param {number} trigger - the trigger to process
  24551. * @param evt {BABYLON.ActionEvent} the event details to be processed
  24552. */
  24553. ActionManager.prototype.processTrigger = function (trigger, evt) {
  24554. for (var index = 0; index < this.actions.length; index++) {
  24555. var action = this.actions[index];
  24556. if (action.trigger === trigger) {
  24557. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  24558. var parameter = action.getTriggerParameter();
  24559. if (parameter) {
  24560. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  24561. var actualkey = String.fromCharCode(unicode).toLowerCase();
  24562. if (actualkey !== parameter.toLowerCase()) {
  24563. continue;
  24564. }
  24565. }
  24566. }
  24567. action._executeCurrent(evt);
  24568. }
  24569. }
  24570. };
  24571. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  24572. var properties = propertyPath.split(".");
  24573. for (var index = 0; index < properties.length - 1; index++) {
  24574. target = target[properties[index]];
  24575. }
  24576. return target;
  24577. };
  24578. ActionManager.prototype._getProperty = function (propertyPath) {
  24579. var properties = propertyPath.split(".");
  24580. return properties[properties.length - 1];
  24581. };
  24582. // Statics
  24583. ActionManager._NothingTrigger = 0;
  24584. ActionManager._OnPickTrigger = 1;
  24585. ActionManager._OnLeftPickTrigger = 2;
  24586. ActionManager._OnRightPickTrigger = 3;
  24587. ActionManager._OnCenterPickTrigger = 4;
  24588. ActionManager._OnPointerOverTrigger = 5;
  24589. ActionManager._OnPointerOutTrigger = 6;
  24590. ActionManager._OnEveryFrameTrigger = 7;
  24591. ActionManager._OnIntersectionEnterTrigger = 8;
  24592. ActionManager._OnIntersectionExitTrigger = 9;
  24593. ActionManager._OnKeyDownTrigger = 10;
  24594. ActionManager._OnKeyUpTrigger = 11;
  24595. return ActionManager;
  24596. })();
  24597. BABYLON.ActionManager = ActionManager;
  24598. })(BABYLON || (BABYLON = {}));
  24599. //# sourceMappingURL=babylon.actionManager.js.map
  24600. var BABYLON;
  24601. (function (BABYLON) {
  24602. var InterpolateValueAction = (function (_super) {
  24603. __extends(InterpolateValueAction, _super);
  24604. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  24605. if (duration === void 0) { duration = 1000; }
  24606. _super.call(this, triggerOptions, condition);
  24607. this.propertyPath = propertyPath;
  24608. this.value = value;
  24609. this.duration = duration;
  24610. this.stopOtherAnimations = stopOtherAnimations;
  24611. this._target = target;
  24612. }
  24613. InterpolateValueAction.prototype._prepare = function () {
  24614. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24615. this._property = this._getProperty(this.propertyPath);
  24616. };
  24617. InterpolateValueAction.prototype.execute = function () {
  24618. var scene = this._actionManager.getScene();
  24619. var keys = [
  24620. {
  24621. frame: 0,
  24622. value: this._target[this._property]
  24623. },
  24624. {
  24625. frame: 100,
  24626. value: this.value
  24627. }
  24628. ];
  24629. var dataType;
  24630. if (typeof this.value === "number") {
  24631. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  24632. }
  24633. else if (this.value instanceof BABYLON.Color3) {
  24634. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  24635. }
  24636. else if (this.value instanceof BABYLON.Vector3) {
  24637. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  24638. }
  24639. else if (this.value instanceof BABYLON.Matrix) {
  24640. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  24641. }
  24642. else if (this.value instanceof BABYLON.Quaternion) {
  24643. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  24644. }
  24645. else {
  24646. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  24647. return;
  24648. }
  24649. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  24650. animation.setKeys(keys);
  24651. if (this.stopOtherAnimations) {
  24652. scene.stopAnimation(this._target);
  24653. }
  24654. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  24655. };
  24656. return InterpolateValueAction;
  24657. })(BABYLON.Action);
  24658. BABYLON.InterpolateValueAction = InterpolateValueAction;
  24659. })(BABYLON || (BABYLON = {}));
  24660. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  24661. var BABYLON;
  24662. (function (BABYLON) {
  24663. var SwitchBooleanAction = (function (_super) {
  24664. __extends(SwitchBooleanAction, _super);
  24665. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  24666. _super.call(this, triggerOptions, condition);
  24667. this.propertyPath = propertyPath;
  24668. this._target = target;
  24669. }
  24670. SwitchBooleanAction.prototype._prepare = function () {
  24671. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24672. this._property = this._getProperty(this.propertyPath);
  24673. };
  24674. SwitchBooleanAction.prototype.execute = function () {
  24675. this._target[this._property] = !this._target[this._property];
  24676. };
  24677. return SwitchBooleanAction;
  24678. })(BABYLON.Action);
  24679. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  24680. var SetStateAction = (function (_super) {
  24681. __extends(SetStateAction, _super);
  24682. function SetStateAction(triggerOptions, target, value, condition) {
  24683. _super.call(this, triggerOptions, condition);
  24684. this.value = value;
  24685. this._target = target;
  24686. }
  24687. SetStateAction.prototype.execute = function () {
  24688. this._target.state = this.value;
  24689. };
  24690. return SetStateAction;
  24691. })(BABYLON.Action);
  24692. BABYLON.SetStateAction = SetStateAction;
  24693. var SetValueAction = (function (_super) {
  24694. __extends(SetValueAction, _super);
  24695. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  24696. _super.call(this, triggerOptions, condition);
  24697. this.propertyPath = propertyPath;
  24698. this.value = value;
  24699. this._target = target;
  24700. }
  24701. SetValueAction.prototype._prepare = function () {
  24702. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24703. this._property = this._getProperty(this.propertyPath);
  24704. };
  24705. SetValueAction.prototype.execute = function () {
  24706. this._target[this._property] = this.value;
  24707. };
  24708. return SetValueAction;
  24709. })(BABYLON.Action);
  24710. BABYLON.SetValueAction = SetValueAction;
  24711. var IncrementValueAction = (function (_super) {
  24712. __extends(IncrementValueAction, _super);
  24713. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  24714. _super.call(this, triggerOptions, condition);
  24715. this.propertyPath = propertyPath;
  24716. this.value = value;
  24717. this._target = target;
  24718. }
  24719. IncrementValueAction.prototype._prepare = function () {
  24720. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24721. this._property = this._getProperty(this.propertyPath);
  24722. if (typeof this._target[this._property] !== "number") {
  24723. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  24724. }
  24725. };
  24726. IncrementValueAction.prototype.execute = function () {
  24727. this._target[this._property] += this.value;
  24728. };
  24729. return IncrementValueAction;
  24730. })(BABYLON.Action);
  24731. BABYLON.IncrementValueAction = IncrementValueAction;
  24732. var PlayAnimationAction = (function (_super) {
  24733. __extends(PlayAnimationAction, _super);
  24734. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  24735. _super.call(this, triggerOptions, condition);
  24736. this.from = from;
  24737. this.to = to;
  24738. this.loop = loop;
  24739. this._target = target;
  24740. }
  24741. PlayAnimationAction.prototype._prepare = function () {
  24742. };
  24743. PlayAnimationAction.prototype.execute = function () {
  24744. var scene = this._actionManager.getScene();
  24745. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  24746. };
  24747. return PlayAnimationAction;
  24748. })(BABYLON.Action);
  24749. BABYLON.PlayAnimationAction = PlayAnimationAction;
  24750. var StopAnimationAction = (function (_super) {
  24751. __extends(StopAnimationAction, _super);
  24752. function StopAnimationAction(triggerOptions, target, condition) {
  24753. _super.call(this, triggerOptions, condition);
  24754. this._target = target;
  24755. }
  24756. StopAnimationAction.prototype._prepare = function () {
  24757. };
  24758. StopAnimationAction.prototype.execute = function () {
  24759. var scene = this._actionManager.getScene();
  24760. scene.stopAnimation(this._target);
  24761. };
  24762. return StopAnimationAction;
  24763. })(BABYLON.Action);
  24764. BABYLON.StopAnimationAction = StopAnimationAction;
  24765. var DoNothingAction = (function (_super) {
  24766. __extends(DoNothingAction, _super);
  24767. function DoNothingAction(triggerOptions, condition) {
  24768. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  24769. _super.call(this, triggerOptions, condition);
  24770. }
  24771. DoNothingAction.prototype.execute = function () {
  24772. };
  24773. return DoNothingAction;
  24774. })(BABYLON.Action);
  24775. BABYLON.DoNothingAction = DoNothingAction;
  24776. var CombineAction = (function (_super) {
  24777. __extends(CombineAction, _super);
  24778. function CombineAction(triggerOptions, children, condition) {
  24779. _super.call(this, triggerOptions, condition);
  24780. this.children = children;
  24781. }
  24782. CombineAction.prototype._prepare = function () {
  24783. for (var index = 0; index < this.children.length; index++) {
  24784. this.children[index]._actionManager = this._actionManager;
  24785. this.children[index]._prepare();
  24786. }
  24787. };
  24788. CombineAction.prototype.execute = function (evt) {
  24789. for (var index = 0; index < this.children.length; index++) {
  24790. this.children[index].execute(evt);
  24791. }
  24792. };
  24793. return CombineAction;
  24794. })(BABYLON.Action);
  24795. BABYLON.CombineAction = CombineAction;
  24796. var ExecuteCodeAction = (function (_super) {
  24797. __extends(ExecuteCodeAction, _super);
  24798. function ExecuteCodeAction(triggerOptions, func, condition) {
  24799. _super.call(this, triggerOptions, condition);
  24800. this.func = func;
  24801. }
  24802. ExecuteCodeAction.prototype.execute = function (evt) {
  24803. this.func(evt);
  24804. };
  24805. return ExecuteCodeAction;
  24806. })(BABYLON.Action);
  24807. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  24808. var SetParentAction = (function (_super) {
  24809. __extends(SetParentAction, _super);
  24810. function SetParentAction(triggerOptions, target, parent, condition) {
  24811. _super.call(this, triggerOptions, condition);
  24812. this._target = target;
  24813. this._parent = parent;
  24814. }
  24815. SetParentAction.prototype._prepare = function () {
  24816. };
  24817. SetParentAction.prototype.execute = function () {
  24818. if (this._target.parent === this._parent) {
  24819. return;
  24820. }
  24821. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  24822. invertParentWorldMatrix.invert();
  24823. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  24824. this._target.parent = this._parent;
  24825. };
  24826. return SetParentAction;
  24827. })(BABYLON.Action);
  24828. BABYLON.SetParentAction = SetParentAction;
  24829. var PlaySoundAction = (function (_super) {
  24830. __extends(PlaySoundAction, _super);
  24831. function PlaySoundAction(triggerOptions, sound, condition) {
  24832. _super.call(this, triggerOptions, condition);
  24833. this._sound = sound;
  24834. }
  24835. PlaySoundAction.prototype._prepare = function () {
  24836. };
  24837. PlaySoundAction.prototype.execute = function () {
  24838. if (this._sound !== undefined)
  24839. this._sound.play();
  24840. };
  24841. return PlaySoundAction;
  24842. })(BABYLON.Action);
  24843. BABYLON.PlaySoundAction = PlaySoundAction;
  24844. var StopSoundAction = (function (_super) {
  24845. __extends(StopSoundAction, _super);
  24846. function StopSoundAction(triggerOptions, sound, condition) {
  24847. _super.call(this, triggerOptions, condition);
  24848. this._sound = sound;
  24849. }
  24850. StopSoundAction.prototype._prepare = function () {
  24851. };
  24852. StopSoundAction.prototype.execute = function () {
  24853. if (this._sound !== undefined)
  24854. this._sound.stop();
  24855. };
  24856. return StopSoundAction;
  24857. })(BABYLON.Action);
  24858. BABYLON.StopSoundAction = StopSoundAction;
  24859. })(BABYLON || (BABYLON = {}));
  24860. //# sourceMappingURL=babylon.directActions.js.map
  24861. var BABYLON;
  24862. (function (BABYLON) {
  24863. var Geometry = (function () {
  24864. function Geometry(id, scene, vertexData, updatable, mesh) {
  24865. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24866. this._totalVertices = 0;
  24867. this._indices = [];
  24868. this._isDisposed = false;
  24869. this.id = id;
  24870. this._engine = scene.getEngine();
  24871. this._meshes = [];
  24872. this._scene = scene;
  24873. // vertexData
  24874. if (vertexData) {
  24875. this.setAllVerticesData(vertexData, updatable);
  24876. }
  24877. else {
  24878. this._totalVertices = 0;
  24879. this._indices = [];
  24880. }
  24881. // applyToMesh
  24882. if (mesh) {
  24883. this.applyToMesh(mesh);
  24884. mesh.computeWorldMatrix(true);
  24885. }
  24886. }
  24887. Geometry.prototype.getScene = function () {
  24888. return this._scene;
  24889. };
  24890. Geometry.prototype.getEngine = function () {
  24891. return this._engine;
  24892. };
  24893. Geometry.prototype.isReady = function () {
  24894. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  24895. };
  24896. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  24897. vertexData.applyToGeometry(this, updatable);
  24898. };
  24899. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  24900. this._vertexBuffers = this._vertexBuffers || {};
  24901. if (this._vertexBuffers[kind]) {
  24902. this._vertexBuffers[kind].dispose();
  24903. }
  24904. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  24905. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24906. stride = this._vertexBuffers[kind].getStrideSize();
  24907. this._totalVertices = data.length / stride;
  24908. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24909. var meshes = this._meshes;
  24910. var numOfMeshes = meshes.length;
  24911. for (var index = 0; index < numOfMeshes; index++) {
  24912. var mesh = meshes[index];
  24913. mesh._resetPointsArrayCache();
  24914. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24915. mesh._createGlobalSubMesh();
  24916. mesh.computeWorldMatrix(true);
  24917. }
  24918. }
  24919. };
  24920. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  24921. var vertexBuffer = this.getVertexBuffer(kind);
  24922. if (!vertexBuffer) {
  24923. return;
  24924. }
  24925. vertexBuffer.updateDirectly(data, offset);
  24926. };
  24927. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  24928. var vertexBuffer = this.getVertexBuffer(kind);
  24929. if (!vertexBuffer) {
  24930. return;
  24931. }
  24932. vertexBuffer.update(data);
  24933. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24934. var extend;
  24935. var stride = vertexBuffer.getStrideSize();
  24936. this._totalVertices = data.length / stride;
  24937. if (updateExtends) {
  24938. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24939. }
  24940. var meshes = this._meshes;
  24941. var numOfMeshes = meshes.length;
  24942. for (var index = 0; index < numOfMeshes; index++) {
  24943. var mesh = meshes[index];
  24944. mesh._resetPointsArrayCache();
  24945. if (updateExtends) {
  24946. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24947. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24948. var subMesh = mesh.subMeshes[subIndex];
  24949. subMesh.refreshBoundingInfo();
  24950. }
  24951. }
  24952. }
  24953. }
  24954. };
  24955. Geometry.prototype.getTotalVertices = function () {
  24956. if (!this.isReady()) {
  24957. return 0;
  24958. }
  24959. return this._totalVertices;
  24960. };
  24961. Geometry.prototype.getVerticesData = function (kind) {
  24962. var vertexBuffer = this.getVertexBuffer(kind);
  24963. if (!vertexBuffer) {
  24964. return null;
  24965. }
  24966. return vertexBuffer.getData();
  24967. };
  24968. Geometry.prototype.getVertexBuffer = function (kind) {
  24969. if (!this.isReady()) {
  24970. return null;
  24971. }
  24972. return this._vertexBuffers[kind];
  24973. };
  24974. Geometry.prototype.getVertexBuffers = function () {
  24975. if (!this.isReady()) {
  24976. return null;
  24977. }
  24978. return this._vertexBuffers;
  24979. };
  24980. Geometry.prototype.isVerticesDataPresent = function (kind) {
  24981. if (!this._vertexBuffers) {
  24982. if (this._delayInfo) {
  24983. return this._delayInfo.indexOf(kind) !== -1;
  24984. }
  24985. return false;
  24986. }
  24987. return this._vertexBuffers[kind] !== undefined;
  24988. };
  24989. Geometry.prototype.getVerticesDataKinds = function () {
  24990. var result = [];
  24991. if (!this._vertexBuffers && this._delayInfo) {
  24992. for (var kind in this._delayInfo) {
  24993. result.push(kind);
  24994. }
  24995. }
  24996. else {
  24997. for (kind in this._vertexBuffers) {
  24998. result.push(kind);
  24999. }
  25000. }
  25001. return result;
  25002. };
  25003. Geometry.prototype.setIndices = function (indices, totalVertices) {
  25004. if (this._indexBuffer) {
  25005. this._engine._releaseBuffer(this._indexBuffer);
  25006. }
  25007. this._indices = indices;
  25008. if (this._meshes.length !== 0 && this._indices) {
  25009. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25010. }
  25011. if (totalVertices !== undefined) {
  25012. this._totalVertices = totalVertices;
  25013. }
  25014. var meshes = this._meshes;
  25015. var numOfMeshes = meshes.length;
  25016. for (var index = 0; index < numOfMeshes; index++) {
  25017. meshes[index]._createGlobalSubMesh();
  25018. }
  25019. };
  25020. Geometry.prototype.getTotalIndices = function () {
  25021. if (!this.isReady()) {
  25022. return 0;
  25023. }
  25024. return this._indices.length;
  25025. };
  25026. Geometry.prototype.getIndices = function () {
  25027. if (!this.isReady()) {
  25028. return null;
  25029. }
  25030. return this._indices;
  25031. };
  25032. Geometry.prototype.getIndexBuffer = function () {
  25033. if (!this.isReady()) {
  25034. return null;
  25035. }
  25036. return this._indexBuffer;
  25037. };
  25038. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  25039. var meshes = this._meshes;
  25040. var index = meshes.indexOf(mesh);
  25041. if (index === -1) {
  25042. return;
  25043. }
  25044. for (var kind in this._vertexBuffers) {
  25045. this._vertexBuffers[kind].dispose();
  25046. }
  25047. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  25048. this._indexBuffer = null;
  25049. }
  25050. meshes.splice(index, 1);
  25051. mesh._geometry = null;
  25052. if (meshes.length === 0 && shouldDispose) {
  25053. this.dispose();
  25054. }
  25055. };
  25056. Geometry.prototype.applyToMesh = function (mesh) {
  25057. if (mesh._geometry === this) {
  25058. return;
  25059. }
  25060. var previousGeometry = mesh._geometry;
  25061. if (previousGeometry) {
  25062. previousGeometry.releaseForMesh(mesh);
  25063. }
  25064. var meshes = this._meshes;
  25065. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  25066. mesh._geometry = this;
  25067. this._scene.pushGeometry(this);
  25068. meshes.push(mesh);
  25069. if (this.isReady()) {
  25070. this._applyToMesh(mesh);
  25071. }
  25072. else {
  25073. mesh._boundingInfo = this._boundingInfo;
  25074. }
  25075. };
  25076. Geometry.prototype._applyToMesh = function (mesh) {
  25077. var numOfMeshes = this._meshes.length;
  25078. for (var kind in this._vertexBuffers) {
  25079. if (numOfMeshes === 1) {
  25080. this._vertexBuffers[kind].create();
  25081. }
  25082. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  25083. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25084. mesh._resetPointsArrayCache();
  25085. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  25086. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25087. mesh._createGlobalSubMesh();
  25088. //bounding info was just created again, world matrix should be applied again.
  25089. mesh._updateBoundingInfo();
  25090. }
  25091. }
  25092. // indexBuffer
  25093. if (numOfMeshes === 1 && this._indices) {
  25094. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25095. }
  25096. if (this._indexBuffer) {
  25097. this._indexBuffer.references = numOfMeshes;
  25098. }
  25099. };
  25100. Geometry.prototype.load = function (scene, onLoaded) {
  25101. var _this = this;
  25102. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25103. return;
  25104. }
  25105. if (this.isReady()) {
  25106. if (onLoaded) {
  25107. onLoaded();
  25108. }
  25109. return;
  25110. }
  25111. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25112. scene._addPendingData(this);
  25113. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25114. _this._delayLoadingFunction(JSON.parse(data), _this);
  25115. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25116. _this._delayInfo = [];
  25117. scene._removePendingData(_this);
  25118. var meshes = _this._meshes;
  25119. var numOfMeshes = meshes.length;
  25120. for (var index = 0; index < numOfMeshes; index++) {
  25121. _this._applyToMesh(meshes[index]);
  25122. }
  25123. if (onLoaded) {
  25124. onLoaded();
  25125. }
  25126. }, function () {
  25127. }, scene.database);
  25128. };
  25129. Geometry.prototype.isDisposed = function () {
  25130. return this._isDisposed;
  25131. };
  25132. Geometry.prototype.dispose = function () {
  25133. var meshes = this._meshes;
  25134. var numOfMeshes = meshes.length;
  25135. var index;
  25136. for (index = 0; index < numOfMeshes; index++) {
  25137. this.releaseForMesh(meshes[index]);
  25138. }
  25139. this._meshes = [];
  25140. for (var kind in this._vertexBuffers) {
  25141. this._vertexBuffers[kind].dispose();
  25142. }
  25143. this._vertexBuffers = [];
  25144. this._totalVertices = 0;
  25145. if (this._indexBuffer) {
  25146. this._engine._releaseBuffer(this._indexBuffer);
  25147. }
  25148. this._indexBuffer = null;
  25149. this._indices = [];
  25150. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25151. this.delayLoadingFile = null;
  25152. this._delayLoadingFunction = null;
  25153. this._delayInfo = [];
  25154. this._boundingInfo = null; // todo: .dispose()
  25155. var geometries = this._scene.getGeometries();
  25156. index = geometries.indexOf(this);
  25157. if (index > -1) {
  25158. geometries.splice(index, 1);
  25159. }
  25160. this._isDisposed = true;
  25161. };
  25162. Geometry.prototype.copy = function (id) {
  25163. var vertexData = new BABYLON.VertexData();
  25164. vertexData.indices = [];
  25165. var indices = this.getIndices();
  25166. for (var index = 0; index < indices.length; index++) {
  25167. vertexData.indices.push(indices[index]);
  25168. }
  25169. var updatable = false;
  25170. var stopChecking = false;
  25171. for (var kind in this._vertexBuffers) {
  25172. // using slice() to make a copy of the array and not just reference it
  25173. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  25174. if (!stopChecking) {
  25175. updatable = this.getVertexBuffer(kind).isUpdatable();
  25176. stopChecking = !updatable;
  25177. }
  25178. }
  25179. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  25180. geometry.delayLoadState = this.delayLoadState;
  25181. geometry.delayLoadingFile = this.delayLoadingFile;
  25182. geometry._delayLoadingFunction = this._delayLoadingFunction;
  25183. for (kind in this._delayInfo) {
  25184. geometry._delayInfo = geometry._delayInfo || [];
  25185. geometry._delayInfo.push(kind);
  25186. }
  25187. // Bounding info
  25188. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  25189. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25190. return geometry;
  25191. };
  25192. // Statics
  25193. Geometry.ExtractFromMesh = function (mesh, id) {
  25194. var geometry = mesh._geometry;
  25195. if (!geometry) {
  25196. return null;
  25197. }
  25198. return geometry.copy(id);
  25199. };
  25200. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  25201. // be aware Math.random() could cause collisions
  25202. Geometry.RandomId = function () {
  25203. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  25204. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  25205. return v.toString(16);
  25206. });
  25207. };
  25208. return Geometry;
  25209. })();
  25210. BABYLON.Geometry = Geometry;
  25211. /////// Primitives //////////////////////////////////////////////
  25212. var Geometry;
  25213. (function (Geometry) {
  25214. var Primitives;
  25215. (function (Primitives) {
  25216. /// Abstract class
  25217. var _Primitive = (function (_super) {
  25218. __extends(_Primitive, _super);
  25219. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  25220. this._beingRegenerated = true;
  25221. this._canBeRegenerated = canBeRegenerated;
  25222. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  25223. this._beingRegenerated = false;
  25224. }
  25225. _Primitive.prototype.canBeRegenerated = function () {
  25226. return this._canBeRegenerated;
  25227. };
  25228. _Primitive.prototype.regenerate = function () {
  25229. if (!this._canBeRegenerated) {
  25230. return;
  25231. }
  25232. this._beingRegenerated = true;
  25233. this.setAllVerticesData(this._regenerateVertexData(), false);
  25234. this._beingRegenerated = false;
  25235. };
  25236. _Primitive.prototype.asNewGeometry = function (id) {
  25237. return _super.prototype.copy.call(this, id);
  25238. };
  25239. // overrides
  25240. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  25241. if (!this._beingRegenerated) {
  25242. return;
  25243. }
  25244. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  25245. };
  25246. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  25247. if (!this._beingRegenerated) {
  25248. return;
  25249. }
  25250. _super.prototype.setVerticesData.call(this, kind, data, false);
  25251. };
  25252. // to override
  25253. // protected
  25254. _Primitive.prototype._regenerateVertexData = function () {
  25255. throw new Error("Abstract method");
  25256. };
  25257. _Primitive.prototype.copy = function (id) {
  25258. throw new Error("Must be overriden in sub-classes.");
  25259. };
  25260. return _Primitive;
  25261. })(Geometry);
  25262. Primitives._Primitive = _Primitive;
  25263. var Ribbon = (function (_super) {
  25264. __extends(Ribbon, _super);
  25265. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  25266. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25267. this.pathArray = pathArray;
  25268. this.closeArray = closeArray;
  25269. this.closePath = closePath;
  25270. this.offset = offset;
  25271. this.side = side;
  25272. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25273. }
  25274. Ribbon.prototype._regenerateVertexData = function () {
  25275. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  25276. };
  25277. Ribbon.prototype.copy = function (id) {
  25278. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  25279. };
  25280. return Ribbon;
  25281. })(_Primitive);
  25282. Primitives.Ribbon = Ribbon;
  25283. var Box = (function (_super) {
  25284. __extends(Box, _super);
  25285. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  25286. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25287. this.size = size;
  25288. this.side = side;
  25289. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25290. }
  25291. Box.prototype._regenerateVertexData = function () {
  25292. return BABYLON.VertexData.CreateBox(this.size, this.side);
  25293. };
  25294. Box.prototype.copy = function (id) {
  25295. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25296. };
  25297. return Box;
  25298. })(_Primitive);
  25299. Primitives.Box = Box;
  25300. var Sphere = (function (_super) {
  25301. __extends(Sphere, _super);
  25302. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  25303. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25304. this.segments = segments;
  25305. this.diameter = diameter;
  25306. this.side = side;
  25307. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25308. }
  25309. Sphere.prototype._regenerateVertexData = function () {
  25310. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  25311. };
  25312. Sphere.prototype.copy = function (id) {
  25313. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  25314. };
  25315. return Sphere;
  25316. })(_Primitive);
  25317. Primitives.Sphere = Sphere;
  25318. var Cylinder = (function (_super) {
  25319. __extends(Cylinder, _super);
  25320. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  25321. if (subdivisions === void 0) { subdivisions = 1; }
  25322. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25323. this.height = height;
  25324. this.diameterTop = diameterTop;
  25325. this.diameterBottom = diameterBottom;
  25326. this.tessellation = tessellation;
  25327. this.subdivisions = subdivisions;
  25328. this.side = side;
  25329. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25330. }
  25331. Cylinder.prototype._regenerateVertexData = function () {
  25332. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  25333. };
  25334. Cylinder.prototype.copy = function (id) {
  25335. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  25336. };
  25337. return Cylinder;
  25338. })(_Primitive);
  25339. Primitives.Cylinder = Cylinder;
  25340. var Torus = (function (_super) {
  25341. __extends(Torus, _super);
  25342. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  25343. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25344. this.diameter = diameter;
  25345. this.thickness = thickness;
  25346. this.tessellation = tessellation;
  25347. this.side = side;
  25348. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25349. }
  25350. Torus.prototype._regenerateVertexData = function () {
  25351. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  25352. };
  25353. Torus.prototype.copy = function (id) {
  25354. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  25355. };
  25356. return Torus;
  25357. })(_Primitive);
  25358. Primitives.Torus = Torus;
  25359. var Ground = (function (_super) {
  25360. __extends(Ground, _super);
  25361. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  25362. this.width = width;
  25363. this.height = height;
  25364. this.subdivisions = subdivisions;
  25365. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25366. }
  25367. Ground.prototype._regenerateVertexData = function () {
  25368. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  25369. };
  25370. Ground.prototype.copy = function (id) {
  25371. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  25372. };
  25373. return Ground;
  25374. })(_Primitive);
  25375. Primitives.Ground = Ground;
  25376. var TiledGround = (function (_super) {
  25377. __extends(TiledGround, _super);
  25378. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  25379. this.xmin = xmin;
  25380. this.zmin = zmin;
  25381. this.xmax = xmax;
  25382. this.zmax = zmax;
  25383. this.subdivisions = subdivisions;
  25384. this.precision = precision;
  25385. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25386. }
  25387. TiledGround.prototype._regenerateVertexData = function () {
  25388. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  25389. };
  25390. TiledGround.prototype.copy = function (id) {
  25391. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  25392. };
  25393. return TiledGround;
  25394. })(_Primitive);
  25395. Primitives.TiledGround = TiledGround;
  25396. var Plane = (function (_super) {
  25397. __extends(Plane, _super);
  25398. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  25399. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25400. this.size = size;
  25401. this.side = side;
  25402. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25403. }
  25404. Plane.prototype._regenerateVertexData = function () {
  25405. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  25406. };
  25407. Plane.prototype.copy = function (id) {
  25408. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25409. };
  25410. return Plane;
  25411. })(_Primitive);
  25412. Primitives.Plane = Plane;
  25413. var TorusKnot = (function (_super) {
  25414. __extends(TorusKnot, _super);
  25415. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  25416. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25417. this.radius = radius;
  25418. this.tube = tube;
  25419. this.radialSegments = radialSegments;
  25420. this.tubularSegments = tubularSegments;
  25421. this.p = p;
  25422. this.q = q;
  25423. this.side = side;
  25424. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25425. }
  25426. TorusKnot.prototype._regenerateVertexData = function () {
  25427. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  25428. };
  25429. TorusKnot.prototype.copy = function (id) {
  25430. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  25431. };
  25432. return TorusKnot;
  25433. })(_Primitive);
  25434. Primitives.TorusKnot = TorusKnot;
  25435. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  25436. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  25437. })(BABYLON || (BABYLON = {}));
  25438. //# sourceMappingURL=babylon.geometry.js.map
  25439. var BABYLON;
  25440. (function (BABYLON) {
  25441. var Gamepads = (function () {
  25442. function Gamepads(ongamedpadconnected) {
  25443. var _this = this;
  25444. this.babylonGamepads = [];
  25445. this.oneGamepadConnected = false;
  25446. this.isMonitoring = false;
  25447. this.gamepadEventSupported = 'GamepadEvent' in window;
  25448. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  25449. 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=";
  25450. this._callbackGamepadConnected = ongamedpadconnected;
  25451. if (this.gamepadSupportAvailable) {
  25452. // Checking if the gamepad connected event is supported (like in Firefox)
  25453. if (this.gamepadEventSupported) {
  25454. window.addEventListener('gamepadconnected', function (evt) {
  25455. _this._onGamepadConnected(evt);
  25456. }, false);
  25457. window.addEventListener('gamepaddisconnected', function (evt) {
  25458. _this._onGamepadDisconnected(evt);
  25459. }, false);
  25460. }
  25461. else {
  25462. this._startMonitoringGamepads();
  25463. }
  25464. if (!this.oneGamepadConnected) {
  25465. this._insertGamepadDOMInstructions();
  25466. }
  25467. }
  25468. else {
  25469. this._insertGamepadDOMNotSupported();
  25470. }
  25471. }
  25472. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  25473. Gamepads.gamepadDOMInfo = document.createElement("div");
  25474. var buttonAImage = document.createElement("img");
  25475. buttonAImage.src = this.buttonADataURL;
  25476. var spanMessage = document.createElement("span");
  25477. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  25478. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  25479. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25480. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25481. Gamepads.gamepadDOMInfo.style.width = "100%";
  25482. Gamepads.gamepadDOMInfo.style.height = "48px";
  25483. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25484. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25485. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25486. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25487. buttonAImage.style.position = "relative";
  25488. buttonAImage.style.bottom = "8px";
  25489. spanMessage.style.position = "relative";
  25490. spanMessage.style.fontSize = "32px";
  25491. spanMessage.style.bottom = "32px";
  25492. spanMessage.style.color = "green";
  25493. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25494. };
  25495. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  25496. Gamepads.gamepadDOMInfo = document.createElement("div");
  25497. var spanMessage = document.createElement("span");
  25498. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  25499. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25500. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25501. Gamepads.gamepadDOMInfo.style.width = "100%";
  25502. Gamepads.gamepadDOMInfo.style.height = "40px";
  25503. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25504. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25505. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25506. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25507. spanMessage.style.position = "relative";
  25508. spanMessage.style.fontSize = "32px";
  25509. spanMessage.style.color = "red";
  25510. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25511. };
  25512. Gamepads.prototype.dispose = function () {
  25513. if (Gamepads.gamepadDOMInfo) {
  25514. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25515. }
  25516. };
  25517. Gamepads.prototype._onGamepadConnected = function (evt) {
  25518. var newGamepad = this._addNewGamepad(evt.gamepad);
  25519. if (this._callbackGamepadConnected)
  25520. this._callbackGamepadConnected(newGamepad);
  25521. this._startMonitoringGamepads();
  25522. };
  25523. Gamepads.prototype._addNewGamepad = function (gamepad) {
  25524. if (!this.oneGamepadConnected) {
  25525. this.oneGamepadConnected = true;
  25526. if (Gamepads.gamepadDOMInfo) {
  25527. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25528. Gamepads.gamepadDOMInfo = null;
  25529. }
  25530. }
  25531. var newGamepad;
  25532. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  25533. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  25534. }
  25535. else {
  25536. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  25537. }
  25538. this.babylonGamepads.push(newGamepad);
  25539. return newGamepad;
  25540. };
  25541. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  25542. for (var i in this.babylonGamepads) {
  25543. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  25544. this.babylonGamepads.splice(i, 1);
  25545. break;
  25546. }
  25547. }
  25548. // If no gamepads are left, stop the polling loop.
  25549. if (this.babylonGamepads.length == 0) {
  25550. this._stopMonitoringGamepads();
  25551. }
  25552. };
  25553. Gamepads.prototype._startMonitoringGamepads = function () {
  25554. if (!this.isMonitoring) {
  25555. this.isMonitoring = true;
  25556. this._checkGamepadsStatus();
  25557. }
  25558. };
  25559. Gamepads.prototype._stopMonitoringGamepads = function () {
  25560. this.isMonitoring = false;
  25561. };
  25562. Gamepads.prototype._checkGamepadsStatus = function () {
  25563. var _this = this;
  25564. // updating gamepad objects
  25565. this._updateGamepadObjects();
  25566. for (var i in this.babylonGamepads) {
  25567. this.babylonGamepads[i].update();
  25568. }
  25569. if (this.isMonitoring) {
  25570. if (window.requestAnimationFrame) {
  25571. window.requestAnimationFrame(function () {
  25572. _this._checkGamepadsStatus();
  25573. });
  25574. }
  25575. else if (window.mozRequestAnimationFrame) {
  25576. window.mozRequestAnimationFrame(function () {
  25577. _this._checkGamepadsStatus();
  25578. });
  25579. }
  25580. else if (window.webkitRequestAnimationFrame) {
  25581. window.webkitRequestAnimationFrame(function () {
  25582. _this._checkGamepadsStatus();
  25583. });
  25584. }
  25585. }
  25586. };
  25587. // This function is called only on Chrome, which does not yet support
  25588. // connection/disconnection events, but requires you to monitor
  25589. // an array for changes.
  25590. Gamepads.prototype._updateGamepadObjects = function () {
  25591. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  25592. for (var i = 0; i < gamepads.length; i++) {
  25593. if (gamepads[i]) {
  25594. if (!(gamepads[i].index in this.babylonGamepads)) {
  25595. var newGamepad = this._addNewGamepad(gamepads[i]);
  25596. if (this._callbackGamepadConnected) {
  25597. this._callbackGamepadConnected(newGamepad);
  25598. }
  25599. }
  25600. else {
  25601. this.babylonGamepads[i].browserGamepad = gamepads[i];
  25602. }
  25603. }
  25604. }
  25605. };
  25606. return Gamepads;
  25607. })();
  25608. BABYLON.Gamepads = Gamepads;
  25609. var StickValues = (function () {
  25610. function StickValues(x, y) {
  25611. this.x = x;
  25612. this.y = y;
  25613. }
  25614. return StickValues;
  25615. })();
  25616. BABYLON.StickValues = StickValues;
  25617. var Gamepad = (function () {
  25618. function Gamepad(id, index, browserGamepad) {
  25619. this.id = id;
  25620. this.index = index;
  25621. this.browserGamepad = browserGamepad;
  25622. if (this.browserGamepad.axes.length >= 2) {
  25623. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25624. }
  25625. if (this.browserGamepad.axes.length >= 4) {
  25626. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25627. }
  25628. }
  25629. Gamepad.prototype.onleftstickchanged = function (callback) {
  25630. this._onleftstickchanged = callback;
  25631. };
  25632. Gamepad.prototype.onrightstickchanged = function (callback) {
  25633. this._onrightstickchanged = callback;
  25634. };
  25635. Object.defineProperty(Gamepad.prototype, "leftStick", {
  25636. get: function () {
  25637. return this._leftStick;
  25638. },
  25639. set: function (newValues) {
  25640. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  25641. this._onleftstickchanged(newValues);
  25642. }
  25643. this._leftStick = newValues;
  25644. },
  25645. enumerable: true,
  25646. configurable: true
  25647. });
  25648. Object.defineProperty(Gamepad.prototype, "rightStick", {
  25649. get: function () {
  25650. return this._rightStick;
  25651. },
  25652. set: function (newValues) {
  25653. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  25654. this._onrightstickchanged(newValues);
  25655. }
  25656. this._rightStick = newValues;
  25657. },
  25658. enumerable: true,
  25659. configurable: true
  25660. });
  25661. Gamepad.prototype.update = function () {
  25662. if (this._leftStick) {
  25663. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25664. }
  25665. if (this._rightStick) {
  25666. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25667. }
  25668. };
  25669. return Gamepad;
  25670. })();
  25671. BABYLON.Gamepad = Gamepad;
  25672. var GenericPad = (function (_super) {
  25673. __extends(GenericPad, _super);
  25674. function GenericPad(id, index, gamepad) {
  25675. _super.call(this, id, index, gamepad);
  25676. this.id = id;
  25677. this.index = index;
  25678. this.gamepad = gamepad;
  25679. this._buttons = new Array(gamepad.buttons.length);
  25680. }
  25681. GenericPad.prototype.onbuttondown = function (callback) {
  25682. this._onbuttondown = callback;
  25683. };
  25684. GenericPad.prototype.onbuttonup = function (callback) {
  25685. this._onbuttonup = callback;
  25686. };
  25687. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  25688. if (newValue !== currentValue) {
  25689. if (this._onbuttondown && newValue === 1) {
  25690. this._onbuttondown(buttonIndex);
  25691. }
  25692. if (this._onbuttonup && newValue === 0) {
  25693. this._onbuttonup(buttonIndex);
  25694. }
  25695. }
  25696. return newValue;
  25697. };
  25698. GenericPad.prototype.update = function () {
  25699. _super.prototype.update.call(this);
  25700. for (var index = 0; index < this._buttons.length; index++) {
  25701. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  25702. }
  25703. };
  25704. return GenericPad;
  25705. })(Gamepad);
  25706. BABYLON.GenericPad = GenericPad;
  25707. (function (Xbox360Button) {
  25708. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  25709. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  25710. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  25711. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  25712. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  25713. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  25714. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  25715. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  25716. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  25717. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  25718. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  25719. var Xbox360Button = BABYLON.Xbox360Button;
  25720. (function (Xbox360Dpad) {
  25721. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  25722. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  25723. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  25724. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  25725. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  25726. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  25727. var Xbox360Pad = (function (_super) {
  25728. __extends(Xbox360Pad, _super);
  25729. function Xbox360Pad() {
  25730. _super.apply(this, arguments);
  25731. this._leftTrigger = 0;
  25732. this._rightTrigger = 0;
  25733. this._buttonA = 0;
  25734. this._buttonB = 0;
  25735. this._buttonX = 0;
  25736. this._buttonY = 0;
  25737. this._buttonBack = 0;
  25738. this._buttonStart = 0;
  25739. this._buttonLB = 0;
  25740. this._buttonRB = 0;
  25741. this._buttonLeftStick = 0;
  25742. this._buttonRightStick = 0;
  25743. this._dPadUp = 0;
  25744. this._dPadDown = 0;
  25745. this._dPadLeft = 0;
  25746. this._dPadRight = 0;
  25747. }
  25748. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  25749. this._onlefttriggerchanged = callback;
  25750. };
  25751. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  25752. this._onrighttriggerchanged = callback;
  25753. };
  25754. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  25755. get: function () {
  25756. return this._leftTrigger;
  25757. },
  25758. set: function (newValue) {
  25759. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  25760. this._onlefttriggerchanged(newValue);
  25761. }
  25762. this._leftTrigger = newValue;
  25763. },
  25764. enumerable: true,
  25765. configurable: true
  25766. });
  25767. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  25768. get: function () {
  25769. return this._rightTrigger;
  25770. },
  25771. set: function (newValue) {
  25772. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  25773. this._onrighttriggerchanged(newValue);
  25774. }
  25775. this._rightTrigger = newValue;
  25776. },
  25777. enumerable: true,
  25778. configurable: true
  25779. });
  25780. Xbox360Pad.prototype.onbuttondown = function (callback) {
  25781. this._onbuttondown = callback;
  25782. };
  25783. Xbox360Pad.prototype.onbuttonup = function (callback) {
  25784. this._onbuttonup = callback;
  25785. };
  25786. Xbox360Pad.prototype.ondpaddown = function (callback) {
  25787. this._ondpaddown = callback;
  25788. };
  25789. Xbox360Pad.prototype.ondpadup = function (callback) {
  25790. this._ondpadup = callback;
  25791. };
  25792. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  25793. if (newValue !== currentValue) {
  25794. if (this._onbuttondown && newValue === 1) {
  25795. this._onbuttondown(buttonType);
  25796. }
  25797. if (this._onbuttonup && newValue === 0) {
  25798. this._onbuttonup(buttonType);
  25799. }
  25800. }
  25801. return newValue;
  25802. };
  25803. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  25804. if (newValue !== currentValue) {
  25805. if (this._ondpaddown && newValue === 1) {
  25806. this._ondpaddown(buttonType);
  25807. }
  25808. if (this._ondpadup && newValue === 0) {
  25809. this._ondpadup(buttonType);
  25810. }
  25811. }
  25812. return newValue;
  25813. };
  25814. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  25815. get: function () {
  25816. return this._buttonA;
  25817. },
  25818. set: function (value) {
  25819. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  25820. },
  25821. enumerable: true,
  25822. configurable: true
  25823. });
  25824. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  25825. get: function () {
  25826. return this._buttonB;
  25827. },
  25828. set: function (value) {
  25829. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  25830. },
  25831. enumerable: true,
  25832. configurable: true
  25833. });
  25834. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  25835. get: function () {
  25836. return this._buttonX;
  25837. },
  25838. set: function (value) {
  25839. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  25840. },
  25841. enumerable: true,
  25842. configurable: true
  25843. });
  25844. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  25845. get: function () {
  25846. return this._buttonY;
  25847. },
  25848. set: function (value) {
  25849. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  25850. },
  25851. enumerable: true,
  25852. configurable: true
  25853. });
  25854. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  25855. get: function () {
  25856. return this._buttonStart;
  25857. },
  25858. set: function (value) {
  25859. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  25860. },
  25861. enumerable: true,
  25862. configurable: true
  25863. });
  25864. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  25865. get: function () {
  25866. return this._buttonBack;
  25867. },
  25868. set: function (value) {
  25869. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  25870. },
  25871. enumerable: true,
  25872. configurable: true
  25873. });
  25874. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  25875. get: function () {
  25876. return this._buttonLB;
  25877. },
  25878. set: function (value) {
  25879. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  25880. },
  25881. enumerable: true,
  25882. configurable: true
  25883. });
  25884. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  25885. get: function () {
  25886. return this._buttonRB;
  25887. },
  25888. set: function (value) {
  25889. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  25890. },
  25891. enumerable: true,
  25892. configurable: true
  25893. });
  25894. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  25895. get: function () {
  25896. return this._buttonLeftStick;
  25897. },
  25898. set: function (value) {
  25899. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  25900. },
  25901. enumerable: true,
  25902. configurable: true
  25903. });
  25904. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  25905. get: function () {
  25906. return this._buttonRightStick;
  25907. },
  25908. set: function (value) {
  25909. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  25910. },
  25911. enumerable: true,
  25912. configurable: true
  25913. });
  25914. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  25915. get: function () {
  25916. return this._dPadUp;
  25917. },
  25918. set: function (value) {
  25919. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  25920. },
  25921. enumerable: true,
  25922. configurable: true
  25923. });
  25924. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  25925. get: function () {
  25926. return this._dPadDown;
  25927. },
  25928. set: function (value) {
  25929. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  25930. },
  25931. enumerable: true,
  25932. configurable: true
  25933. });
  25934. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  25935. get: function () {
  25936. return this._dPadLeft;
  25937. },
  25938. set: function (value) {
  25939. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  25940. },
  25941. enumerable: true,
  25942. configurable: true
  25943. });
  25944. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  25945. get: function () {
  25946. return this._dPadRight;
  25947. },
  25948. set: function (value) {
  25949. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  25950. },
  25951. enumerable: true,
  25952. configurable: true
  25953. });
  25954. Xbox360Pad.prototype.update = function () {
  25955. _super.prototype.update.call(this);
  25956. this.buttonA = this.browserGamepad.buttons[0].value;
  25957. this.buttonB = this.browserGamepad.buttons[1].value;
  25958. this.buttonX = this.browserGamepad.buttons[2].value;
  25959. this.buttonY = this.browserGamepad.buttons[3].value;
  25960. this.buttonLB = this.browserGamepad.buttons[4].value;
  25961. this.buttonRB = this.browserGamepad.buttons[5].value;
  25962. this.leftTrigger = this.browserGamepad.buttons[6].value;
  25963. this.rightTrigger = this.browserGamepad.buttons[7].value;
  25964. this.buttonBack = this.browserGamepad.buttons[8].value;
  25965. this.buttonStart = this.browserGamepad.buttons[9].value;
  25966. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  25967. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  25968. this.dPadUp = this.browserGamepad.buttons[12].value;
  25969. this.dPadDown = this.browserGamepad.buttons[13].value;
  25970. this.dPadLeft = this.browserGamepad.buttons[14].value;
  25971. this.dPadRight = this.browserGamepad.buttons[15].value;
  25972. };
  25973. return Xbox360Pad;
  25974. })(Gamepad);
  25975. BABYLON.Xbox360Pad = Xbox360Pad;
  25976. })(BABYLON || (BABYLON = {}));
  25977. //# sourceMappingURL=babylon.gamepads.js.map
  25978. var BABYLON;
  25979. (function (BABYLON) {
  25980. // We're mainly based on the logic defined into the FreeCamera code
  25981. var GamepadCamera = (function (_super) {
  25982. __extends(GamepadCamera, _super);
  25983. function GamepadCamera(name, position, scene) {
  25984. var _this = this;
  25985. _super.call(this, name, position, scene);
  25986. this.angularSensibility = 200;
  25987. this.moveSensibility = 75;
  25988. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  25989. _this._onNewGameConnected(gamepad);
  25990. });
  25991. }
  25992. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  25993. // Only the first gamepad can control the camera
  25994. if (gamepad.index === 0) {
  25995. this._gamepad = gamepad;
  25996. }
  25997. };
  25998. GamepadCamera.prototype._checkInputs = function () {
  25999. if (!this._gamepad) {
  26000. return;
  26001. }
  26002. var LSValues = this._gamepad.leftStick;
  26003. var normalizedLX = LSValues.x / this.moveSensibility;
  26004. var normalizedLY = LSValues.y / this.moveSensibility;
  26005. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  26006. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  26007. var RSValues = this._gamepad.rightStick;
  26008. var normalizedRX = RSValues.x / this.angularSensibility;
  26009. var normalizedRY = RSValues.y / this.angularSensibility;
  26010. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  26011. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  26012. ;
  26013. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  26014. var speed = this._computeLocalCameraSpeed() * 50.0;
  26015. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  26016. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  26017. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  26018. };
  26019. GamepadCamera.prototype.dispose = function () {
  26020. this._gamepads.dispose();
  26021. _super.prototype.dispose.call(this);
  26022. };
  26023. return GamepadCamera;
  26024. })(BABYLON.FreeCamera);
  26025. BABYLON.GamepadCamera = GamepadCamera;
  26026. })(BABYLON || (BABYLON = {}));
  26027. //# sourceMappingURL=babylon.gamepadCamera.js.map
  26028. var BABYLON;
  26029. (function (BABYLON) {
  26030. var LinesMesh = (function (_super) {
  26031. __extends(LinesMesh, _super);
  26032. function LinesMesh(name, scene, updatable) {
  26033. if (updatable === void 0) { updatable = false; }
  26034. _super.call(this, name, scene);
  26035. this.color = new BABYLON.Color3(1, 1, 1);
  26036. this.alpha = 1;
  26037. this._indices = new Array();
  26038. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26039. attributes: ["position"],
  26040. uniforms: ["worldViewProjection", "color"],
  26041. needAlphaBlending: true
  26042. });
  26043. }
  26044. Object.defineProperty(LinesMesh.prototype, "material", {
  26045. get: function () {
  26046. return this._colorShader;
  26047. },
  26048. enumerable: true,
  26049. configurable: true
  26050. });
  26051. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26052. get: function () {
  26053. return false;
  26054. },
  26055. enumerable: true,
  26056. configurable: true
  26057. });
  26058. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26059. get: function () {
  26060. return false;
  26061. },
  26062. enumerable: true,
  26063. configurable: true
  26064. });
  26065. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26066. var engine = this.getScene().getEngine();
  26067. var indexToBind = this._geometry.getIndexBuffer();
  26068. // VBOs
  26069. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26070. // Color
  26071. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26072. };
  26073. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26074. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26075. return;
  26076. }
  26077. var engine = this.getScene().getEngine();
  26078. // Draw order
  26079. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26080. };
  26081. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26082. return null;
  26083. };
  26084. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26085. this._colorShader.dispose();
  26086. _super.prototype.dispose.call(this, doNotRecurse);
  26087. };
  26088. return LinesMesh;
  26089. })(BABYLON.Mesh);
  26090. BABYLON.LinesMesh = LinesMesh;
  26091. })(BABYLON || (BABYLON = {}));
  26092. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  26093. (function (BABYLON) {
  26094. var OutlineRenderer = (function () {
  26095. function OutlineRenderer(scene) {
  26096. this._scene = scene;
  26097. }
  26098. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  26099. var _this = this;
  26100. if (useOverlay === void 0) { useOverlay = false; }
  26101. var scene = this._scene;
  26102. var engine = this._scene.getEngine();
  26103. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26104. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  26105. return;
  26106. }
  26107. var mesh = subMesh.getRenderingMesh();
  26108. var material = subMesh.getMaterial();
  26109. engine.enableEffect(this._effect);
  26110. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  26111. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  26112. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26113. // Bones
  26114. if (mesh.useBones) {
  26115. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  26116. }
  26117. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  26118. // Alpha test
  26119. if (material && material.needAlphaTesting()) {
  26120. var alphaTexture = material.getAlphaTestTexture();
  26121. this._effect.setTexture("diffuseSampler", alphaTexture);
  26122. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  26123. }
  26124. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  26125. _this._effect.setMatrix("world", world);
  26126. });
  26127. };
  26128. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  26129. var defines = [];
  26130. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  26131. var mesh = subMesh.getMesh();
  26132. var material = subMesh.getMaterial();
  26133. // Alpha test
  26134. if (material && material.needAlphaTesting()) {
  26135. defines.push("#define ALPHATEST");
  26136. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26137. attribs.push(BABYLON.VertexBuffer.UVKind);
  26138. defines.push("#define UV1");
  26139. }
  26140. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26141. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26142. defines.push("#define UV2");
  26143. }
  26144. }
  26145. // Bones
  26146. if (mesh.useBones) {
  26147. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26148. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26149. defines.push("#define BONES");
  26150. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  26151. }
  26152. // Instances
  26153. if (useInstances) {
  26154. defines.push("#define INSTANCES");
  26155. attribs.push("world0");
  26156. attribs.push("world1");
  26157. attribs.push("world2");
  26158. attribs.push("world3");
  26159. }
  26160. // Get correct effect
  26161. var join = defines.join("\n");
  26162. if (this._cachedDefines !== join) {
  26163. this._cachedDefines = join;
  26164. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  26165. }
  26166. return this._effect.isReady();
  26167. };
  26168. return OutlineRenderer;
  26169. })();
  26170. BABYLON.OutlineRenderer = OutlineRenderer;
  26171. })(BABYLON || (BABYLON = {}));
  26172. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  26173. (function (BABYLON) {
  26174. var MeshAssetTask = (function () {
  26175. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  26176. this.name = name;
  26177. this.meshesNames = meshesNames;
  26178. this.rootUrl = rootUrl;
  26179. this.sceneFilename = sceneFilename;
  26180. this.isCompleted = false;
  26181. }
  26182. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26183. var _this = this;
  26184. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  26185. _this.loadedMeshes = meshes;
  26186. _this.loadedParticleSystems = particleSystems;
  26187. _this.loadedSkeletons = skeletons;
  26188. _this.isCompleted = true;
  26189. if (_this.onSuccess) {
  26190. _this.onSuccess(_this);
  26191. }
  26192. onSuccess();
  26193. }, null, function () {
  26194. if (_this.onError) {
  26195. _this.onError(_this);
  26196. }
  26197. onError();
  26198. });
  26199. };
  26200. return MeshAssetTask;
  26201. })();
  26202. BABYLON.MeshAssetTask = MeshAssetTask;
  26203. var TextFileAssetTask = (function () {
  26204. function TextFileAssetTask(name, url) {
  26205. this.name = name;
  26206. this.url = url;
  26207. this.isCompleted = false;
  26208. }
  26209. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26210. var _this = this;
  26211. BABYLON.Tools.LoadFile(this.url, function (data) {
  26212. _this.text = data;
  26213. _this.isCompleted = true;
  26214. if (_this.onSuccess) {
  26215. _this.onSuccess(_this);
  26216. }
  26217. onSuccess();
  26218. }, null, scene.database, false, function () {
  26219. if (_this.onError) {
  26220. _this.onError(_this);
  26221. }
  26222. onError();
  26223. });
  26224. };
  26225. return TextFileAssetTask;
  26226. })();
  26227. BABYLON.TextFileAssetTask = TextFileAssetTask;
  26228. var BinaryFileAssetTask = (function () {
  26229. function BinaryFileAssetTask(name, url) {
  26230. this.name = name;
  26231. this.url = url;
  26232. this.isCompleted = false;
  26233. }
  26234. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26235. var _this = this;
  26236. BABYLON.Tools.LoadFile(this.url, function (data) {
  26237. _this.data = data;
  26238. _this.isCompleted = true;
  26239. if (_this.onSuccess) {
  26240. _this.onSuccess(_this);
  26241. }
  26242. onSuccess();
  26243. }, null, scene.database, true, function () {
  26244. if (_this.onError) {
  26245. _this.onError(_this);
  26246. }
  26247. onError();
  26248. });
  26249. };
  26250. return BinaryFileAssetTask;
  26251. })();
  26252. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  26253. var ImageAssetTask = (function () {
  26254. function ImageAssetTask(name, url) {
  26255. this.name = name;
  26256. this.url = url;
  26257. this.isCompleted = false;
  26258. }
  26259. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26260. var _this = this;
  26261. var img = new Image();
  26262. img.onload = function () {
  26263. _this.image = img;
  26264. _this.isCompleted = true;
  26265. if (_this.onSuccess) {
  26266. _this.onSuccess(_this);
  26267. }
  26268. onSuccess();
  26269. };
  26270. img.onerror = function () {
  26271. if (_this.onError) {
  26272. _this.onError(_this);
  26273. }
  26274. onError();
  26275. };
  26276. img.src = this.url;
  26277. };
  26278. return ImageAssetTask;
  26279. })();
  26280. BABYLON.ImageAssetTask = ImageAssetTask;
  26281. var TextureAssetTask = (function () {
  26282. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  26283. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26284. this.name = name;
  26285. this.url = url;
  26286. this.noMipmap = noMipmap;
  26287. this.invertY = invertY;
  26288. this.samplingMode = samplingMode;
  26289. this.isCompleted = false;
  26290. }
  26291. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26292. var _this = this;
  26293. var onload = function () {
  26294. _this.isCompleted = true;
  26295. if (_this.onSuccess) {
  26296. _this.onSuccess(_this);
  26297. }
  26298. onSuccess();
  26299. };
  26300. var onerror = function () {
  26301. if (_this.onError) {
  26302. _this.onError(_this);
  26303. }
  26304. onError();
  26305. };
  26306. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  26307. };
  26308. return TextureAssetTask;
  26309. })();
  26310. BABYLON.TextureAssetTask = TextureAssetTask;
  26311. var AssetsManager = (function () {
  26312. function AssetsManager(scene) {
  26313. this._tasks = new Array();
  26314. this._waitingTasksCount = 0;
  26315. this.useDefaultLoadingScreen = true;
  26316. this._scene = scene;
  26317. }
  26318. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  26319. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  26320. this._tasks.push(task);
  26321. return task;
  26322. };
  26323. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  26324. var task = new TextFileAssetTask(taskName, url);
  26325. this._tasks.push(task);
  26326. return task;
  26327. };
  26328. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  26329. var task = new BinaryFileAssetTask(taskName, url);
  26330. this._tasks.push(task);
  26331. return task;
  26332. };
  26333. AssetsManager.prototype.addImageTask = function (taskName, url) {
  26334. var task = new ImageAssetTask(taskName, url);
  26335. this._tasks.push(task);
  26336. return task;
  26337. };
  26338. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  26339. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26340. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  26341. this._tasks.push(task);
  26342. return task;
  26343. };
  26344. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  26345. this._waitingTasksCount--;
  26346. if (this._waitingTasksCount === 0) {
  26347. if (this.onFinish) {
  26348. this.onFinish(this._tasks);
  26349. }
  26350. this._scene.getEngine().hideLoadingUI();
  26351. }
  26352. };
  26353. AssetsManager.prototype._runTask = function (task) {
  26354. var _this = this;
  26355. task.run(this._scene, function () {
  26356. if (_this.onTaskSuccess) {
  26357. _this.onTaskSuccess(task);
  26358. }
  26359. _this._decreaseWaitingTasksCount();
  26360. }, function () {
  26361. if (_this.onTaskError) {
  26362. _this.onTaskError(task);
  26363. }
  26364. _this._decreaseWaitingTasksCount();
  26365. });
  26366. };
  26367. AssetsManager.prototype.reset = function () {
  26368. this._tasks = new Array();
  26369. return this;
  26370. };
  26371. AssetsManager.prototype.load = function () {
  26372. this._waitingTasksCount = this._tasks.length;
  26373. if (this._waitingTasksCount === 0) {
  26374. if (this.onFinish) {
  26375. this.onFinish(this._tasks);
  26376. }
  26377. return this;
  26378. }
  26379. if (this.useDefaultLoadingScreen) {
  26380. this._scene.getEngine().displayLoadingUI();
  26381. }
  26382. for (var index = 0; index < this._tasks.length; index++) {
  26383. var task = this._tasks[index];
  26384. this._runTask(task);
  26385. }
  26386. return this;
  26387. };
  26388. return AssetsManager;
  26389. })();
  26390. BABYLON.AssetsManager = AssetsManager;
  26391. })(BABYLON || (BABYLON = {}));
  26392. //# sourceMappingURL=babylon.assetsManager.js.map
  26393. var BABYLON;
  26394. (function (BABYLON) {
  26395. var VRDeviceOrientationCamera = (function (_super) {
  26396. __extends(VRDeviceOrientationCamera, _super);
  26397. function VRDeviceOrientationCamera(name, position, scene) {
  26398. _super.call(this, name, position, scene);
  26399. this._alpha = 0;
  26400. this._beta = 0;
  26401. this._gamma = 0;
  26402. }
  26403. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  26404. this._alpha = +evt.alpha | 0;
  26405. this._beta = +evt.beta | 0;
  26406. this._gamma = +evt.gamma | 0;
  26407. if (this._gamma < 0) {
  26408. this._gamma = 90 + this._gamma;
  26409. }
  26410. else {
  26411. // Incline it in the correct angle.
  26412. this._gamma = 270 - this._gamma;
  26413. }
  26414. this.rotation.x = this._gamma / 180.0 * Math.PI;
  26415. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  26416. this.rotation.z = this._beta / 180.0 * Math.PI;
  26417. };
  26418. return VRDeviceOrientationCamera;
  26419. })(BABYLON.OculusCamera);
  26420. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  26421. })(BABYLON || (BABYLON = {}));
  26422. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  26423. var BABYLON;
  26424. (function (BABYLON) {
  26425. var WebVRCamera = (function (_super) {
  26426. __extends(WebVRCamera, _super);
  26427. function WebVRCamera(name, position, scene) {
  26428. _super.call(this, name, position, scene);
  26429. this._hmdDevice = null;
  26430. this._sensorDevice = null;
  26431. this._cacheState = null;
  26432. this._cacheQuaternion = new BABYLON.Quaternion();
  26433. this._cacheRotation = BABYLON.Vector3.Zero();
  26434. this._vrEnabled = false;
  26435. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  26436. }
  26437. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  26438. var size = devices.length;
  26439. var i = 0;
  26440. // Reset devices.
  26441. this._sensorDevice = null;
  26442. this._hmdDevice = null;
  26443. while (i < size && this._hmdDevice === null) {
  26444. if (devices[i] instanceof HMDVRDevice) {
  26445. this._hmdDevice = devices[i];
  26446. }
  26447. i++;
  26448. }
  26449. i = 0;
  26450. while (i < size && this._sensorDevice === null) {
  26451. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  26452. this._sensorDevice = devices[i];
  26453. }
  26454. i++;
  26455. }
  26456. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  26457. };
  26458. WebVRCamera.prototype._update = function () {
  26459. if (this._vrEnabled) {
  26460. this._cacheState = this._sensorDevice.getState();
  26461. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  26462. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  26463. this.rotation.x = -this._cacheRotation.z;
  26464. this.rotation.y = -this._cacheRotation.y;
  26465. this.rotation.z = this._cacheRotation.x;
  26466. }
  26467. _super.prototype._update.call(this);
  26468. };
  26469. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  26470. _super.prototype.attachControl.call(this, element, noPreventDefault);
  26471. if (navigator.getVRDevices) {
  26472. navigator.getVRDevices().then(this._getWebVRDevices);
  26473. }
  26474. else if (navigator.mozGetVRDevices) {
  26475. navigator.mozGetVRDevices(this._getWebVRDevices);
  26476. }
  26477. };
  26478. WebVRCamera.prototype.detachControl = function (element) {
  26479. _super.prototype.detachControl.call(this, element);
  26480. this._vrEnabled = false;
  26481. };
  26482. return WebVRCamera;
  26483. })(BABYLON.OculusCamera);
  26484. BABYLON.WebVRCamera = WebVRCamera;
  26485. })(BABYLON || (BABYLON = {}));
  26486. //# sourceMappingURL=babylon.webVRCamera.js.map
  26487. var BABYLON;
  26488. (function (BABYLON) {
  26489. // Standard optimizations
  26490. var SceneOptimization = (function () {
  26491. function SceneOptimization(priority) {
  26492. if (priority === void 0) { priority = 0; }
  26493. this.priority = priority;
  26494. this.apply = function (scene) {
  26495. return true; // Return true if everything that can be done was applied
  26496. };
  26497. }
  26498. return SceneOptimization;
  26499. })();
  26500. BABYLON.SceneOptimization = SceneOptimization;
  26501. var TextureOptimization = (function (_super) {
  26502. __extends(TextureOptimization, _super);
  26503. function TextureOptimization(priority, maximumSize) {
  26504. var _this = this;
  26505. if (priority === void 0) { priority = 0; }
  26506. if (maximumSize === void 0) { maximumSize = 1024; }
  26507. _super.call(this, priority);
  26508. this.priority = priority;
  26509. this.maximumSize = maximumSize;
  26510. this.apply = function (scene) {
  26511. var allDone = true;
  26512. for (var index = 0; index < scene.textures.length; index++) {
  26513. var texture = scene.textures[index];
  26514. if (!texture.canRescale) {
  26515. continue;
  26516. }
  26517. var currentSize = texture.getSize();
  26518. var maxDimension = Math.max(currentSize.width, currentSize.height);
  26519. if (maxDimension > _this.maximumSize) {
  26520. texture.scale(0.5);
  26521. allDone = false;
  26522. }
  26523. }
  26524. return allDone;
  26525. };
  26526. }
  26527. return TextureOptimization;
  26528. })(SceneOptimization);
  26529. BABYLON.TextureOptimization = TextureOptimization;
  26530. var HardwareScalingOptimization = (function (_super) {
  26531. __extends(HardwareScalingOptimization, _super);
  26532. function HardwareScalingOptimization(priority, maximumScale) {
  26533. var _this = this;
  26534. if (priority === void 0) { priority = 0; }
  26535. if (maximumScale === void 0) { maximumScale = 2; }
  26536. _super.call(this, priority);
  26537. this.priority = priority;
  26538. this.maximumScale = maximumScale;
  26539. this._currentScale = 1;
  26540. this.apply = function (scene) {
  26541. _this._currentScale++;
  26542. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  26543. return _this._currentScale >= _this.maximumScale;
  26544. };
  26545. }
  26546. return HardwareScalingOptimization;
  26547. })(SceneOptimization);
  26548. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  26549. var ShadowsOptimization = (function (_super) {
  26550. __extends(ShadowsOptimization, _super);
  26551. function ShadowsOptimization() {
  26552. _super.apply(this, arguments);
  26553. this.apply = function (scene) {
  26554. scene.shadowsEnabled = false;
  26555. return true;
  26556. };
  26557. }
  26558. return ShadowsOptimization;
  26559. })(SceneOptimization);
  26560. BABYLON.ShadowsOptimization = ShadowsOptimization;
  26561. var PostProcessesOptimization = (function (_super) {
  26562. __extends(PostProcessesOptimization, _super);
  26563. function PostProcessesOptimization() {
  26564. _super.apply(this, arguments);
  26565. this.apply = function (scene) {
  26566. scene.postProcessesEnabled = false;
  26567. return true;
  26568. };
  26569. }
  26570. return PostProcessesOptimization;
  26571. })(SceneOptimization);
  26572. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  26573. var LensFlaresOptimization = (function (_super) {
  26574. __extends(LensFlaresOptimization, _super);
  26575. function LensFlaresOptimization() {
  26576. _super.apply(this, arguments);
  26577. this.apply = function (scene) {
  26578. scene.lensFlaresEnabled = false;
  26579. return true;
  26580. };
  26581. }
  26582. return LensFlaresOptimization;
  26583. })(SceneOptimization);
  26584. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  26585. var ParticlesOptimization = (function (_super) {
  26586. __extends(ParticlesOptimization, _super);
  26587. function ParticlesOptimization() {
  26588. _super.apply(this, arguments);
  26589. this.apply = function (scene) {
  26590. scene.particlesEnabled = false;
  26591. return true;
  26592. };
  26593. }
  26594. return ParticlesOptimization;
  26595. })(SceneOptimization);
  26596. BABYLON.ParticlesOptimization = ParticlesOptimization;
  26597. var RenderTargetsOptimization = (function (_super) {
  26598. __extends(RenderTargetsOptimization, _super);
  26599. function RenderTargetsOptimization() {
  26600. _super.apply(this, arguments);
  26601. this.apply = function (scene) {
  26602. scene.renderTargetsEnabled = false;
  26603. return true;
  26604. };
  26605. }
  26606. return RenderTargetsOptimization;
  26607. })(SceneOptimization);
  26608. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  26609. var MergeMeshesOptimization = (function (_super) {
  26610. __extends(MergeMeshesOptimization, _super);
  26611. function MergeMeshesOptimization() {
  26612. var _this = this;
  26613. _super.apply(this, arguments);
  26614. this._canBeMerged = function (abstractMesh) {
  26615. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  26616. return false;
  26617. }
  26618. var mesh = abstractMesh;
  26619. if (!mesh.isVisible || !mesh.isEnabled()) {
  26620. return false;
  26621. }
  26622. if (mesh.instances.length > 0) {
  26623. return false;
  26624. }
  26625. if (mesh.skeleton || mesh.hasLODLevels) {
  26626. return false;
  26627. }
  26628. return true;
  26629. };
  26630. this.apply = function (scene) {
  26631. var globalPool = scene.meshes.slice(0);
  26632. var globalLength = globalPool.length;
  26633. for (var index = 0; index < globalLength; index++) {
  26634. var currentPool = new Array();
  26635. var current = globalPool[index];
  26636. // Checks
  26637. if (!_this._canBeMerged(current)) {
  26638. continue;
  26639. }
  26640. currentPool.push(current);
  26641. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  26642. var otherMesh = globalPool[subIndex];
  26643. if (!_this._canBeMerged(otherMesh)) {
  26644. continue;
  26645. }
  26646. if (otherMesh.material !== current.material) {
  26647. continue;
  26648. }
  26649. if (otherMesh.checkCollisions !== current.checkCollisions) {
  26650. continue;
  26651. }
  26652. currentPool.push(otherMesh);
  26653. globalLength--;
  26654. globalPool.splice(subIndex, 1);
  26655. subIndex--;
  26656. }
  26657. if (currentPool.length < 2) {
  26658. continue;
  26659. }
  26660. // Merge meshes
  26661. BABYLON.Mesh.MergeMeshes(currentPool);
  26662. }
  26663. return true;
  26664. };
  26665. }
  26666. return MergeMeshesOptimization;
  26667. })(SceneOptimization);
  26668. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  26669. // Options
  26670. var SceneOptimizerOptions = (function () {
  26671. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  26672. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  26673. if (trackerDuration === void 0) { trackerDuration = 2000; }
  26674. this.targetFrameRate = targetFrameRate;
  26675. this.trackerDuration = trackerDuration;
  26676. this.optimizations = new Array();
  26677. }
  26678. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  26679. var result = new SceneOptimizerOptions(targetFrameRate);
  26680. var priority = 0;
  26681. result.optimizations.push(new MergeMeshesOptimization(priority));
  26682. result.optimizations.push(new ShadowsOptimization(priority));
  26683. result.optimizations.push(new LensFlaresOptimization(priority));
  26684. // Next priority
  26685. priority++;
  26686. result.optimizations.push(new PostProcessesOptimization(priority));
  26687. result.optimizations.push(new ParticlesOptimization(priority));
  26688. // Next priority
  26689. priority++;
  26690. result.optimizations.push(new TextureOptimization(priority, 1024));
  26691. return result;
  26692. };
  26693. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  26694. var result = new SceneOptimizerOptions(targetFrameRate);
  26695. var priority = 0;
  26696. result.optimizations.push(new MergeMeshesOptimization(priority));
  26697. result.optimizations.push(new ShadowsOptimization(priority));
  26698. result.optimizations.push(new LensFlaresOptimization(priority));
  26699. // Next priority
  26700. priority++;
  26701. result.optimizations.push(new PostProcessesOptimization(priority));
  26702. result.optimizations.push(new ParticlesOptimization(priority));
  26703. // Next priority
  26704. priority++;
  26705. result.optimizations.push(new TextureOptimization(priority, 512));
  26706. // Next priority
  26707. priority++;
  26708. result.optimizations.push(new RenderTargetsOptimization(priority));
  26709. // Next priority
  26710. priority++;
  26711. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  26712. return result;
  26713. };
  26714. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  26715. var result = new SceneOptimizerOptions(targetFrameRate);
  26716. var priority = 0;
  26717. result.optimizations.push(new MergeMeshesOptimization(priority));
  26718. result.optimizations.push(new ShadowsOptimization(priority));
  26719. result.optimizations.push(new LensFlaresOptimization(priority));
  26720. // Next priority
  26721. priority++;
  26722. result.optimizations.push(new PostProcessesOptimization(priority));
  26723. result.optimizations.push(new ParticlesOptimization(priority));
  26724. // Next priority
  26725. priority++;
  26726. result.optimizations.push(new TextureOptimization(priority, 256));
  26727. // Next priority
  26728. priority++;
  26729. result.optimizations.push(new RenderTargetsOptimization(priority));
  26730. // Next priority
  26731. priority++;
  26732. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  26733. return result;
  26734. };
  26735. return SceneOptimizerOptions;
  26736. })();
  26737. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  26738. // Scene optimizer tool
  26739. var SceneOptimizer = (function () {
  26740. function SceneOptimizer() {
  26741. }
  26742. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  26743. // TODO: add an epsilon
  26744. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  26745. if (onSuccess) {
  26746. onSuccess();
  26747. }
  26748. return;
  26749. }
  26750. // Apply current level of optimizations
  26751. var allDone = true;
  26752. var noOptimizationApplied = true;
  26753. for (var index = 0; index < options.optimizations.length; index++) {
  26754. var optimization = options.optimizations[index];
  26755. if (optimization.priority === currentPriorityLevel) {
  26756. noOptimizationApplied = false;
  26757. allDone = allDone && optimization.apply(scene);
  26758. }
  26759. }
  26760. // If no optimization was applied, this is a failure :(
  26761. if (noOptimizationApplied) {
  26762. if (onFailure) {
  26763. onFailure();
  26764. }
  26765. return;
  26766. }
  26767. // If all optimizations were done, move to next level
  26768. if (allDone) {
  26769. currentPriorityLevel++;
  26770. }
  26771. // Let's the system running for a specific amount of time before checking FPS
  26772. scene.executeWhenReady(function () {
  26773. setTimeout(function () {
  26774. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  26775. }, options.trackerDuration);
  26776. });
  26777. };
  26778. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  26779. if (!options) {
  26780. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  26781. }
  26782. // Let's the system running for a specific amount of time before checking FPS
  26783. scene.executeWhenReady(function () {
  26784. setTimeout(function () {
  26785. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  26786. }, options.trackerDuration);
  26787. });
  26788. };
  26789. return SceneOptimizer;
  26790. })();
  26791. BABYLON.SceneOptimizer = SceneOptimizer;
  26792. })(BABYLON || (BABYLON = {}));
  26793. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  26794. (function (BABYLON) {
  26795. var Internals;
  26796. (function (Internals) {
  26797. var MeshLODLevel = (function () {
  26798. function MeshLODLevel(distance, mesh) {
  26799. this.distance = distance;
  26800. this.mesh = mesh;
  26801. }
  26802. return MeshLODLevel;
  26803. })();
  26804. Internals.MeshLODLevel = MeshLODLevel;
  26805. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26806. })(BABYLON || (BABYLON = {}));
  26807. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  26808. (function (BABYLON) {
  26809. var AudioEngine = (function () {
  26810. function AudioEngine() {
  26811. this.audioContext = null;
  26812. this.canUseWebAudio = false;
  26813. this.WarnedWebAudioUnsupported = false;
  26814. try {
  26815. if (typeof AudioContext !== 'undefined') {
  26816. this.audioContext = new AudioContext();
  26817. this.canUseWebAudio = true;
  26818. }
  26819. else if (typeof webkitAudioContext !== 'undefined') {
  26820. this.audioContext = new webkitAudioContext();
  26821. this.canUseWebAudio = true;
  26822. }
  26823. }
  26824. catch (e) {
  26825. this.canUseWebAudio = false;
  26826. BABYLON.Tools.Error("Web Audio: " + e.message);
  26827. }
  26828. // create a global volume gain node
  26829. if (this.canUseWebAudio) {
  26830. this.masterGain = this.audioContext.createGain();
  26831. this.masterGain.gain.value = 1;
  26832. this.masterGain.connect(this.audioContext.destination);
  26833. }
  26834. }
  26835. AudioEngine.prototype.dispose = function () {
  26836. if (this.canUseWebAudio) {
  26837. if (this._connectedAnalyser) {
  26838. this._connectedAnalyser.stopDebugCanvas();
  26839. this._connectedAnalyser.dispose();
  26840. this.masterGain.disconnect();
  26841. this.masterGain.connect(this.audioContext.destination);
  26842. this._connectedAnalyser = null;
  26843. }
  26844. this.masterGain.gain.value = 1;
  26845. }
  26846. this.WarnedWebAudioUnsupported = false;
  26847. };
  26848. AudioEngine.prototype.getGlobalVolume = function () {
  26849. if (this.canUseWebAudio) {
  26850. return this.masterGain.gain.value;
  26851. }
  26852. else {
  26853. return -1;
  26854. }
  26855. };
  26856. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  26857. if (this.canUseWebAudio) {
  26858. this.masterGain.gain.value = newVolume;
  26859. }
  26860. };
  26861. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  26862. if (this._connectedAnalyser) {
  26863. this._connectedAnalyser.stopDebugCanvas();
  26864. }
  26865. this._connectedAnalyser = analyser;
  26866. if (this.canUseWebAudio) {
  26867. this.masterGain.disconnect();
  26868. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  26869. }
  26870. };
  26871. return AudioEngine;
  26872. })();
  26873. BABYLON.AudioEngine = AudioEngine;
  26874. })(BABYLON || (BABYLON = {}));
  26875. //# sourceMappingURL=babylon.audioEngine.js.mapvar BABYLON;
  26876. (function (BABYLON) {
  26877. var Sound = (function () {
  26878. /**
  26879. * Create a sound and attach it to a scene
  26880. * @param name Name of your sound
  26881. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  26882. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  26883. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  26884. */
  26885. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  26886. var _this = this;
  26887. this.autoplay = false;
  26888. this.loop = false;
  26889. this.useCustomAttenuation = false;
  26890. this.spatialSound = false;
  26891. this.refDistance = 1;
  26892. this.rolloffFactor = 1;
  26893. this.maxDistance = 100;
  26894. this.distanceModel = "linear";
  26895. this._panningModel = "equalpower";
  26896. this._playbackRate = 1;
  26897. this._startTime = 0;
  26898. this._startOffset = 0;
  26899. this._position = BABYLON.Vector3.Zero();
  26900. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  26901. this._volume = 1;
  26902. this._isLoaded = false;
  26903. this._isReadyToPlay = false;
  26904. this.isPlaying = false;
  26905. this.isPaused = false;
  26906. this._isDirectional = false;
  26907. // Used if you'd like to create a directional sound.
  26908. // If not set, the sound will be omnidirectional
  26909. this._coneInnerAngle = 360;
  26910. this._coneOuterAngle = 360;
  26911. this._coneOuterGain = 0;
  26912. this.name = name;
  26913. this._scene = scene;
  26914. this._readyToPlayCallback = readyToPlayCallback;
  26915. // Default custom attenuation function is a linear attenuation
  26916. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  26917. if (currentDistance < maxDistance) {
  26918. return currentVolume * (1 - currentDistance / maxDistance);
  26919. }
  26920. else {
  26921. return 0;
  26922. }
  26923. };
  26924. if (options) {
  26925. this.autoplay = options.autoplay || false;
  26926. this.loop = options.loop || false;
  26927. // if volume === 0, we need another way to check this option
  26928. if (options.volume !== undefined) {
  26929. this._volume = options.volume;
  26930. }
  26931. this.spatialSound = options.spatialSound || false;
  26932. this.maxDistance = options.maxDistance || 100;
  26933. this.useCustomAttenuation = options.useCustomAttenuation || false;
  26934. this.rolloffFactor = options.rolloffFactor || 1;
  26935. this.refDistance = options.refDistance || 1;
  26936. this.distanceModel = options.distanceModel || "linear";
  26937. this._playbackRate = options.playbackRate || 1;
  26938. }
  26939. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26940. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  26941. this._soundGain.gain.value = this._volume;
  26942. this._inputAudioNode = this._soundGain;
  26943. this._ouputAudioNode = this._soundGain;
  26944. if (this.spatialSound) {
  26945. this._createSpatialParameters();
  26946. }
  26947. this._scene.mainSoundTrack.AddSound(this);
  26948. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  26949. if (urlOrArrayBuffer) {
  26950. // If it's an URL
  26951. if (typeof (urlOrArrayBuffer) === "string") {
  26952. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  26953. _this._soundLoaded(data);
  26954. }, null, null, true);
  26955. }
  26956. else {
  26957. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  26958. this._soundLoaded(urlOrArrayBuffer);
  26959. }
  26960. else {
  26961. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  26962. }
  26963. }
  26964. }
  26965. }
  26966. else {
  26967. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  26968. this._scene.mainSoundTrack.AddSound(this);
  26969. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  26970. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  26971. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  26972. }
  26973. if (this._readyToPlayCallback) {
  26974. this._readyToPlayCallback();
  26975. }
  26976. }
  26977. }
  26978. Sound.prototype.dispose = function () {
  26979. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  26980. if (this.isPlaying) {
  26981. this.stop();
  26982. }
  26983. this._isReadyToPlay = false;
  26984. if (this.soundTrackId === -1) {
  26985. this._scene.mainSoundTrack.RemoveSound(this);
  26986. }
  26987. else {
  26988. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  26989. }
  26990. if (this._soundGain) {
  26991. this._soundGain.disconnect();
  26992. this._soundGain = null;
  26993. }
  26994. if (this._soundPanner) {
  26995. this._soundPanner.disconnect();
  26996. this._soundPanner = null;
  26997. }
  26998. if (this._soundSource) {
  26999. this._soundSource.disconnect();
  27000. this._soundSource = null;
  27001. }
  27002. this._audioBuffer = null;
  27003. if (this._connectedMesh) {
  27004. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  27005. this._connectedMesh = null;
  27006. }
  27007. }
  27008. };
  27009. Sound.prototype._soundLoaded = function (audioData) {
  27010. var _this = this;
  27011. this._isLoaded = true;
  27012. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  27013. _this._audioBuffer = buffer;
  27014. _this._isReadyToPlay = true;
  27015. if (_this.autoplay) {
  27016. _this.play();
  27017. }
  27018. if (_this._readyToPlayCallback) {
  27019. _this._readyToPlayCallback();
  27020. }
  27021. }, function (error) {
  27022. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  27023. });
  27024. };
  27025. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  27026. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27027. this._audioBuffer = audioBuffer;
  27028. this._isReadyToPlay = true;
  27029. }
  27030. };
  27031. Sound.prototype.updateOptions = function (options) {
  27032. if (options) {
  27033. this.loop = options.loop || this.loop;
  27034. this.maxDistance = options.maxDistance || this.maxDistance;
  27035. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  27036. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  27037. this.refDistance = options.refDistance || this.refDistance;
  27038. this.distanceModel = options.distanceModel || this.distanceModel;
  27039. this._playbackRate = options.playbackRate || this._playbackRate;
  27040. }
  27041. };
  27042. Sound.prototype._createSpatialParameters = function () {
  27043. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27044. if (this._scene.headphone) {
  27045. this._panningModel = "HRTF";
  27046. }
  27047. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  27048. if (this.useCustomAttenuation) {
  27049. // Tricks to disable in a way embedded Web Audio attenuation
  27050. this._soundPanner.distanceModel = "linear";
  27051. this._soundPanner.maxDistance = Number.MAX_VALUE;
  27052. this._soundPanner.refDistance = 1;
  27053. this._soundPanner.rolloffFactor = 1;
  27054. this._soundPanner.panningModel = this._panningModel;
  27055. }
  27056. else {
  27057. this._soundPanner.distanceModel = this.distanceModel;
  27058. this._soundPanner.maxDistance = this.maxDistance;
  27059. this._soundPanner.refDistance = this.refDistance;
  27060. this._soundPanner.rolloffFactor = this.rolloffFactor;
  27061. this._soundPanner.panningModel = this._panningModel;
  27062. }
  27063. this._soundPanner.connect(this._ouputAudioNode);
  27064. this._inputAudioNode = this._soundPanner;
  27065. }
  27066. };
  27067. Sound.prototype.switchPanningModelToHRTF = function () {
  27068. this._panningModel = "HRTF";
  27069. this._switchPanningModel();
  27070. };
  27071. Sound.prototype.switchPanningModelToEqualPower = function () {
  27072. this._panningModel = "equalpower";
  27073. this._switchPanningModel();
  27074. };
  27075. Sound.prototype._switchPanningModel = function () {
  27076. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27077. this._soundPanner.panningModel = this._panningModel;
  27078. }
  27079. };
  27080. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  27081. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27082. this._ouputAudioNode.disconnect();
  27083. this._ouputAudioNode.connect(soundTrackAudioNode);
  27084. }
  27085. };
  27086. /**
  27087. * Transform this sound into a directional source
  27088. * @param coneInnerAngle Size of the inner cone in degree
  27089. * @param coneOuterAngle Size of the outer cone in degree
  27090. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  27091. */
  27092. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  27093. if (coneOuterAngle < coneInnerAngle) {
  27094. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  27095. return;
  27096. }
  27097. this._coneInnerAngle = coneInnerAngle;
  27098. this._coneOuterAngle = coneOuterAngle;
  27099. this._coneOuterGain = coneOuterGain;
  27100. this._isDirectional = true;
  27101. if (this.isPlaying && this.loop) {
  27102. this.stop();
  27103. this.play();
  27104. }
  27105. };
  27106. Sound.prototype.setPosition = function (newPosition) {
  27107. this._position = newPosition;
  27108. if (this.spatialSound) {
  27109. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27110. }
  27111. };
  27112. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  27113. this._localDirection = newLocalDirection;
  27114. if (this._connectedMesh && this.isPlaying) {
  27115. this._updateDirection();
  27116. }
  27117. };
  27118. Sound.prototype._updateDirection = function () {
  27119. var mat = this._connectedMesh.getWorldMatrix();
  27120. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  27121. direction.normalize();
  27122. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  27123. };
  27124. Sound.prototype.updateDistanceFromListener = function () {
  27125. if (this._connectedMesh && this.useCustomAttenuation) {
  27126. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  27127. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  27128. }
  27129. };
  27130. Sound.prototype.setAttenuationFunction = function (callback) {
  27131. this._customAttenuationFunction = callback;
  27132. };
  27133. /**
  27134. * Play the sound
  27135. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  27136. */
  27137. Sound.prototype.play = function (time) {
  27138. var _this = this;
  27139. if (this._isReadyToPlay && this._scene.audioEnabled) {
  27140. try {
  27141. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27142. if (!this._soundSource) {
  27143. if (this.spatialSound) {
  27144. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27145. if (this._isDirectional) {
  27146. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  27147. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  27148. this._soundPanner.coneOuterGain = this._coneOuterGain;
  27149. if (this._connectedMesh) {
  27150. this._updateDirection();
  27151. }
  27152. else {
  27153. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  27154. }
  27155. }
  27156. }
  27157. }
  27158. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  27159. this._soundSource.buffer = this._audioBuffer;
  27160. this._soundSource.connect(this._inputAudioNode);
  27161. this._soundSource.loop = this.loop;
  27162. this._soundSource.playbackRate.value = this._playbackRate;
  27163. this._startTime = startTime;
  27164. this._soundSource.onended = function () {
  27165. _this._onended();
  27166. };
  27167. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  27168. this.isPlaying = true;
  27169. this.isPaused = false;
  27170. }
  27171. catch (ex) {
  27172. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  27173. }
  27174. }
  27175. };
  27176. Sound.prototype._onended = function () {
  27177. if (!this.loop) {
  27178. this.isPlaying = false;
  27179. if (this.onended) {
  27180. this.onended();
  27181. }
  27182. }
  27183. };
  27184. /**
  27185. * Stop the sound
  27186. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  27187. */
  27188. Sound.prototype.stop = function (time) {
  27189. if (this.isPlaying) {
  27190. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27191. this._soundSource.stop(stopTime);
  27192. this.isPlaying = false;
  27193. }
  27194. };
  27195. Sound.prototype.pause = function () {
  27196. if (this.isPlaying) {
  27197. this.stop(0);
  27198. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  27199. this.isPaused = true;
  27200. }
  27201. };
  27202. Sound.prototype.setVolume = function (newVolume, time) {
  27203. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27204. if (time) {
  27205. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  27206. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  27207. }
  27208. else {
  27209. this._soundGain.gain.value = newVolume;
  27210. }
  27211. }
  27212. this._volume = newVolume;
  27213. };
  27214. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  27215. this._playbackRate = newPlaybackRate;
  27216. if (this.isPlaying) {
  27217. this._soundSource.playbackRate.value = this._playbackRate;
  27218. }
  27219. };
  27220. Sound.prototype.getVolume = function () {
  27221. return this._volume;
  27222. };
  27223. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  27224. var _this = this;
  27225. this._connectedMesh = meshToConnectTo;
  27226. if (!this.spatialSound) {
  27227. this._createSpatialParameters();
  27228. this.spatialSound = true;
  27229. if (this.isPlaying && this.loop) {
  27230. this.stop();
  27231. this.play();
  27232. }
  27233. }
  27234. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  27235. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  27236. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  27237. };
  27238. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  27239. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  27240. if (this._isDirectional && this.isPlaying) {
  27241. this._updateDirection();
  27242. }
  27243. };
  27244. return Sound;
  27245. })();
  27246. BABYLON.Sound = Sound;
  27247. })(BABYLON || (BABYLON = {}));
  27248. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  27249. (function (BABYLON) {
  27250. var SoundTrack = (function () {
  27251. function SoundTrack(scene, options) {
  27252. this.id = -1;
  27253. this._isMainTrack = false;
  27254. this._scene = scene;
  27255. this._audioEngine = BABYLON.Engine.audioEngine;
  27256. this.soundCollection = new Array();
  27257. if (this._audioEngine.canUseWebAudio) {
  27258. this._trackGain = this._audioEngine.audioContext.createGain();
  27259. this._trackGain.connect(this._audioEngine.masterGain);
  27260. if (options) {
  27261. if (options.volume) {
  27262. this._trackGain.gain.value = options.volume;
  27263. }
  27264. if (options.mainTrack) {
  27265. this._isMainTrack = options.mainTrack;
  27266. }
  27267. }
  27268. }
  27269. if (!this._isMainTrack) {
  27270. this._scene.soundTracks.push(this);
  27271. this.id = this._scene.soundTracks.length - 1;
  27272. }
  27273. }
  27274. SoundTrack.prototype.dispose = function () {
  27275. if (this._audioEngine.canUseWebAudio) {
  27276. if (this._connectedAnalyser) {
  27277. this._connectedAnalyser.stopDebugCanvas();
  27278. }
  27279. while (this.soundCollection.length) {
  27280. this.soundCollection[0].dispose();
  27281. }
  27282. this._trackGain.disconnect();
  27283. this._trackGain = null;
  27284. }
  27285. };
  27286. SoundTrack.prototype.AddSound = function (sound) {
  27287. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27288. sound.connectToSoundTrackAudioNode(this._trackGain);
  27289. }
  27290. if (sound.soundTrackId) {
  27291. if (sound.soundTrackId === -1) {
  27292. this._scene.mainSoundTrack.RemoveSound(sound);
  27293. }
  27294. else {
  27295. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  27296. }
  27297. }
  27298. this.soundCollection.push(sound);
  27299. sound.soundTrackId = this.id;
  27300. };
  27301. SoundTrack.prototype.RemoveSound = function (sound) {
  27302. var index = this.soundCollection.indexOf(sound);
  27303. if (index !== -1) {
  27304. this.soundCollection.splice(index, 1);
  27305. }
  27306. };
  27307. SoundTrack.prototype.setVolume = function (newVolume) {
  27308. if (this._audioEngine.canUseWebAudio) {
  27309. this._trackGain.gain.value = newVolume;
  27310. }
  27311. };
  27312. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  27313. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27314. for (var i = 0; i < this.soundCollection.length; i++) {
  27315. this.soundCollection[i].switchPanningModelToHRTF();
  27316. }
  27317. }
  27318. };
  27319. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  27320. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27321. for (var i = 0; i < this.soundCollection.length; i++) {
  27322. this.soundCollection[i].switchPanningModelToEqualPower();
  27323. }
  27324. }
  27325. };
  27326. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  27327. if (this._connectedAnalyser) {
  27328. this._connectedAnalyser.stopDebugCanvas();
  27329. }
  27330. this._connectedAnalyser = analyser;
  27331. if (this._audioEngine.canUseWebAudio) {
  27332. this._trackGain.disconnect();
  27333. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  27334. }
  27335. };
  27336. return SoundTrack;
  27337. })();
  27338. BABYLON.SoundTrack = SoundTrack;
  27339. })(BABYLON || (BABYLON = {}));
  27340. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  27341. (function (BABYLON) {
  27342. var DebugLayer = (function () {
  27343. function DebugLayer(scene) {
  27344. var _this = this;
  27345. this._transformationMatrix = BABYLON.Matrix.Identity();
  27346. this._enabled = false;
  27347. this._labelsEnabled = false;
  27348. this._displayStatistics = true;
  27349. this._displayTree = false;
  27350. this._displayLogs = false;
  27351. this._identityMatrix = BABYLON.Matrix.Identity();
  27352. this.axisRatio = 0.02;
  27353. this.accentColor = "orange";
  27354. this._scene = scene;
  27355. this._syncPositions = function () {
  27356. var engine = _this._scene.getEngine();
  27357. var canvasRect = engine.getRenderingCanvasClientRect();
  27358. if (_this._showUI) {
  27359. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  27360. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  27361. _this._statsDiv.style.width = "400px";
  27362. _this._statsDiv.style.height = "auto";
  27363. _this._statsSubsetDiv.style.maxHeight = "240px";
  27364. _this._optionsDiv.style.left = "0px";
  27365. _this._optionsDiv.style.top = "10px";
  27366. _this._optionsDiv.style.width = "200px";
  27367. _this._optionsDiv.style.height = "auto";
  27368. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  27369. _this._logDiv.style.left = "0px";
  27370. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27371. _this._logDiv.style.width = "600px";
  27372. _this._logDiv.style.height = "160px";
  27373. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27374. _this._treeDiv.style.top = "10px";
  27375. _this._treeDiv.style.width = "300px";
  27376. _this._treeDiv.style.height = "auto";
  27377. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27378. }
  27379. _this._globalDiv.style.left = canvasRect.left + "px";
  27380. _this._globalDiv.style.top = canvasRect.top + "px";
  27381. _this._drawingCanvas.style.left = "0px";
  27382. _this._drawingCanvas.style.top = "0px";
  27383. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27384. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27385. var devicePixelRatio = window.devicePixelRatio || 1;
  27386. var context = _this._drawingContext;
  27387. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  27388. _this._ratio = devicePixelRatio / backingStoreRatio;
  27389. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27390. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27391. };
  27392. this._onCanvasClick = function (evt) {
  27393. _this._clickPosition = {
  27394. x: evt.clientX * _this._ratio,
  27395. y: evt.clientY * _this._ratio
  27396. };
  27397. };
  27398. this._syncUI = function () {
  27399. if (_this._showUI) {
  27400. if (_this._displayStatistics) {
  27401. _this._displayStats();
  27402. _this._statsDiv.style.display = "";
  27403. }
  27404. else {
  27405. _this._statsDiv.style.display = "none";
  27406. }
  27407. if (_this._displayLogs) {
  27408. _this._logDiv.style.display = "";
  27409. }
  27410. else {
  27411. _this._logDiv.style.display = "none";
  27412. }
  27413. if (_this._displayTree) {
  27414. _this._treeDiv.style.display = "";
  27415. if (_this._needToRefreshMeshesTree) {
  27416. _this._needToRefreshMeshesTree = false;
  27417. _this._refreshMeshesTreeContent();
  27418. }
  27419. }
  27420. else {
  27421. _this._treeDiv.style.display = "none";
  27422. }
  27423. }
  27424. };
  27425. this._syncData = function () {
  27426. if (_this._labelsEnabled || !_this._showUI) {
  27427. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27428. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27429. var engine = _this._scene.getEngine();
  27430. var viewport = _this._camera.viewport;
  27431. var globalViewport = viewport.toGlobal(engine);
  27432. // Meshes
  27433. var meshes = _this._camera.getActiveMeshes();
  27434. for (var index = 0; index < meshes.length; index++) {
  27435. var mesh = meshes.data[index];
  27436. var position = mesh.getBoundingInfo().boundingSphere.center;
  27437. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27438. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27439. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27440. }
  27441. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27442. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  27443. mesh.renderOverlay = !mesh.renderOverlay;
  27444. }, function () {
  27445. return mesh.renderOverlay ? 'red' : 'black';
  27446. });
  27447. }
  27448. }
  27449. // Cameras
  27450. var cameras = _this._scene.cameras;
  27451. for (index = 0; index < cameras.length; index++) {
  27452. var camera = cameras[index];
  27453. if (camera === _this._camera) {
  27454. continue;
  27455. }
  27456. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27457. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27458. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27459. _this._camera.detachControl(engine.getRenderingCanvas());
  27460. _this._camera = camera;
  27461. _this._camera.attachControl(engine.getRenderingCanvas());
  27462. }, function () {
  27463. return "purple";
  27464. });
  27465. }
  27466. }
  27467. // Lights
  27468. var lights = _this._scene.lights;
  27469. for (index = 0; index < lights.length; index++) {
  27470. var light = lights[index];
  27471. if (light.position) {
  27472. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27473. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27474. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27475. light.setEnabled(!light.isEnabled());
  27476. }, function () {
  27477. return light.isEnabled() ? "orange" : "gray";
  27478. });
  27479. }
  27480. }
  27481. }
  27482. }
  27483. _this._clickPosition = undefined;
  27484. };
  27485. }
  27486. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27487. while (this._treeSubsetDiv.hasChildNodes()) {
  27488. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27489. }
  27490. // Add meshes
  27491. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27492. sortedArray.sort(function (a, b) {
  27493. if (a.name === b.name) {
  27494. return 0;
  27495. }
  27496. return (a.name > b.name) ? 1 : -1;
  27497. });
  27498. for (var index = 0; index < sortedArray.length; index++) {
  27499. var mesh = sortedArray[index];
  27500. if (!mesh.isEnabled()) {
  27501. continue;
  27502. }
  27503. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27504. m.isVisible = element.checked;
  27505. }, mesh);
  27506. }
  27507. };
  27508. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27509. this._drawingContext.beginPath();
  27510. this._drawingContext.moveTo(zero.x, zero.y);
  27511. this._drawingContext.lineTo(unit.x, unit.y);
  27512. this._drawingContext.strokeStyle = color;
  27513. this._drawingContext.lineWidth = 4;
  27514. this._drawingContext.stroke();
  27515. this._drawingContext.font = "normal 14px Segoe UI";
  27516. this._drawingContext.fillStyle = color;
  27517. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27518. };
  27519. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27520. var position = mesh.getBoundingInfo().boundingSphere.center;
  27521. var worldMatrix = mesh.getWorldMatrix();
  27522. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27523. var unit = (unprojectedVector.subtract(position)).length();
  27524. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27525. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27526. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27527. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27528. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27529. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27530. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27531. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27532. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27533. };
  27534. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27535. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27536. this._drawingContext.font = "normal 12px Segoe UI";
  27537. var textMetrics = this._drawingContext.measureText(text);
  27538. var centerX = projectedPosition.x - textMetrics.width / 2;
  27539. var centerY = projectedPosition.y;
  27540. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27541. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27542. onClick();
  27543. }
  27544. this._drawingContext.beginPath();
  27545. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27546. this._drawingContext.fillStyle = getFillStyle();
  27547. this._drawingContext.globalAlpha = 0.5;
  27548. this._drawingContext.fill();
  27549. this._drawingContext.globalAlpha = 1.0;
  27550. this._drawingContext.strokeStyle = '#FFFFFF';
  27551. this._drawingContext.lineWidth = 1;
  27552. this._drawingContext.stroke();
  27553. this._drawingContext.fillStyle = "#FFFFFF";
  27554. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27555. this._drawingContext.beginPath();
  27556. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27557. this._drawingContext.fill();
  27558. }
  27559. };
  27560. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27561. if (!this._clickPosition) {
  27562. return false;
  27563. }
  27564. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27565. return false;
  27566. }
  27567. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27568. return false;
  27569. }
  27570. return true;
  27571. };
  27572. DebugLayer.prototype.isVisible = function () {
  27573. return this._enabled;
  27574. };
  27575. DebugLayer.prototype.hide = function () {
  27576. if (!this._enabled) {
  27577. return;
  27578. }
  27579. this._enabled = false;
  27580. var engine = this._scene.getEngine();
  27581. this._scene.unregisterBeforeRender(this._syncData);
  27582. this._scene.unregisterAfterRender(this._syncUI);
  27583. document.body.removeChild(this._globalDiv);
  27584. window.removeEventListener("resize", this._syncPositions);
  27585. this._scene.forceShowBoundingBoxes = false;
  27586. this._scene.forceWireframe = false;
  27587. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27588. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27589. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27590. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27591. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27592. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27593. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27594. this._scene.shadowsEnabled = true;
  27595. this._scene.particlesEnabled = true;
  27596. this._scene.postProcessesEnabled = true;
  27597. this._scene.collisionsEnabled = true;
  27598. this._scene.lightsEnabled = true;
  27599. this._scene.texturesEnabled = true;
  27600. this._scene.lensFlaresEnabled = true;
  27601. this._scene.proceduralTexturesEnabled = true;
  27602. this._scene.renderTargetsEnabled = true;
  27603. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27604. };
  27605. DebugLayer.prototype.show = function (showUI, camera) {
  27606. if (showUI === void 0) { showUI = true; }
  27607. if (camera === void 0) { camera = null; }
  27608. if (this._enabled) {
  27609. return;
  27610. }
  27611. if (camera) {
  27612. this._camera = camera;
  27613. }
  27614. else {
  27615. this._camera = this._scene.activeCamera;
  27616. }
  27617. this._enabled = true;
  27618. this._showUI = showUI;
  27619. var engine = this._scene.getEngine();
  27620. this._globalDiv = document.createElement("div");
  27621. document.body.appendChild(this._globalDiv);
  27622. this._generateDOMelements();
  27623. window.addEventListener("resize", this._syncPositions);
  27624. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27625. this._syncPositions();
  27626. this._scene.registerBeforeRender(this._syncData);
  27627. this._scene.registerAfterRender(this._syncUI);
  27628. };
  27629. DebugLayer.prototype._clearLabels = function () {
  27630. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27631. for (var index = 0; index < this._scene.meshes.length; index++) {
  27632. var mesh = this._scene.meshes[index];
  27633. mesh.renderOverlay = false;
  27634. }
  27635. };
  27636. DebugLayer.prototype._generateheader = function (root, text) {
  27637. var header = document.createElement("div");
  27638. header.innerHTML = text + "&nbsp;";
  27639. header.style.textAlign = "right";
  27640. header.style.width = "100%";
  27641. header.style.color = "white";
  27642. header.style.backgroundColor = "Black";
  27643. header.style.padding = "5px 5px 4px 0px";
  27644. header.style.marginLeft = "-5px";
  27645. header.style.fontWeight = "bold";
  27646. root.appendChild(header);
  27647. };
  27648. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27649. var label = document.createElement("label");
  27650. label.innerHTML = title;
  27651. label.style.color = color;
  27652. root.appendChild(label);
  27653. root.appendChild(document.createElement("br"));
  27654. };
  27655. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27656. if (tag === void 0) { tag = null; }
  27657. var label = document.createElement("label");
  27658. var boundingBoxesCheckbox = document.createElement("input");
  27659. boundingBoxesCheckbox.type = "checkbox";
  27660. boundingBoxesCheckbox.checked = initialState;
  27661. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27662. task(evt.target, tag);
  27663. });
  27664. label.appendChild(boundingBoxesCheckbox);
  27665. var container = document.createElement("span");
  27666. var leftPart = document.createElement("span");
  27667. var rightPart = document.createElement("span");
  27668. rightPart.style.cssFloat = "right";
  27669. leftPart.innerHTML = leftTitle;
  27670. rightPart.innerHTML = rightTitle;
  27671. rightPart.style.fontSize = "12px";
  27672. rightPart.style.maxWidth = "200px";
  27673. container.appendChild(leftPart);
  27674. container.appendChild(rightPart);
  27675. label.appendChild(container);
  27676. root.appendChild(label);
  27677. root.appendChild(document.createElement("br"));
  27678. };
  27679. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27680. if (tag === void 0) { tag = null; }
  27681. var label = document.createElement("label");
  27682. var checkBox = document.createElement("input");
  27683. checkBox.type = "checkbox";
  27684. checkBox.checked = initialState;
  27685. checkBox.addEventListener("change", function (evt) {
  27686. task(evt.target, tag);
  27687. });
  27688. label.appendChild(checkBox);
  27689. label.appendChild(document.createTextNode(title));
  27690. root.appendChild(label);
  27691. root.appendChild(document.createElement("br"));
  27692. };
  27693. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27694. if (tag === void 0) { tag = null; }
  27695. var button = document.createElement("button");
  27696. button.innerHTML = title;
  27697. button.style.height = "24px";
  27698. button.style.color = "#444444";
  27699. button.style.border = "1px solid white";
  27700. button.className = "debugLayerButton";
  27701. button.addEventListener("click", function (evt) {
  27702. task(evt.target, tag);
  27703. });
  27704. root.appendChild(button);
  27705. root.appendChild(document.createElement("br"));
  27706. };
  27707. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27708. if (tag === void 0) { tag = null; }
  27709. var label = document.createElement("label");
  27710. var boundingBoxesRadio = document.createElement("input");
  27711. boundingBoxesRadio.type = "radio";
  27712. boundingBoxesRadio.name = name;
  27713. boundingBoxesRadio.checked = initialState;
  27714. boundingBoxesRadio.addEventListener("change", function (evt) {
  27715. task(evt.target, tag);
  27716. });
  27717. label.appendChild(boundingBoxesRadio);
  27718. label.appendChild(document.createTextNode(title));
  27719. root.appendChild(label);
  27720. root.appendChild(document.createElement("br"));
  27721. };
  27722. DebugLayer.prototype._generateDOMelements = function () {
  27723. var _this = this;
  27724. this._globalDiv.id = "DebugLayer";
  27725. this._globalDiv.style.position = "absolute";
  27726. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27727. this._globalDiv.style.fontSize = "14px";
  27728. this._globalDiv.style.color = "white";
  27729. // Drawing canvas
  27730. this._drawingCanvas = document.createElement("canvas");
  27731. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27732. this._drawingCanvas.style.position = "absolute";
  27733. this._drawingCanvas.style.pointerEvents = "none";
  27734. this._drawingContext = this._drawingCanvas.getContext("2d");
  27735. this._globalDiv.appendChild(this._drawingCanvas);
  27736. if (this._showUI) {
  27737. var background = "rgba(128, 128, 128, 0.4)";
  27738. var border = "rgb(180, 180, 180) solid 1px";
  27739. // Stats
  27740. this._statsDiv = document.createElement("div");
  27741. this._statsDiv.id = "DebugLayerStats";
  27742. this._statsDiv.style.border = border;
  27743. this._statsDiv.style.position = "absolute";
  27744. this._statsDiv.style.background = background;
  27745. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27746. this._generateheader(this._statsDiv, "STATISTICS");
  27747. this._statsSubsetDiv = document.createElement("div");
  27748. this._statsSubsetDiv.style.paddingTop = "5px";
  27749. this._statsSubsetDiv.style.paddingBottom = "5px";
  27750. this._statsSubsetDiv.style.overflowY = "auto";
  27751. this._statsDiv.appendChild(this._statsSubsetDiv);
  27752. // Tree
  27753. this._treeDiv = document.createElement("div");
  27754. this._treeDiv.id = "DebugLayerTree";
  27755. this._treeDiv.style.border = border;
  27756. this._treeDiv.style.position = "absolute";
  27757. this._treeDiv.style.background = background;
  27758. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27759. this._treeDiv.style.display = "none";
  27760. this._generateheader(this._treeDiv, "MESHES TREE");
  27761. this._treeSubsetDiv = document.createElement("div");
  27762. this._treeSubsetDiv.style.paddingTop = "5px";
  27763. this._treeSubsetDiv.style.paddingRight = "5px";
  27764. this._treeSubsetDiv.style.overflowY = "auto";
  27765. this._treeSubsetDiv.style.maxHeight = "300px";
  27766. this._treeDiv.appendChild(this._treeSubsetDiv);
  27767. this._needToRefreshMeshesTree = true;
  27768. // Logs
  27769. this._logDiv = document.createElement("div");
  27770. this._logDiv.style.border = border;
  27771. this._logDiv.id = "DebugLayerLogs";
  27772. this._logDiv.style.position = "absolute";
  27773. this._logDiv.style.background = background;
  27774. this._logDiv.style.padding = "0px 0px 0px 5px";
  27775. this._logDiv.style.display = "none";
  27776. this._generateheader(this._logDiv, "LOGS");
  27777. this._logSubsetDiv = document.createElement("div");
  27778. this._logSubsetDiv.style.height = "127px";
  27779. this._logSubsetDiv.style.paddingTop = "5px";
  27780. this._logSubsetDiv.style.overflowY = "auto";
  27781. this._logSubsetDiv.style.fontSize = "12px";
  27782. this._logSubsetDiv.style.fontFamily = "consolas";
  27783. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27784. this._logDiv.appendChild(this._logSubsetDiv);
  27785. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27786. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27787. };
  27788. // Options
  27789. this._optionsDiv = document.createElement("div");
  27790. this._optionsDiv.id = "DebugLayerOptions";
  27791. this._optionsDiv.style.border = border;
  27792. this._optionsDiv.style.position = "absolute";
  27793. this._optionsDiv.style.background = background;
  27794. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27795. this._optionsDiv.style.overflowY = "auto";
  27796. this._generateheader(this._optionsDiv, "OPTIONS");
  27797. this._optionsSubsetDiv = document.createElement("div");
  27798. this._optionsSubsetDiv.style.paddingTop = "5px";
  27799. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27800. this._optionsSubsetDiv.style.overflowY = "auto";
  27801. this._optionsSubsetDiv.style.maxHeight = "200px";
  27802. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27803. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27804. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  27805. _this._displayStatistics = element.checked;
  27806. });
  27807. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  27808. _this._displayLogs = element.checked;
  27809. });
  27810. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27811. _this._displayTree = element.checked;
  27812. _this._needToRefreshMeshesTree = true;
  27813. });
  27814. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27815. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27816. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  27817. _this._scene.forceShowBoundingBoxes = element.checked;
  27818. });
  27819. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27820. _this._labelsEnabled = element.checked;
  27821. if (!_this._labelsEnabled) {
  27822. _this._clearLabels();
  27823. }
  27824. });
  27825. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27826. if (element.checked) {
  27827. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27828. }
  27829. else {
  27830. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27831. }
  27832. });
  27833. ;
  27834. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27835. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27836. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27837. if (element.checked) {
  27838. _this._scene.forceWireframe = false;
  27839. _this._scene.forcePointsCloud = false;
  27840. }
  27841. });
  27842. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27843. if (element.checked) {
  27844. _this._scene.forceWireframe = true;
  27845. _this._scene.forcePointsCloud = false;
  27846. }
  27847. });
  27848. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27849. if (element.checked) {
  27850. _this._scene.forceWireframe = false;
  27851. _this._scene.forcePointsCloud = true;
  27852. }
  27853. });
  27854. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27855. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27856. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  27857. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  27858. });
  27859. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  27860. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  27861. });
  27862. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  27863. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  27864. });
  27865. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  27866. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  27867. });
  27868. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  27869. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  27870. });
  27871. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  27872. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  27873. });
  27874. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  27875. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  27876. });
  27877. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  27878. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  27879. });
  27880. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27881. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27882. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  27883. _this._scene.animationsEnabled = element.checked;
  27884. });
  27885. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  27886. _this._scene.collisionsEnabled = element.checked;
  27887. });
  27888. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  27889. _this._scene.fogEnabled = element.checked;
  27890. });
  27891. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  27892. _this._scene.lensFlaresEnabled = element.checked;
  27893. });
  27894. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  27895. _this._scene.lightsEnabled = element.checked;
  27896. });
  27897. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  27898. _this._scene.particlesEnabled = element.checked;
  27899. });
  27900. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  27901. _this._scene.postProcessesEnabled = element.checked;
  27902. });
  27903. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  27904. _this._scene.proceduralTexturesEnabled = element.checked;
  27905. });
  27906. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  27907. _this._scene.renderTargetsEnabled = element.checked;
  27908. });
  27909. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  27910. _this._scene.shadowsEnabled = element.checked;
  27911. });
  27912. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  27913. _this._scene.skeletonsEnabled = element.checked;
  27914. });
  27915. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  27916. _this._scene.spritesEnabled = element.checked;
  27917. });
  27918. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  27919. _this._scene.texturesEnabled = element.checked;
  27920. });
  27921. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27922. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27923. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27924. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  27925. if (element.checked) {
  27926. _this._scene.headphone = true;
  27927. }
  27928. });
  27929. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  27930. if (element.checked) {
  27931. _this._scene.headphone = false;
  27932. }
  27933. });
  27934. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27935. _this._scene.audioEnabled = !element.checked;
  27936. });
  27937. }
  27938. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27939. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27940. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  27941. _this._scene.dumpNextRenderTargets = true;
  27942. });
  27943. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27944. this._globalDiv.appendChild(this._statsDiv);
  27945. this._globalDiv.appendChild(this._logDiv);
  27946. this._globalDiv.appendChild(this._optionsDiv);
  27947. this._globalDiv.appendChild(this._treeDiv);
  27948. }
  27949. };
  27950. DebugLayer.prototype._displayStats = function () {
  27951. var scene = this._scene;
  27952. var engine = scene.getEngine();
  27953. var glInfo = engine.getGlInfo();
  27954. 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>";
  27955. if (this.customStatsFunction) {
  27956. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27957. }
  27958. };
  27959. return DebugLayer;
  27960. })();
  27961. BABYLON.DebugLayer = DebugLayer;
  27962. })(BABYLON || (BABYLON = {}));
  27963. //# sourceMappingURL=babylon.debugLayer.js.map
  27964. var BABYLON;
  27965. (function (BABYLON) {
  27966. var RawTexture = (function (_super) {
  27967. __extends(RawTexture, _super);
  27968. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  27969. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27970. if (invertY === void 0) { invertY = false; }
  27971. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27972. _super.call(this, null, scene, !generateMipMaps, invertY);
  27973. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  27974. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27975. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27976. }
  27977. // Statics
  27978. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27979. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27980. if (invertY === void 0) { invertY = false; }
  27981. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27982. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  27983. };
  27984. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27985. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27986. if (invertY === void 0) { invertY = false; }
  27987. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27988. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27989. };
  27990. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27991. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27992. if (invertY === void 0) { invertY = false; }
  27993. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27994. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27995. };
  27996. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27997. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27998. if (invertY === void 0) { invertY = false; }
  27999. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28000. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  28001. };
  28002. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28003. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28004. if (invertY === void 0) { invertY = false; }
  28005. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28006. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  28007. };
  28008. return RawTexture;
  28009. })(BABYLON.Texture);
  28010. BABYLON.RawTexture = RawTexture;
  28011. })(BABYLON || (BABYLON = {}));
  28012. //# sourceMappingURL=babylon.rawTexture.js.map
  28013. var BABYLON;
  28014. (function (BABYLON) {
  28015. var IndexedVector2 = (function (_super) {
  28016. __extends(IndexedVector2, _super);
  28017. function IndexedVector2(original, index) {
  28018. _super.call(this, original.x, original.y);
  28019. this.index = index;
  28020. }
  28021. return IndexedVector2;
  28022. })(BABYLON.Vector2);
  28023. var PolygonPoints = (function () {
  28024. function PolygonPoints() {
  28025. this.elements = new Array();
  28026. }
  28027. PolygonPoints.prototype.add = function (originalPoints) {
  28028. var _this = this;
  28029. var result = new Array();
  28030. originalPoints.forEach(function (point) {
  28031. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  28032. var newPoint = new IndexedVector2(point, _this.elements.length);
  28033. result.push(newPoint);
  28034. _this.elements.push(newPoint);
  28035. }
  28036. });
  28037. return result;
  28038. };
  28039. PolygonPoints.prototype.computeBounds = function () {
  28040. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28041. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28042. this.elements.forEach(function (point) {
  28043. // x
  28044. if (point.x < lmin.x) {
  28045. lmin.x = point.x;
  28046. }
  28047. else if (point.x > lmax.x) {
  28048. lmax.x = point.x;
  28049. }
  28050. // y
  28051. if (point.y < lmin.y) {
  28052. lmin.y = point.y;
  28053. }
  28054. else if (point.y > lmax.y) {
  28055. lmax.y = point.y;
  28056. }
  28057. });
  28058. return {
  28059. min: lmin,
  28060. max: lmax,
  28061. width: lmax.x - lmin.x,
  28062. height: lmax.y - lmin.y
  28063. };
  28064. };
  28065. return PolygonPoints;
  28066. })();
  28067. var Polygon = (function () {
  28068. function Polygon() {
  28069. }
  28070. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  28071. return [
  28072. new BABYLON.Vector2(xmin, ymin),
  28073. new BABYLON.Vector2(xmax, ymin),
  28074. new BABYLON.Vector2(xmax, ymax),
  28075. new BABYLON.Vector2(xmin, ymax)
  28076. ];
  28077. };
  28078. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  28079. if (cx === void 0) { cx = 0; }
  28080. if (cy === void 0) { cy = 0; }
  28081. if (numberOfSides === void 0) { numberOfSides = 32; }
  28082. var result = new Array();
  28083. var angle = 0;
  28084. var increment = (Math.PI * 2) / numberOfSides;
  28085. for (var i = 0; i < numberOfSides; i++) {
  28086. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  28087. angle -= increment;
  28088. }
  28089. return result;
  28090. };
  28091. Polygon.Parse = function (input) {
  28092. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  28093. var i, result = [];
  28094. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  28095. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  28096. }
  28097. return result;
  28098. };
  28099. Polygon.StartingAt = function (x, y) {
  28100. return BABYLON.Path2.StartingAt(x, y);
  28101. };
  28102. return Polygon;
  28103. })();
  28104. BABYLON.Polygon = Polygon;
  28105. var PolygonMeshBuilder = (function () {
  28106. function PolygonMeshBuilder(name, contours, scene) {
  28107. this._points = new PolygonPoints();
  28108. if (!("poly2tri" in window)) {
  28109. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  28110. }
  28111. this._name = name;
  28112. this._scene = scene;
  28113. var points;
  28114. if (contours instanceof BABYLON.Path2) {
  28115. points = contours.getPoints();
  28116. }
  28117. else {
  28118. points = contours;
  28119. }
  28120. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  28121. }
  28122. PolygonMeshBuilder.prototype.addHole = function (hole) {
  28123. this._swctx.addHole(this._points.add(hole));
  28124. return this;
  28125. };
  28126. PolygonMeshBuilder.prototype.build = function (updatable) {
  28127. if (updatable === void 0) { updatable = false; }
  28128. var result = new BABYLON.Mesh(this._name, this._scene);
  28129. var normals = [];
  28130. var positions = [];
  28131. var uvs = [];
  28132. var bounds = this._points.computeBounds();
  28133. this._points.elements.forEach(function (p) {
  28134. normals.push(0, 1.0, 0);
  28135. positions.push(p.x, 0, p.y);
  28136. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  28137. });
  28138. var indices = [];
  28139. this._swctx.triangulate();
  28140. this._swctx.getTriangles().forEach(function (triangle) {
  28141. triangle.getPoints().forEach(function (point) {
  28142. indices.push(point.index);
  28143. });
  28144. });
  28145. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  28146. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  28147. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  28148. result.setIndices(indices);
  28149. return result;
  28150. };
  28151. return PolygonMeshBuilder;
  28152. })();
  28153. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  28154. })(BABYLON || (BABYLON = {}));
  28155. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  28156. (function (BABYLON) {
  28157. var SimplificationSettings = (function () {
  28158. function SimplificationSettings(quality, distance) {
  28159. this.quality = quality;
  28160. this.distance = distance;
  28161. }
  28162. return SimplificationSettings;
  28163. })();
  28164. BABYLON.SimplificationSettings = SimplificationSettings;
  28165. var SimplificationQueue = (function () {
  28166. function SimplificationQueue() {
  28167. this.running = false;
  28168. this._simplificationArray = [];
  28169. }
  28170. SimplificationQueue.prototype.addTask = function (task) {
  28171. this._simplificationArray.push(task);
  28172. };
  28173. SimplificationQueue.prototype.executeNext = function () {
  28174. var task = this._simplificationArray.pop();
  28175. if (task) {
  28176. this.running = true;
  28177. this.runSimplification(task);
  28178. }
  28179. else {
  28180. this.running = false;
  28181. }
  28182. };
  28183. SimplificationQueue.prototype.runSimplification = function (task) {
  28184. var _this = this;
  28185. if (task.parallelProcessing) {
  28186. //parallel simplifier
  28187. task.settings.forEach(function (setting) {
  28188. var simplifier = _this.getSimplifier(task);
  28189. simplifier.simplify(setting, function (newMesh) {
  28190. task.mesh.addLODLevel(setting.distance, newMesh);
  28191. newMesh.isVisible = true;
  28192. //check if it is the last
  28193. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28194. //all done, run the success callback.
  28195. task.successCallback();
  28196. }
  28197. _this.executeNext();
  28198. });
  28199. });
  28200. }
  28201. else {
  28202. //single simplifier.
  28203. var simplifier = this.getSimplifier(task);
  28204. var runDecimation = function (setting, callback) {
  28205. simplifier.simplify(setting, function (newMesh) {
  28206. task.mesh.addLODLevel(setting.distance, newMesh);
  28207. newMesh.isVisible = true;
  28208. //run the next quality level
  28209. callback();
  28210. });
  28211. };
  28212. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28213. runDecimation(task.settings[loop.index], function () {
  28214. loop.executeNext();
  28215. });
  28216. }, function () {
  28217. //execution ended, run the success callback.
  28218. if (task.successCallback) {
  28219. task.successCallback();
  28220. }
  28221. _this.executeNext();
  28222. });
  28223. }
  28224. };
  28225. SimplificationQueue.prototype.getSimplifier = function (task) {
  28226. switch (task.simplificationType) {
  28227. case 0 /* QUADRATIC */:
  28228. default:
  28229. return new QuadraticErrorSimplification(task.mesh);
  28230. }
  28231. };
  28232. return SimplificationQueue;
  28233. })();
  28234. BABYLON.SimplificationQueue = SimplificationQueue;
  28235. /**
  28236. * The implemented types of simplification.
  28237. * At the moment only Quadratic Error Decimation is implemented.
  28238. */
  28239. (function (SimplificationType) {
  28240. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28241. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28242. var SimplificationType = BABYLON.SimplificationType;
  28243. var DecimationTriangle = (function () {
  28244. function DecimationTriangle(vertices) {
  28245. this.vertices = vertices;
  28246. this.error = new Array(4);
  28247. this.deleted = false;
  28248. this.isDirty = false;
  28249. this.deletePending = false;
  28250. this.borderFactor = 0;
  28251. }
  28252. return DecimationTriangle;
  28253. })();
  28254. BABYLON.DecimationTriangle = DecimationTriangle;
  28255. var DecimationVertex = (function () {
  28256. function DecimationVertex(position, normal, uv, id) {
  28257. this.position = position;
  28258. this.normal = normal;
  28259. this.uv = uv;
  28260. this.id = id;
  28261. this.isBorder = true;
  28262. this.q = new QuadraticMatrix();
  28263. this.triangleCount = 0;
  28264. this.triangleStart = 0;
  28265. }
  28266. return DecimationVertex;
  28267. })();
  28268. BABYLON.DecimationVertex = DecimationVertex;
  28269. var QuadraticMatrix = (function () {
  28270. function QuadraticMatrix(data) {
  28271. this.data = new Array(10);
  28272. for (var i = 0; i < 10; ++i) {
  28273. if (data && data[i]) {
  28274. this.data[i] = data[i];
  28275. }
  28276. else {
  28277. this.data[i] = 0;
  28278. }
  28279. }
  28280. }
  28281. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28282. 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];
  28283. return det;
  28284. };
  28285. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28286. for (var i = 0; i < 10; ++i) {
  28287. this.data[i] += matrix.data[i];
  28288. }
  28289. };
  28290. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  28291. for (var i = 0; i < 10; ++i) {
  28292. this.data[i] += data[i];
  28293. }
  28294. };
  28295. QuadraticMatrix.prototype.add = function (matrix) {
  28296. var m = new QuadraticMatrix();
  28297. for (var i = 0; i < 10; ++i) {
  28298. m.data[i] = this.data[i] + matrix.data[i];
  28299. }
  28300. return m;
  28301. };
  28302. QuadraticMatrix.FromData = function (a, b, c, d) {
  28303. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  28304. };
  28305. //returning an array to avoid garbage collection
  28306. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28307. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28308. };
  28309. return QuadraticMatrix;
  28310. })();
  28311. BABYLON.QuadraticMatrix = QuadraticMatrix;
  28312. var Reference = (function () {
  28313. function Reference(vertexId, triangleId) {
  28314. this.vertexId = vertexId;
  28315. this.triangleId = triangleId;
  28316. }
  28317. return Reference;
  28318. })();
  28319. BABYLON.Reference = Reference;
  28320. /**
  28321. * An implementation of the Quadratic Error simplification algorithm.
  28322. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  28323. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  28324. * @author RaananW
  28325. */
  28326. var QuadraticErrorSimplification = (function () {
  28327. function QuadraticErrorSimplification(_mesh) {
  28328. this._mesh = _mesh;
  28329. this.initialised = false;
  28330. this.syncIterations = 5000;
  28331. this.aggressiveness = 7;
  28332. this.decimationIterations = 100;
  28333. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  28334. }
  28335. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  28336. var _this = this;
  28337. this.initDecimatedMesh();
  28338. //iterating through the submeshes array, one after the other.
  28339. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  28340. _this.initWithMesh(_this._mesh, loop.index, function () {
  28341. _this.runDecimation(settings, loop.index, function () {
  28342. loop.executeNext();
  28343. });
  28344. });
  28345. }, function () {
  28346. setTimeout(function () {
  28347. successCallback(_this._reconstructedMesh);
  28348. }, 0);
  28349. });
  28350. };
  28351. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  28352. var _this = this;
  28353. var gCount = 0;
  28354. triangle.vertices.forEach(function (vId) {
  28355. var count = 0;
  28356. var vPos = _this.vertices[vId].position;
  28357. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  28358. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  28359. ++count;
  28360. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  28361. ++count;
  28362. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  28363. ++count;
  28364. if (count > 1) {
  28365. ++gCount;
  28366. }
  28367. ;
  28368. });
  28369. if (gCount > 1) {
  28370. console.log(triangle, gCount);
  28371. }
  28372. return gCount > 1;
  28373. };
  28374. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  28375. var _this = this;
  28376. var targetCount = ~~(this.triangles.length * settings.quality);
  28377. var deletedTriangles = 0;
  28378. var triangleCount = this.triangles.length;
  28379. var iterationFunction = function (iteration, callback) {
  28380. setTimeout(function () {
  28381. if (iteration % 5 === 0) {
  28382. _this.updateMesh(iteration === 0);
  28383. }
  28384. for (var i = 0; i < _this.triangles.length; ++i) {
  28385. _this.triangles[i].isDirty = false;
  28386. }
  28387. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  28388. var trianglesIterator = function (i) {
  28389. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  28390. var t = _this.triangles[tIdx];
  28391. if (!t)
  28392. return;
  28393. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  28394. return;
  28395. }
  28396. for (var j = 0; j < 3; ++j) {
  28397. if (t.error[j] < threshold) {
  28398. var deleted0 = [];
  28399. var deleted1 = [];
  28400. var i0 = t.vertices[j];
  28401. var i1 = t.vertices[(j + 1) % 3];
  28402. var v0 = _this.vertices[i0];
  28403. var v1 = _this.vertices[i1];
  28404. if (v0.isBorder !== v1.isBorder)
  28405. continue;
  28406. var p = BABYLON.Vector3.Zero();
  28407. var n = BABYLON.Vector3.Zero();
  28408. var uv = BABYLON.Vector2.Zero();
  28409. var color = new BABYLON.Color4(0, 0, 0, 1);
  28410. _this.calculateError(v0, v1, p, n, uv, color);
  28411. var delTr = [];
  28412. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  28413. continue;
  28414. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  28415. continue;
  28416. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  28417. continue;
  28418. var uniqueArray = [];
  28419. delTr.forEach(function (deletedT) {
  28420. if (uniqueArray.indexOf(deletedT) === -1) {
  28421. deletedT.deletePending = true;
  28422. uniqueArray.push(deletedT);
  28423. }
  28424. });
  28425. if (uniqueArray.length % 2 != 0) {
  28426. continue;
  28427. }
  28428. v0.normal = n;
  28429. if (v0.uv)
  28430. v0.uv = uv;
  28431. else if (v0.color)
  28432. v0.color = color;
  28433. v0.q = v1.q.add(v0.q);
  28434. v0.position = p;
  28435. var tStart = _this.references.length;
  28436. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  28437. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  28438. var tCount = _this.references.length - tStart;
  28439. if (tCount <= v0.triangleCount) {
  28440. if (tCount) {
  28441. for (var c = 0; c < tCount; c++) {
  28442. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  28443. }
  28444. }
  28445. }
  28446. else {
  28447. v0.triangleStart = tStart;
  28448. }
  28449. v0.triangleCount = tCount;
  28450. break;
  28451. }
  28452. }
  28453. };
  28454. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  28455. return (triangleCount - deletedTriangles <= targetCount);
  28456. });
  28457. }, 0);
  28458. };
  28459. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  28460. if (triangleCount - deletedTriangles <= targetCount)
  28461. loop.breakLoop();
  28462. else {
  28463. iterationFunction(loop.index, function () {
  28464. loop.executeNext();
  28465. });
  28466. }
  28467. }, function () {
  28468. setTimeout(function () {
  28469. //reconstruct this part of the mesh
  28470. _this.reconstructMesh(submeshIndex);
  28471. successCallback();
  28472. }, 0);
  28473. });
  28474. };
  28475. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, submeshIndex, callback) {
  28476. var _this = this;
  28477. if (!mesh)
  28478. return;
  28479. this.vertices = [];
  28480. this.triangles = [];
  28481. this._mesh = mesh;
  28482. //It is assumed that a mesh has positions, normals and either uvs or colors.
  28483. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28484. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28485. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28486. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28487. var indices = mesh.getIndices();
  28488. var submesh = mesh.subMeshes[submeshIndex];
  28489. var vertexInit = function (i) {
  28490. var offset = i + submesh.verticesStart;
  28491. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, offset * 3), BABYLON.Vector3.FromArray(normalData, offset * 3), null, i);
  28492. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28493. vertex.uv = BABYLON.Vector2.FromArray(uvs, offset * 2);
  28494. }
  28495. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28496. vertex.color = BABYLON.Color4.FromArray(colorsData, offset * 4);
  28497. }
  28498. _this.vertices.push(vertex);
  28499. };
  28500. //var totalVertices = mesh.getTotalVertices();
  28501. var totalVertices = submesh.verticesCount;
  28502. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  28503. var indicesInit = function (i) {
  28504. var offset = (submesh.indexStart / 3) + i;
  28505. var pos = (offset * 3);
  28506. var i0 = indices[pos + 0] - submesh.verticesStart;
  28507. var i1 = indices[pos + 1] - submesh.verticesStart;
  28508. var i2 = indices[pos + 2] - submesh.verticesStart;
  28509. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  28510. _this.triangles.push(triangle);
  28511. };
  28512. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  28513. _this.init(callback);
  28514. });
  28515. });
  28516. };
  28517. QuadraticErrorSimplification.prototype.init = function (callback) {
  28518. var _this = this;
  28519. var triangleInit1 = function (i) {
  28520. var t = _this.triangles[i];
  28521. t.normal = BABYLON.Vector3.Cross(_this.vertices[t.vertices[1]].position.subtract(_this.vertices[t.vertices[0]].position), _this.vertices[t.vertices[2]].position.subtract(_this.vertices[t.vertices[0]].position)).normalize();
  28522. for (var j = 0; j < 3; j++) {
  28523. _this.vertices[t.vertices[j]].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, _this.vertices[t.vertices[0]].position))));
  28524. }
  28525. };
  28526. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  28527. var triangleInit2 = function (i) {
  28528. var t = _this.triangles[i];
  28529. for (var j = 0; j < 3; ++j) {
  28530. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  28531. }
  28532. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28533. };
  28534. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  28535. _this.initialised = true;
  28536. callback();
  28537. });
  28538. });
  28539. };
  28540. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  28541. var newTriangles = [];
  28542. var i;
  28543. for (i = 0; i < this.vertices.length; ++i) {
  28544. this.vertices[i].triangleCount = 0;
  28545. }
  28546. var t;
  28547. var j;
  28548. for (i = 0; i < this.triangles.length; ++i) {
  28549. if (!this.triangles[i].deleted) {
  28550. t = this.triangles[i];
  28551. for (j = 0; j < 3; ++j) {
  28552. this.vertices[t.vertices[j]].triangleCount = 1;
  28553. }
  28554. newTriangles.push(t);
  28555. }
  28556. }
  28557. var newVerticesOrder = [];
  28558. //compact vertices, get the IDs of the vertices used.
  28559. var dst = 0;
  28560. for (i = 0; i < this.vertices.length; ++i) {
  28561. if (this.vertices[i].triangleCount) {
  28562. this.vertices[i].triangleStart = dst;
  28563. this.vertices[dst].position = this.vertices[i].position;
  28564. this.vertices[dst].normal = this.vertices[i].normal;
  28565. this.vertices[dst].uv = this.vertices[i].uv;
  28566. this.vertices[dst].color = this.vertices[i].color;
  28567. newVerticesOrder.push(dst);
  28568. dst++;
  28569. }
  28570. }
  28571. for (i = 0; i < newTriangles.length; ++i) {
  28572. t = newTriangles[i];
  28573. for (j = 0; j < 3; ++j) {
  28574. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  28575. }
  28576. }
  28577. this.vertices = this.vertices.slice(0, dst);
  28578. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  28579. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  28580. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  28581. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  28582. for (i = 0; i < newVerticesOrder.length; ++i) {
  28583. newPositionData.push(this.vertices[i].position.x);
  28584. newPositionData.push(this.vertices[i].position.y);
  28585. newPositionData.push(this.vertices[i].position.z);
  28586. newNormalData.push(this.vertices[i].normal.x);
  28587. newNormalData.push(this.vertices[i].normal.y);
  28588. newNormalData.push(this.vertices[i].normal.z);
  28589. if (this.vertices[i].uv) {
  28590. newUVsData.push(this.vertices[i].uv.x);
  28591. newUVsData.push(this.vertices[i].uv.y);
  28592. }
  28593. else if (this.vertices[i].color) {
  28594. newColorsData.push(this.vertices[i].color.r);
  28595. newColorsData.push(this.vertices[i].color.g);
  28596. newColorsData.push(this.vertices[i].color.b);
  28597. newColorsData.push(this.vertices[i].color.a);
  28598. }
  28599. }
  28600. var startingIndex = this._reconstructedMesh.getTotalIndices();
  28601. var startingVertex = this._reconstructedMesh.getTotalVertices();
  28602. var submeshesArray = this._reconstructedMesh.subMeshes;
  28603. this._reconstructedMesh.subMeshes = [];
  28604. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  28605. for (i = 0; i < newTriangles.length; ++i) {
  28606. newIndicesArray.push(newTriangles[i].vertices[0] + startingVertex);
  28607. newIndicesArray.push(newTriangles[i].vertices[1] + startingVertex);
  28608. newIndicesArray.push(newTriangles[i].vertices[2] + startingVertex);
  28609. }
  28610. //overwriting the old vertex buffers and indices.
  28611. this._reconstructedMesh.setIndices(newIndicesArray);
  28612. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  28613. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  28614. if (newUVsData.length > 0)
  28615. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  28616. if (newColorsData.length > 0)
  28617. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  28618. //create submesh
  28619. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  28620. if (submeshIndex > 0) {
  28621. this._reconstructedMesh.subMeshes = [];
  28622. submeshesArray.forEach(function (submesh) {
  28623. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  28624. });
  28625. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, newVerticesOrder.length, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  28626. }
  28627. };
  28628. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  28629. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  28630. this._reconstructedMesh.material = this._mesh.material;
  28631. this._reconstructedMesh.parent = this._mesh.parent;
  28632. this._reconstructedMesh.isVisible = false;
  28633. };
  28634. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  28635. for (var i = 0; i < vertex1.triangleCount; ++i) {
  28636. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  28637. if (t.deleted)
  28638. continue;
  28639. var s = this.references[vertex1.triangleStart + i].vertexId;
  28640. var id1 = t.vertices[(s + 1) % 3];
  28641. var id2 = t.vertices[(s + 2) % 3];
  28642. if ((id1 === index2 || id2 === index2)) {
  28643. deletedArray[i] = true;
  28644. delTr.push(t);
  28645. continue;
  28646. }
  28647. var d1 = this.vertices[id1].position.subtract(point);
  28648. d1 = d1.normalize();
  28649. var d2 = this.vertices[id2].position.subtract(point);
  28650. d2 = d2.normalize();
  28651. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  28652. return true;
  28653. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  28654. deletedArray[i] = false;
  28655. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  28656. return true;
  28657. }
  28658. return false;
  28659. };
  28660. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  28661. var newDeleted = deletedTriangles;
  28662. for (var i = 0; i < vertex.triangleCount; ++i) {
  28663. var ref = this.references[vertex.triangleStart + i];
  28664. var t = this.triangles[ref.triangleId];
  28665. if (t.deleted)
  28666. continue;
  28667. if (deletedArray[i] && t.deletePending) {
  28668. t.deleted = true;
  28669. newDeleted++;
  28670. continue;
  28671. }
  28672. t.vertices[ref.vertexId] = vertexId;
  28673. t.isDirty = true;
  28674. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  28675. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  28676. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  28677. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28678. this.references.push(ref);
  28679. }
  28680. return newDeleted;
  28681. };
  28682. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  28683. for (var i = 0; i < this.vertices.length; ++i) {
  28684. var vCount = [];
  28685. var vId = [];
  28686. var v = this.vertices[i];
  28687. var j;
  28688. for (j = 0; j < v.triangleCount; ++j) {
  28689. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  28690. for (var ii = 0; ii < 3; ii++) {
  28691. var ofs = 0;
  28692. var id = triangle.vertices[ii];
  28693. while (ofs < vCount.length) {
  28694. if (vId[ofs] === id)
  28695. break;
  28696. ++ofs;
  28697. }
  28698. if (ofs === vCount.length) {
  28699. vCount.push(1);
  28700. vId.push(id);
  28701. }
  28702. else {
  28703. vCount[ofs]++;
  28704. }
  28705. }
  28706. }
  28707. for (j = 0; j < vCount.length; ++j) {
  28708. if (vCount[j] === 1) {
  28709. this.vertices[vId[j]].isBorder = true;
  28710. }
  28711. else {
  28712. this.vertices[vId[j]].isBorder = false;
  28713. }
  28714. }
  28715. }
  28716. };
  28717. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  28718. if (identifyBorders === void 0) { identifyBorders = false; }
  28719. var i;
  28720. if (!identifyBorders) {
  28721. var newTrianglesVector = [];
  28722. for (i = 0; i < this.triangles.length; ++i) {
  28723. if (!this.triangles[i].deleted) {
  28724. newTrianglesVector.push(this.triangles[i]);
  28725. }
  28726. }
  28727. this.triangles = newTrianglesVector;
  28728. }
  28729. for (i = 0; i < this.vertices.length; ++i) {
  28730. this.vertices[i].triangleCount = 0;
  28731. this.vertices[i].triangleStart = 0;
  28732. }
  28733. var t;
  28734. var j;
  28735. var v;
  28736. for (i = 0; i < this.triangles.length; ++i) {
  28737. t = this.triangles[i];
  28738. for (j = 0; j < 3; ++j) {
  28739. v = this.vertices[t.vertices[j]];
  28740. v.triangleCount++;
  28741. }
  28742. }
  28743. var tStart = 0;
  28744. for (i = 0; i < this.vertices.length; ++i) {
  28745. this.vertices[i].triangleStart = tStart;
  28746. tStart += this.vertices[i].triangleCount;
  28747. this.vertices[i].triangleCount = 0;
  28748. }
  28749. var newReferences = new Array(this.triangles.length * 3);
  28750. for (i = 0; i < this.triangles.length; ++i) {
  28751. t = this.triangles[i];
  28752. for (j = 0; j < 3; ++j) {
  28753. v = this.vertices[t.vertices[j]];
  28754. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  28755. v.triangleCount++;
  28756. }
  28757. }
  28758. this.references = newReferences;
  28759. if (identifyBorders) {
  28760. this.identifyBorder();
  28761. }
  28762. };
  28763. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  28764. var x = point.x;
  28765. var y = point.y;
  28766. var z = point.z;
  28767. 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];
  28768. };
  28769. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  28770. var q = vertex1.q.add(vertex2.q);
  28771. var border = vertex1.isBorder && vertex2.isBorder;
  28772. var error = 0;
  28773. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  28774. if (qDet !== 0 && !border) {
  28775. if (!pointResult) {
  28776. pointResult = BABYLON.Vector3.Zero();
  28777. }
  28778. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  28779. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  28780. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  28781. error = this.vertexError(q, pointResult);
  28782. //TODO this should be correctly calculated
  28783. if (normalResult) {
  28784. normalResult.copyFrom(vertex1.normal);
  28785. if (vertex1.uv)
  28786. uvResult.copyFrom(vertex1.uv);
  28787. else if (vertex1.color)
  28788. colorResult.copyFrom(vertex1.color);
  28789. }
  28790. }
  28791. else {
  28792. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  28793. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  28794. var error1 = this.vertexError(q, vertex1.position);
  28795. var error2 = this.vertexError(q, vertex2.position);
  28796. var error3 = this.vertexError(q, p3);
  28797. error = Math.min(error1, error2, error3);
  28798. if (error === error1) {
  28799. if (pointResult) {
  28800. pointResult.copyFrom(vertex1.position);
  28801. normalResult.copyFrom(vertex1.normal);
  28802. if (vertex1.uv)
  28803. uvResult.copyFrom(vertex1.uv);
  28804. else if (vertex1.color)
  28805. colorResult.copyFrom(vertex1.color);
  28806. }
  28807. }
  28808. else if (error === error2) {
  28809. if (pointResult) {
  28810. pointResult.copyFrom(vertex2.position);
  28811. normalResult.copyFrom(vertex2.normal);
  28812. if (vertex2.uv)
  28813. uvResult.copyFrom(vertex2.uv);
  28814. else if (vertex2.color)
  28815. colorResult.copyFrom(vertex2.color);
  28816. }
  28817. }
  28818. else {
  28819. if (pointResult) {
  28820. pointResult.copyFrom(p3);
  28821. normalResult.copyFrom(vertex1.normal);
  28822. if (vertex1.uv)
  28823. uvResult.copyFrom(vertex1.uv);
  28824. else if (vertex1.color)
  28825. colorResult.copyFrom(vertex1.color);
  28826. }
  28827. }
  28828. }
  28829. return error;
  28830. };
  28831. return QuadraticErrorSimplification;
  28832. })();
  28833. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  28834. })(BABYLON || (BABYLON = {}));
  28835. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  28836. (function (BABYLON) {
  28837. var Analyser = (function () {
  28838. function Analyser(scene) {
  28839. this.SMOOTHING = 0.75;
  28840. this.FFT_SIZE = 512;
  28841. this.BARGRAPHAMPLITUDE = 256;
  28842. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  28843. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  28844. this._scene = scene;
  28845. this._audioEngine = BABYLON.Engine.audioEngine;
  28846. if (this._audioEngine.canUseWebAudio) {
  28847. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  28848. this._webAudioAnalyser.minDecibels = -140;
  28849. this._webAudioAnalyser.maxDecibels = 0;
  28850. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28851. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28852. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  28853. }
  28854. }
  28855. Analyser.prototype.getFrequencyBinCount = function () {
  28856. if (this._audioEngine.canUseWebAudio) {
  28857. return this._webAudioAnalyser.frequencyBinCount;
  28858. }
  28859. else {
  28860. return 0;
  28861. }
  28862. };
  28863. Analyser.prototype.getByteFrequencyData = function () {
  28864. if (this._audioEngine.canUseWebAudio) {
  28865. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28866. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28867. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  28868. }
  28869. return this._byteFreqs;
  28870. };
  28871. Analyser.prototype.getByteTimeDomainData = function () {
  28872. if (this._audioEngine.canUseWebAudio) {
  28873. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28874. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28875. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  28876. }
  28877. return this._byteTime;
  28878. };
  28879. Analyser.prototype.getFloatFrequencyData = function () {
  28880. if (this._audioEngine.canUseWebAudio) {
  28881. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28882. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28883. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  28884. }
  28885. return this._floatFreqs;
  28886. };
  28887. Analyser.prototype.drawDebugCanvas = function () {
  28888. var _this = this;
  28889. if (this._audioEngine.canUseWebAudio) {
  28890. if (!this._debugCanvas) {
  28891. this._debugCanvas = document.createElement("canvas");
  28892. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  28893. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  28894. this._debugCanvas.style.position = "absolute";
  28895. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  28896. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  28897. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  28898. document.body.appendChild(this._debugCanvas);
  28899. this._registerFunc = function () {
  28900. _this.drawDebugCanvas();
  28901. };
  28902. this._scene.registerBeforeRender(this._registerFunc);
  28903. }
  28904. if (this._registerFunc) {
  28905. var workingArray = this.getByteFrequencyData();
  28906. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  28907. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  28908. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  28909. var value = workingArray[i];
  28910. var percent = value / this.BARGRAPHAMPLITUDE;
  28911. var height = this.DEBUGCANVASSIZE.height * percent;
  28912. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  28913. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  28914. var hue = i / this.getFrequencyBinCount() * 360;
  28915. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  28916. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  28917. }
  28918. }
  28919. }
  28920. };
  28921. Analyser.prototype.stopDebugCanvas = function () {
  28922. if (this._debugCanvas) {
  28923. this._scene.unregisterBeforeRender(this._registerFunc);
  28924. this._registerFunc = null;
  28925. document.body.removeChild(this._debugCanvas);
  28926. this._debugCanvas = null;
  28927. this._debugCanvasContext = null;
  28928. }
  28929. };
  28930. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  28931. if (this._audioEngine.canUseWebAudio) {
  28932. inputAudioNode.connect(this._webAudioAnalyser);
  28933. this._webAudioAnalyser.connect(outputAudioNode);
  28934. }
  28935. };
  28936. Analyser.prototype.dispose = function () {
  28937. if (this._audioEngine.canUseWebAudio) {
  28938. this._webAudioAnalyser.disconnect();
  28939. }
  28940. };
  28941. return Analyser;
  28942. })();
  28943. BABYLON.Analyser = Analyser;
  28944. })(BABYLON || (BABYLON = {}));
  28945. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  28946. (function (BABYLON) {
  28947. var DepthRenderer = (function () {
  28948. function DepthRenderer(scene, type) {
  28949. var _this = this;
  28950. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  28951. this._viewMatrix = BABYLON.Matrix.Zero();
  28952. this._projectionMatrix = BABYLON.Matrix.Zero();
  28953. this._transformMatrix = BABYLON.Matrix.Zero();
  28954. this._worldViewProjection = BABYLON.Matrix.Zero();
  28955. this._scene = scene;
  28956. var engine = scene.getEngine();
  28957. // Render target
  28958. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  28959. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28960. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28961. this._depthMap.refreshRate = 1;
  28962. this._depthMap.renderParticles = false;
  28963. this._depthMap.renderList = null;
  28964. // Custom render function
  28965. var renderSubMesh = function (subMesh) {
  28966. var mesh = subMesh.getRenderingMesh();
  28967. var scene = _this._scene;
  28968. var engine = scene.getEngine();
  28969. // Culling
  28970. engine.setState(subMesh.getMaterial().backFaceCulling);
  28971. // Managing instances
  28972. var batch = mesh._getInstancesRenderList(subMesh._id);
  28973. if (batch.mustReturn) {
  28974. return;
  28975. }
  28976. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  28977. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  28978. engine.enableEffect(_this._effect);
  28979. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  28980. var material = subMesh.getMaterial();
  28981. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  28982. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  28983. // Alpha test
  28984. if (material && material.needAlphaTesting()) {
  28985. var alphaTexture = material.getAlphaTestTexture();
  28986. _this._effect.setTexture("diffuseSampler", alphaTexture);
  28987. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28988. }
  28989. // Bones
  28990. if (mesh.useBones) {
  28991. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28992. }
  28993. // Draw
  28994. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  28995. }
  28996. };
  28997. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  28998. var index;
  28999. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29000. renderSubMesh(opaqueSubMeshes.data[index]);
  29001. }
  29002. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29003. renderSubMesh(alphaTestSubMeshes.data[index]);
  29004. }
  29005. };
  29006. }
  29007. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  29008. var defines = [];
  29009. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29010. var mesh = subMesh.getMesh();
  29011. var scene = mesh.getScene();
  29012. var material = subMesh.getMaterial();
  29013. // Alpha test
  29014. if (material && material.needAlphaTesting()) {
  29015. defines.push("#define ALPHATEST");
  29016. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29017. attribs.push(BABYLON.VertexBuffer.UVKind);
  29018. defines.push("#define UV1");
  29019. }
  29020. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29021. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29022. defines.push("#define UV2");
  29023. }
  29024. }
  29025. // Bones
  29026. if (mesh.useBones) {
  29027. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29028. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29029. defines.push("#define BONES");
  29030. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29031. }
  29032. // Instances
  29033. if (useInstances) {
  29034. defines.push("#define INSTANCES");
  29035. attribs.push("world0");
  29036. attribs.push("world1");
  29037. attribs.push("world2");
  29038. attribs.push("world3");
  29039. }
  29040. // Get correct effect
  29041. var join = defines.join("\n");
  29042. if (this._cachedDefines !== join) {
  29043. this._cachedDefines = join;
  29044. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  29045. }
  29046. return this._effect.isReady();
  29047. };
  29048. DepthRenderer.prototype.getDepthMap = function () {
  29049. return this._depthMap;
  29050. };
  29051. // Methods
  29052. DepthRenderer.prototype.dispose = function () {
  29053. this._depthMap.dispose();
  29054. };
  29055. return DepthRenderer;
  29056. })();
  29057. BABYLON.DepthRenderer = DepthRenderer;
  29058. })(BABYLON || (BABYLON = {}));
  29059. //# sourceMappingURL=babylon.depthRenderer.js.map
  29060. var BABYLON;
  29061. (function (BABYLON) {
  29062. var SSAORenderingPipeline = (function (_super) {
  29063. __extends(SSAORenderingPipeline, _super);
  29064. /**
  29065. * @constructor
  29066. * @param {string} name - The rendering pipeline name
  29067. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29068. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  29069. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29070. */
  29071. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  29072. var _this = this;
  29073. _super.call(this, scene.getEngine(), name);
  29074. // Members
  29075. /**
  29076. * The PassPostProcess id in the pipeline that contains the original scene color
  29077. * @type {string}
  29078. */
  29079. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  29080. /**
  29081. * The SSAO PostProcess id in the pipeline
  29082. * @type {string}
  29083. */
  29084. this.SSAORenderEffect = "SSAORenderEffect";
  29085. /**
  29086. * The horizontal blur PostProcess id in the pipeline
  29087. * @type {string}
  29088. */
  29089. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  29090. /**
  29091. * The vertical blur PostProcess id in the pipeline
  29092. * @type {string}
  29093. */
  29094. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  29095. /**
  29096. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  29097. * @type {string}
  29098. */
  29099. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  29100. this._firstUpdate = true;
  29101. this._scene = scene;
  29102. // Set up assets
  29103. this._createRandomTexture();
  29104. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29105. var ssaoRatio = ratio.ssaoRatio || ratio;
  29106. var combineRatio = ratio.combineRatio || ratio;
  29107. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29108. this._createSSAOPostProcess(ssaoRatio);
  29109. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29110. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29111. this._createSSAOCombinePostProcess(combineRatio);
  29112. // Set up pipeline
  29113. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  29114. return _this._originalColorPostProcess;
  29115. }, true));
  29116. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  29117. return _this._ssaoPostProcess;
  29118. }, true));
  29119. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  29120. return _this._blurHPostProcess;
  29121. }, true));
  29122. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  29123. return _this._blurVPostProcess;
  29124. }, true));
  29125. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  29126. return _this._ssaoCombinePostProcess;
  29127. }, true));
  29128. // Finish
  29129. scene.postProcessRenderPipelineManager.addPipeline(this);
  29130. if (cameras)
  29131. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29132. }
  29133. // Public Methods
  29134. /**
  29135. * Returns the horizontal blur PostProcess
  29136. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  29137. */
  29138. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  29139. return this._blurHPostProcess;
  29140. };
  29141. /**
  29142. * Returns the vertical blur PostProcess
  29143. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  29144. */
  29145. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  29146. return this._blurVPostProcess;
  29147. };
  29148. /**
  29149. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  29150. */
  29151. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29152. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29153. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29154. this._originalColorPostProcess = undefined;
  29155. this._ssaoPostProcess = undefined;
  29156. this._blurHPostProcess = undefined;
  29157. this._blurVPostProcess = undefined;
  29158. this._ssaoCombinePostProcess = undefined;
  29159. this._randomTexture.dispose();
  29160. if (disableDepthRender)
  29161. this._scene.disableDepthRenderer();
  29162. };
  29163. // Private Methods
  29164. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  29165. var _this = this;
  29166. var sampleSphere = [
  29167. 0.5381,
  29168. 0.1856,
  29169. -0.4319,
  29170. 0.1379,
  29171. 0.2486,
  29172. 0.4430,
  29173. 0.3371,
  29174. 0.5679,
  29175. -0.0057,
  29176. -0.6999,
  29177. -0.0451,
  29178. -0.0019,
  29179. 0.0689,
  29180. -0.1598,
  29181. -0.8547,
  29182. 0.0560,
  29183. 0.0069,
  29184. -0.1843,
  29185. -0.0146,
  29186. 0.1402,
  29187. 0.0762,
  29188. 0.0100,
  29189. -0.1924,
  29190. -0.0344,
  29191. -0.3577,
  29192. -0.5301,
  29193. -0.4358,
  29194. -0.3169,
  29195. 0.1063,
  29196. 0.0158,
  29197. 0.0103,
  29198. -0.5869,
  29199. 0.0046,
  29200. -0.0897,
  29201. -0.4940,
  29202. 0.3287,
  29203. 0.7119,
  29204. -0.0154,
  29205. -0.0918,
  29206. -0.0533,
  29207. 0.0596,
  29208. -0.5411,
  29209. 0.0352,
  29210. -0.0631,
  29211. 0.5460,
  29212. -0.4776,
  29213. 0.2847,
  29214. -0.0271
  29215. ];
  29216. var samplesFactor = 1.0 / 16.0;
  29217. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29218. this._ssaoPostProcess.onApply = function (effect) {
  29219. if (_this._firstUpdate) {
  29220. effect.setArray3("sampleSphere", sampleSphere);
  29221. effect.setFloat("samplesFactor", samplesFactor);
  29222. effect.setFloat("randTextureTiles", 4.0 / ratio);
  29223. _this._firstUpdate = false;
  29224. }
  29225. effect.setTexture("textureSampler", _this._depthTexture);
  29226. effect.setTexture("randomSampler", _this._randomTexture);
  29227. };
  29228. };
  29229. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  29230. var _this = this;
  29231. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29232. this._ssaoCombinePostProcess.onApply = function (effect) {
  29233. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  29234. };
  29235. };
  29236. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  29237. var size = 512;
  29238. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29239. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29240. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29241. var context = this._randomTexture.getContext();
  29242. var rand = function (min, max) {
  29243. return Math.random() * (max - min) + min;
  29244. };
  29245. for (var x = 0; x < size; x++) {
  29246. for (var y = 0; y < size; y++) {
  29247. var randVector = BABYLON.Vector3.Zero();
  29248. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  29249. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  29250. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  29251. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  29252. context.fillRect(x, y, 1, 1);
  29253. }
  29254. }
  29255. this._randomTexture.update(false);
  29256. };
  29257. return SSAORenderingPipeline;
  29258. })(BABYLON.PostProcessRenderPipeline);
  29259. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  29260. })(BABYLON || (BABYLON = {}));
  29261. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  29262. var BABYLON;
  29263. (function (BABYLON) {
  29264. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  29265. var VolumetricLightScatteringPostProcess = (function (_super) {
  29266. __extends(VolumetricLightScatteringPostProcess, _super);
  29267. /**
  29268. * @constructor
  29269. * @param {string} name - The post-process name
  29270. * @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)
  29271. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  29272. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  29273. * @param {number} samples - The post-process quality, default 100
  29274. * @param {number} samplingMode - The post-process filtering mode
  29275. * @param {BABYLON.Engine} engine - The babylon engine
  29276. * @param {boolean} reusable - If the post-process is reusable
  29277. */
  29278. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  29279. var _this = this;
  29280. if (samples === void 0) { samples = 100; }
  29281. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  29282. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  29283. this._screenCoordinates = BABYLON.Vector2.Zero();
  29284. /**
  29285. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  29286. * @type {boolean}
  29287. */
  29288. this.useCustomMeshPosition = false;
  29289. /**
  29290. * If the post-process should inverse the light scattering direction
  29291. * @type {boolean}
  29292. */
  29293. this.invert = true;
  29294. /**
  29295. * Array containing the excluded meshes not rendered in the internal pass
  29296. */
  29297. this.excludedMeshes = new Array();
  29298. this.exposure = 0.3;
  29299. this.decay = 0.96815;
  29300. this.weight = 0.58767;
  29301. this.density = 0.926;
  29302. var scene = camera.getScene();
  29303. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  29304. // Configure mesh
  29305. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  29306. // Configure
  29307. this._createPass(scene, ratio.passRatio || ratio);
  29308. this.onApply = function (effect) {
  29309. _this._updateMeshScreenCoordinates(scene);
  29310. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  29311. effect.setFloat("exposure", _this.exposure);
  29312. effect.setFloat("decay", _this.decay);
  29313. effect.setFloat("weight", _this.weight);
  29314. effect.setFloat("density", _this.density);
  29315. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  29316. };
  29317. }
  29318. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  29319. var mesh = subMesh.getMesh();
  29320. var defines = [];
  29321. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29322. var material = subMesh.getMaterial();
  29323. var needUV = false;
  29324. // Render this.mesh as default
  29325. if (mesh === this.mesh) {
  29326. defines.push("#define BASIC_RENDER");
  29327. defines.push("#define NEED_UV");
  29328. needUV = true;
  29329. }
  29330. // Alpha test
  29331. if (material) {
  29332. if (material.needAlphaTesting() || mesh === this.mesh)
  29333. defines.push("#define ALPHATEST");
  29334. if (material.opacityTexture !== undefined) {
  29335. defines.push("#define OPACITY");
  29336. if (material.opacityTexture.getAlphaFromRGB)
  29337. defines.push("#define OPACITYRGB");
  29338. if (!needUV)
  29339. defines.push("#define NEED_UV");
  29340. }
  29341. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29342. attribs.push(BABYLON.VertexBuffer.UVKind);
  29343. defines.push("#define UV1");
  29344. }
  29345. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29346. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29347. defines.push("#define UV2");
  29348. }
  29349. }
  29350. // Bones
  29351. if (mesh.useBones) {
  29352. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29353. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29354. defines.push("#define BONES");
  29355. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29356. }
  29357. // Instances
  29358. if (useInstances) {
  29359. defines.push("#define INSTANCES");
  29360. attribs.push("world0");
  29361. attribs.push("world1");
  29362. attribs.push("world2");
  29363. attribs.push("world3");
  29364. }
  29365. // Get correct effect
  29366. var join = defines.join("\n");
  29367. if (this._cachedDefines !== join) {
  29368. this._cachedDefines = join;
  29369. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  29370. }
  29371. return this._volumetricLightScatteringPass.isReady();
  29372. };
  29373. /**
  29374. * Sets the new light position for light scattering effect
  29375. * @param {BABYLON.Vector3} The new custom light position
  29376. */
  29377. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  29378. this._customMeshPosition = position;
  29379. };
  29380. /**
  29381. * Returns the light position for light scattering effect
  29382. * @return {BABYLON.Vector3} The custom light position
  29383. */
  29384. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  29385. return this._customMeshPosition;
  29386. };
  29387. /**
  29388. * Disposes the internal assets and detaches the post-process from the camera
  29389. */
  29390. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  29391. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  29392. if (rttIndex !== -1) {
  29393. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  29394. }
  29395. this._volumetricLightScatteringRTT.dispose();
  29396. _super.prototype.dispose.call(this, camera);
  29397. };
  29398. /**
  29399. * Returns the render target texture used by the post-process
  29400. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  29401. */
  29402. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  29403. return this._volumetricLightScatteringRTT;
  29404. };
  29405. // Private methods
  29406. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  29407. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  29408. return true;
  29409. }
  29410. return false;
  29411. };
  29412. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  29413. var _this = this;
  29414. var engine = scene.getEngine();
  29415. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  29416. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29417. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29418. this._volumetricLightScatteringRTT.renderList = null;
  29419. this._volumetricLightScatteringRTT.renderParticles = false;
  29420. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  29421. // Custom render function for submeshes
  29422. var renderSubMesh = function (subMesh) {
  29423. var mesh = subMesh.getRenderingMesh();
  29424. if (_this._meshExcluded(mesh)) {
  29425. return;
  29426. }
  29427. var scene = mesh.getScene();
  29428. var engine = scene.getEngine();
  29429. // Culling
  29430. engine.setState(subMesh.getMaterial().backFaceCulling);
  29431. // Managing instances
  29432. var batch = mesh._getInstancesRenderList(subMesh._id);
  29433. if (batch.mustReturn) {
  29434. return;
  29435. }
  29436. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29437. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29438. engine.enableEffect(_this._volumetricLightScatteringPass);
  29439. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  29440. var material = subMesh.getMaterial();
  29441. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  29442. // Alpha test
  29443. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  29444. var alphaTexture = material.getAlphaTestTexture();
  29445. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  29446. if (alphaTexture) {
  29447. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29448. }
  29449. if (material.opacityTexture !== undefined) {
  29450. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  29451. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  29452. }
  29453. }
  29454. // Bones
  29455. if (mesh.useBones) {
  29456. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29457. }
  29458. // Draw
  29459. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  29460. }
  29461. };
  29462. // Render target texture callbacks
  29463. var savedSceneClearColor;
  29464. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  29465. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  29466. savedSceneClearColor = scene.clearColor;
  29467. scene.clearColor = sceneClearColor;
  29468. };
  29469. this._volumetricLightScatteringRTT.onAfterRender = function () {
  29470. scene.clearColor = savedSceneClearColor;
  29471. };
  29472. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  29473. var engine = scene.getEngine();
  29474. var index;
  29475. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29476. renderSubMesh(opaqueSubMeshes.data[index]);
  29477. }
  29478. engine.setAlphaTesting(true);
  29479. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29480. renderSubMesh(alphaTestSubMeshes.data[index]);
  29481. }
  29482. engine.setAlphaTesting(false);
  29483. if (transparentSubMeshes.length) {
  29484. for (index = 0; index < transparentSubMeshes.length; index++) {
  29485. var submesh = transparentSubMeshes.data[index];
  29486. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  29487. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  29488. }
  29489. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  29490. sortedArray.sort(function (a, b) {
  29491. // Alpha index first
  29492. if (a._alphaIndex > b._alphaIndex) {
  29493. return 1;
  29494. }
  29495. if (a._alphaIndex < b._alphaIndex) {
  29496. return -1;
  29497. }
  29498. // Then distance to camera
  29499. if (a._distanceToCamera < b._distanceToCamera) {
  29500. return 1;
  29501. }
  29502. if (a._distanceToCamera > b._distanceToCamera) {
  29503. return -1;
  29504. }
  29505. return 0;
  29506. });
  29507. // Render sub meshes
  29508. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29509. for (index = 0; index < sortedArray.length; index++) {
  29510. renderSubMesh(sortedArray[index]);
  29511. }
  29512. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29513. }
  29514. };
  29515. };
  29516. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  29517. var transform = scene.getTransformMatrix();
  29518. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  29519. this._screenCoordinates.x = pos.x / this._viewPort.width;
  29520. this._screenCoordinates.y = pos.y / this._viewPort.height;
  29521. if (this.invert)
  29522. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  29523. };
  29524. // Static methods
  29525. /**
  29526. * Creates a default mesh for the Volumeric Light Scattering post-process
  29527. * @param {string} The mesh name
  29528. * @param {BABYLON.Scene} The scene where to create the mesh
  29529. * @return {BABYLON.Mesh} the default mesh
  29530. */
  29531. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  29532. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  29533. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  29534. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  29535. return mesh;
  29536. };
  29537. return VolumetricLightScatteringPostProcess;
  29538. })(BABYLON.PostProcess);
  29539. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  29540. })(BABYLON || (BABYLON = {}));
  29541. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  29542. var BABYLON;
  29543. (function (BABYLON) {
  29544. var LensRenderingPipeline = (function (_super) {
  29545. __extends(LensRenderingPipeline, _super);
  29546. /**
  29547. * @constructor
  29548. * @param {string} name - The rendering pipeline name
  29549. * @param {object} parameters - An object containing all parameters (see below)
  29550. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29551. * @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)
  29552. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29553. Effect parameters are as follow:
  29554. {
  29555. chromatic_aberration: number; // from 0 to x (1 for realism)
  29556. edge_blur: number; // from 0 to x (1 for realism)
  29557. distortion: number; // from 0 to x (1 for realism)
  29558. grain_amount: number; // from 0 to 1
  29559. grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  29560. dof_focus_depth: number; // depth-of-field: focus depth; unset to disable
  29561. dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  29562. dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  29563. dof_gain: boolean; // depth-of-field: depthOfField gain (default: 1)
  29564. dof_threshold: boolean; // depth-of-field: depthOfField threshold (default: 1)
  29565. blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  29566. }
  29567. Note: if an effect parameter is unset, effect is disabled
  29568. */
  29569. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  29570. var _this = this;
  29571. if (ratio === void 0) { ratio = 1.0; }
  29572. _super.call(this, scene.getEngine(), name);
  29573. // Lens effects can be of the following:
  29574. // - chromatic aberration (slight shift of RGB colors)
  29575. // - blur on the edge of the lens
  29576. // - lens distortion
  29577. // - depth-of-field 'bokeh' effect (shapes appearing in blured areas, stronger highlights)
  29578. // - grain/dust-on-lens effect
  29579. // Two additional texture samplers are needed:
  29580. // - depth map (for depth-of-field)
  29581. // - grain texture
  29582. /**
  29583. * The chromatic aberration PostProcess id in the pipeline
  29584. * @type {string}
  29585. */
  29586. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  29587. /**
  29588. * The depth-of-field PostProcess id in the pipeline
  29589. * @type {string}
  29590. */
  29591. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  29592. this._scene = scene;
  29593. // Fetch texture samplers
  29594. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29595. if (parameters.grain_texture) {
  29596. this._grainTexture = parameters.grain_texture;
  29597. }
  29598. else {
  29599. this._createGrainTexture();
  29600. }
  29601. // save parameters
  29602. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  29603. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  29604. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  29605. this._distortion = parameters.distortion ? parameters.distortion : 0;
  29606. this._highlightsGain = parameters.dof_gain ? parameters.dof_gain : 1;
  29607. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  29608. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  29609. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  29610. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  29611. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  29612. // Create effects
  29613. this._createChromaticAberrationPostProcess(ratio);
  29614. this._createDepthOfFieldPostProcess(ratio);
  29615. // Set up pipeline
  29616. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  29617. return _this._chromaticAberrationPostProcess;
  29618. }, true));
  29619. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  29620. return _this._depthOfFieldPostProcess;
  29621. }, true));
  29622. // Finish
  29623. scene.postProcessRenderPipelineManager.addPipeline(this);
  29624. if (cameras) {
  29625. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29626. }
  29627. }
  29628. // public methods
  29629. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  29630. this._edgeBlur = amount;
  29631. };
  29632. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  29633. this._edgeBlur = 0;
  29634. };
  29635. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  29636. this._grainAmount = amount;
  29637. };
  29638. LensRenderingPipeline.prototype.disableGrain = function () {
  29639. this._grainAmount = 0;
  29640. };
  29641. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  29642. this._chromaticAberration = amount;
  29643. };
  29644. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  29645. this._chromaticAberration = 0;
  29646. };
  29647. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  29648. this._distortion = amount;
  29649. };
  29650. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  29651. this._distortion = 0;
  29652. };
  29653. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  29654. this._highlightsGain = amount;
  29655. };
  29656. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  29657. this._highlightsThreshold = amount;
  29658. };
  29659. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  29660. this._dofDepth = amount;
  29661. };
  29662. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  29663. this._dofDepth = -1;
  29664. };
  29665. LensRenderingPipeline.prototype.setAperture = function (amount) {
  29666. this._dofAperture = amount;
  29667. };
  29668. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  29669. this._dofPentagon = true;
  29670. };
  29671. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  29672. this._dofPentagon = false;
  29673. };
  29674. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  29675. this._blurNoise = true;
  29676. };
  29677. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  29678. this._blurNoise = false;
  29679. };
  29680. /**
  29681. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  29682. */
  29683. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29684. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29685. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29686. this._chromaticAberrationPostProcess = undefined;
  29687. this._depthOfFieldPostProcess = undefined;
  29688. this._grainTexture.dispose();
  29689. if (disableDepthRender)
  29690. this._scene.disableDepthRenderer();
  29691. };
  29692. // colors shifting and distortion
  29693. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  29694. var _this = this;
  29695. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29696. this._chromaticAberrationPostProcess.onApply = function (effect) {
  29697. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  29698. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  29699. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  29700. };
  29701. };
  29702. // colors shifting and distortion
  29703. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  29704. var _this = this;
  29705. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  29706. "gain",
  29707. "threshold",
  29708. "focus_depth",
  29709. "aperture",
  29710. "pentagon",
  29711. "maxZ",
  29712. "edge_blur",
  29713. "chromatic_aberration",
  29714. "distortion",
  29715. "blur_noise",
  29716. "grain_amount",
  29717. "screen_width",
  29718. "screen_height"
  29719. ], ["depthSampler", "grainSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29720. this._depthOfFieldPostProcess.onApply = function (effect) {
  29721. effect.setBool('pentagon', _this._dofPentagon);
  29722. effect.setBool('blur_noise', _this._blurNoise);
  29723. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  29724. effect.setFloat('grain_amount', _this._grainAmount);
  29725. effect.setTexture("depthSampler", _this._depthTexture);
  29726. effect.setTexture("grainSampler", _this._grainTexture);
  29727. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  29728. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  29729. effect.setFloat('distortion', _this._distortion);
  29730. effect.setFloat('focus_depth', _this._dofDepth);
  29731. effect.setFloat('aperture', _this._dofAperture);
  29732. effect.setFloat('gain', _this._highlightsGain);
  29733. effect.setFloat('threshold', _this._highlightsThreshold);
  29734. effect.setFloat('edge_blur', _this._edgeBlur);
  29735. };
  29736. };
  29737. // creates a black and white random noise texture, 512x512
  29738. LensRenderingPipeline.prototype._createGrainTexture = function () {
  29739. var size = 512;
  29740. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29741. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29742. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29743. var context = this._grainTexture.getContext();
  29744. var rand = function (min, max) {
  29745. return Math.random() * (max - min) + min;
  29746. };
  29747. var value;
  29748. for (var x = 0; x < size; x++) {
  29749. for (var y = 0; y < size; y++) {
  29750. value = Math.floor(rand(0.42, 0.58) * 255);
  29751. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  29752. context.fillRect(x, y, 1, 1);
  29753. }
  29754. }
  29755. this._grainTexture.update(false);
  29756. };
  29757. return LensRenderingPipeline;
  29758. })(BABYLON.PostProcessRenderPipeline);
  29759. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  29760. })(BABYLON || (BABYLON = {}));
  29761. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map//
  29762. // This post-process allows the modification of rendered colors by using
  29763. // a 'look-up table' (LUT). This effect is also called Color Grading.
  29764. //
  29765. // The object needs to be provided an url to a texture containing the color
  29766. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  29767. // Use an image editing software to tweak the LUT to match your needs.
  29768. //
  29769. // For an example of a color LUT, see here:
  29770. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  29771. // For explanations on color grading, see here:
  29772. // http://udn.epicgames.com/Three/ColorGrading.html
  29773. //
  29774. var BABYLON;
  29775. (function (BABYLON) {
  29776. var ColorCorrectionPostProcess = (function (_super) {
  29777. __extends(ColorCorrectionPostProcess, _super);
  29778. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  29779. var _this = this;
  29780. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  29781. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  29782. this._colorTableTexture.anisotropicFilteringLevel = 1;
  29783. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29784. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29785. this.onApply = function (effect) {
  29786. effect.setTexture("colorTable", _this._colorTableTexture);
  29787. };
  29788. }
  29789. return ColorCorrectionPostProcess;
  29790. })(BABYLON.PostProcess);
  29791. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  29792. })(BABYLON || (BABYLON = {}));
  29793. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.mapvar BABYLON;
  29794. (function (BABYLON) {
  29795. var SmartCollection = (function () {
  29796. function SmartCollection(capacity) {
  29797. if (capacity === void 0) { capacity = 10; }
  29798. this.count = 0;
  29799. this._initialCapacity = capacity;
  29800. this.items = {};
  29801. this._keys = new Array(this._initialCapacity);
  29802. }
  29803. SmartCollection.prototype.add = function (key, item) {
  29804. if (this.items[key] != undefined) {
  29805. return -1;
  29806. }
  29807. this.items[key] = item;
  29808. //literal keys are always strings, but we keep source type of key in _keys array
  29809. this._keys[this.count++] = key;
  29810. if (this.count > this._keys.length) {
  29811. this._keys.length *= 2;
  29812. }
  29813. return this.count;
  29814. };
  29815. SmartCollection.prototype.remove = function (key) {
  29816. if (this.items[key] == undefined) {
  29817. return -1;
  29818. }
  29819. return this.removeItemOfIndex(this.indexOf(key));
  29820. };
  29821. SmartCollection.prototype.removeItemOfIndex = function (index) {
  29822. if (index < this.count && index > -1) {
  29823. delete this.items[this._keys[index]];
  29824. while (index < this.count) {
  29825. this._keys[index] = this._keys[index + 1];
  29826. index++;
  29827. }
  29828. }
  29829. else {
  29830. return -1;
  29831. }
  29832. return --this.count;
  29833. };
  29834. SmartCollection.prototype.indexOf = function (key) {
  29835. for (var i = 0; i !== this.count; i++) {
  29836. if (this._keys[i] === key) {
  29837. return i;
  29838. }
  29839. }
  29840. return -1;
  29841. };
  29842. SmartCollection.prototype.item = function (key) {
  29843. return this.items[key];
  29844. };
  29845. SmartCollection.prototype.getAllKeys = function () {
  29846. if (this.count > 0) {
  29847. var keys = new Array(this.count);
  29848. for (var i = 0; i < this.count; i++) {
  29849. keys[i] = this._keys[i];
  29850. }
  29851. return keys;
  29852. }
  29853. else {
  29854. return undefined;
  29855. }
  29856. };
  29857. SmartCollection.prototype.getKeyByIndex = function (index) {
  29858. if (index < this.count && index > -1) {
  29859. return this._keys[index];
  29860. }
  29861. else {
  29862. return undefined;
  29863. }
  29864. };
  29865. SmartCollection.prototype.getItemByIndex = function (index) {
  29866. if (index < this.count && index > -1) {
  29867. return this.items[this._keys[index]];
  29868. }
  29869. else {
  29870. return undefined;
  29871. }
  29872. };
  29873. SmartCollection.prototype.empty = function () {
  29874. if (this.count > 0) {
  29875. this.count = 0;
  29876. this.items = {};
  29877. this._keys = new Array(this._initialCapacity);
  29878. }
  29879. };
  29880. return SmartCollection;
  29881. })();
  29882. BABYLON.SmartCollection = SmartCollection;
  29883. })(BABYLON || (BABYLON = {}));
  29884. //# sourceMappingURL=babylon.smartCollection.js.map