babylon.2.0.debug.js 1.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };var BABYLON;
  7. (function (BABYLON) {
  8. var Color3 = (function () {
  9. function Color3(r, g, b) {
  10. if (r === void 0) { r = 0; }
  11. if (g === void 0) { g = 0; }
  12. if (b === void 0) { b = 0; }
  13. this.r = r;
  14. this.g = g;
  15. this.b = b;
  16. }
  17. Color3.prototype.toString = function () {
  18. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  19. };
  20. // Operators
  21. Color3.prototype.toArray = function (array, index) {
  22. if (index === undefined) {
  23. index = 0;
  24. }
  25. array[index] = this.r;
  26. array[index + 1] = this.g;
  27. array[index + 2] = this.b;
  28. return this;
  29. };
  30. Color3.prototype.toColor4 = function (alpha) {
  31. if (alpha === void 0) { alpha = 1; }
  32. return new Color4(this.r, this.g, this.b, alpha);
  33. };
  34. Color3.prototype.asArray = function () {
  35. var result = [];
  36. this.toArray(result, 0);
  37. return result;
  38. };
  39. Color3.prototype.toLuminance = function () {
  40. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  41. };
  42. Color3.prototype.multiply = function (otherColor) {
  43. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  44. };
  45. Color3.prototype.multiplyToRef = function (otherColor, result) {
  46. result.r = this.r * otherColor.r;
  47. result.g = this.g * otherColor.g;
  48. result.b = this.b * otherColor.b;
  49. return this;
  50. };
  51. Color3.prototype.equals = function (otherColor) {
  52. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  53. };
  54. Color3.prototype.scale = function (scale) {
  55. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  56. };
  57. Color3.prototype.scaleToRef = function (scale, result) {
  58. result.r = this.r * scale;
  59. result.g = this.g * scale;
  60. result.b = this.b * scale;
  61. return this;
  62. };
  63. Color3.prototype.add = function (otherColor) {
  64. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  65. };
  66. Color3.prototype.addToRef = function (otherColor, result) {
  67. result.r = this.r + otherColor.r;
  68. result.g = this.g + otherColor.g;
  69. result.b = this.b + otherColor.b;
  70. return this;
  71. };
  72. Color3.prototype.subtract = function (otherColor) {
  73. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  74. };
  75. Color3.prototype.subtractToRef = function (otherColor, result) {
  76. result.r = this.r - otherColor.r;
  77. result.g = this.g - otherColor.g;
  78. result.b = this.b - otherColor.b;
  79. return this;
  80. };
  81. Color3.prototype.clone = function () {
  82. return new Color3(this.r, this.g, this.b);
  83. };
  84. Color3.prototype.copyFrom = function (source) {
  85. this.r = source.r;
  86. this.g = source.g;
  87. this.b = source.b;
  88. return this;
  89. };
  90. Color3.prototype.copyFromFloats = function (r, g, b) {
  91. this.r = r;
  92. this.g = g;
  93. this.b = b;
  94. return this;
  95. };
  96. // Statics
  97. Color3.FromArray = function (array, offset) {
  98. if (offset === void 0) { offset = 0; }
  99. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  100. };
  101. Color3.FromInts = function (r, g, b) {
  102. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  103. };
  104. Color3.Lerp = function (start, end, amount) {
  105. var r = start.r + ((end.r - start.r) * amount);
  106. var g = start.g + ((end.g - start.g) * amount);
  107. var b = start.b + ((end.b - start.b) * amount);
  108. return new Color3(r, g, b);
  109. };
  110. Color3.Red = function () {
  111. return new Color3(1, 0, 0);
  112. };
  113. Color3.Green = function () {
  114. return new Color3(0, 1, 0);
  115. };
  116. Color3.Blue = function () {
  117. return new Color3(0, 0, 1);
  118. };
  119. Color3.Black = function () {
  120. return new Color3(0, 0, 0);
  121. };
  122. Color3.White = function () {
  123. return new Color3(1, 1, 1);
  124. };
  125. Color3.Purple = function () {
  126. return new Color3(0.5, 0, 0.5);
  127. };
  128. Color3.Magenta = function () {
  129. return new Color3(1, 0, 1);
  130. };
  131. Color3.Yellow = function () {
  132. return new Color3(1, 1, 0);
  133. };
  134. Color3.Gray = function () {
  135. return new Color3(0.5, 0.5, 0.5);
  136. };
  137. return Color3;
  138. })();
  139. BABYLON.Color3 = Color3;
  140. var Color4 = (function () {
  141. function Color4(r, g, b, a) {
  142. this.r = r;
  143. this.g = g;
  144. this.b = b;
  145. this.a = a;
  146. }
  147. // Operators
  148. Color4.prototype.addInPlace = function (right) {
  149. this.r += right.r;
  150. this.g += right.g;
  151. this.b += right.b;
  152. this.a += right.a;
  153. return this;
  154. };
  155. Color4.prototype.asArray = function () {
  156. var result = [];
  157. this.toArray(result, 0);
  158. return result;
  159. };
  160. Color4.prototype.toArray = function (array, index) {
  161. if (index === undefined) {
  162. index = 0;
  163. }
  164. array[index] = this.r;
  165. array[index + 1] = this.g;
  166. array[index + 2] = this.b;
  167. array[index + 3] = this.a;
  168. return this;
  169. };
  170. Color4.prototype.add = function (right) {
  171. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  172. };
  173. Color4.prototype.subtract = function (right) {
  174. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  175. };
  176. Color4.prototype.subtractToRef = function (right, result) {
  177. result.r = this.r - right.r;
  178. result.g = this.g - right.g;
  179. result.b = this.b - right.b;
  180. result.a = this.a - right.a;
  181. return this;
  182. };
  183. Color4.prototype.scale = function (scale) {
  184. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  185. };
  186. Color4.prototype.scaleToRef = function (scale, result) {
  187. result.r = this.r * scale;
  188. result.g = this.g * scale;
  189. result.b = this.b * scale;
  190. result.a = this.a * scale;
  191. return this;
  192. };
  193. Color4.prototype.toString = function () {
  194. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  195. };
  196. Color4.prototype.clone = function () {
  197. return new Color4(this.r, this.g, this.b, this.a);
  198. };
  199. Color4.prototype.copyFrom = function (source) {
  200. this.r = source.r;
  201. this.g = source.g;
  202. this.b = source.b;
  203. this.a = source.a;
  204. return this;
  205. };
  206. // Statics
  207. Color4.Lerp = function (left, right, amount) {
  208. var result = new Color4(0, 0, 0, 0);
  209. Color4.LerpToRef(left, right, amount, result);
  210. return result;
  211. };
  212. Color4.LerpToRef = function (left, right, amount, result) {
  213. result.r = left.r + (right.r - left.r) * amount;
  214. result.g = left.g + (right.g - left.g) * amount;
  215. result.b = left.b + (right.b - left.b) * amount;
  216. result.a = left.a + (right.a - left.a) * amount;
  217. };
  218. Color4.FromArray = function (array, offset) {
  219. if (offset === void 0) { offset = 0; }
  220. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  221. };
  222. Color4.FromInts = function (r, g, b, a) {
  223. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  224. };
  225. return Color4;
  226. })();
  227. BABYLON.Color4 = Color4;
  228. var Vector2 = (function () {
  229. function Vector2(x, y) {
  230. this.x = x;
  231. this.y = y;
  232. }
  233. Vector2.prototype.toString = function () {
  234. return "{X: " + this.x + " Y:" + this.y + "}";
  235. };
  236. // Operators
  237. Vector2.prototype.toArray = function (array, index) {
  238. if (index === void 0) { index = 0; }
  239. array[index] = this.x;
  240. array[index + 1] = this.y;
  241. return this;
  242. };
  243. Vector2.prototype.asArray = function () {
  244. var result = [];
  245. this.toArray(result, 0);
  246. return result;
  247. };
  248. Vector2.prototype.copyFrom = function (source) {
  249. this.x = source.x;
  250. this.y = source.y;
  251. return this;
  252. };
  253. Vector2.prototype.copyFromFloats = function (x, y) {
  254. this.x = x;
  255. this.y = y;
  256. return this;
  257. };
  258. Vector2.prototype.add = function (otherVector) {
  259. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  260. };
  261. Vector2.prototype.addVector3 = function (otherVector) {
  262. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  263. };
  264. Vector2.prototype.subtract = function (otherVector) {
  265. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  266. };
  267. Vector2.prototype.subtractInPlace = function (otherVector) {
  268. this.x -= otherVector.x;
  269. this.y -= otherVector.y;
  270. return this;
  271. };
  272. Vector2.prototype.multiplyInPlace = function (otherVector) {
  273. this.x *= otherVector.x;
  274. this.y *= otherVector.y;
  275. return this;
  276. };
  277. Vector2.prototype.multiply = function (otherVector) {
  278. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  279. };
  280. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  281. result.x = this.x * otherVector.x;
  282. result.y = this.y * otherVector.y;
  283. return this;
  284. };
  285. Vector2.prototype.multiplyByFloats = function (x, y) {
  286. return new Vector2(this.x * x, this.y * y);
  287. };
  288. Vector2.prototype.divide = function (otherVector) {
  289. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  290. };
  291. Vector2.prototype.divideToRef = function (otherVector, result) {
  292. result.x = this.x / otherVector.x;
  293. result.y = this.y / otherVector.y;
  294. return this;
  295. };
  296. Vector2.prototype.negate = function () {
  297. return new Vector2(-this.x, -this.y);
  298. };
  299. Vector2.prototype.scaleInPlace = function (scale) {
  300. this.x *= scale;
  301. this.y *= scale;
  302. return this;
  303. };
  304. Vector2.prototype.scale = function (scale) {
  305. return new Vector2(this.x * scale, this.y * scale);
  306. };
  307. Vector2.prototype.equals = function (otherVector) {
  308. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  309. };
  310. // Properties
  311. Vector2.prototype.length = function () {
  312. return Math.sqrt(this.x * this.x + this.y * this.y);
  313. };
  314. Vector2.prototype.lengthSquared = function () {
  315. return (this.x * this.x + this.y * this.y);
  316. };
  317. // Methods
  318. Vector2.prototype.normalize = function () {
  319. var len = this.length();
  320. if (len === 0)
  321. return this;
  322. var num = 1.0 / len;
  323. this.x *= num;
  324. this.y *= num;
  325. return this;
  326. };
  327. Vector2.prototype.clone = function () {
  328. return new Vector2(this.x, this.y);
  329. };
  330. // Statics
  331. Vector2.Zero = function () {
  332. return new Vector2(0, 0);
  333. };
  334. Vector2.FromArray = function (array, offset) {
  335. if (offset === void 0) { offset = 0; }
  336. return new Vector2(array[offset], array[offset + 1]);
  337. };
  338. Vector2.FromArrayToRef = function (array, offset, result) {
  339. result.x = array[offset];
  340. result.y = array[offset + 1];
  341. };
  342. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  346. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  347. return new Vector2(x, y);
  348. };
  349. Vector2.Clamp = function (value, min, max) {
  350. var x = value.x;
  351. x = (x > max.x) ? max.x : x;
  352. x = (x < min.x) ? min.x : x;
  353. var y = value.y;
  354. y = (y > max.y) ? max.y : y;
  355. y = (y < min.y) ? min.y : y;
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  359. var squared = amount * amount;
  360. var cubed = amount * squared;
  361. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  362. var part2 = (-2.0 * cubed) + (3.0 * squared);
  363. var part3 = (cubed - (2.0 * squared)) + amount;
  364. var part4 = cubed - squared;
  365. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  366. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  367. return new Vector2(x, y);
  368. };
  369. Vector2.Lerp = function (start, end, amount) {
  370. var x = start.x + ((end.x - start.x) * amount);
  371. var y = start.y + ((end.y - start.y) * amount);
  372. return new Vector2(x, y);
  373. };
  374. Vector2.Dot = function (left, right) {
  375. return left.x * right.x + left.y * right.y;
  376. };
  377. Vector2.Normalize = function (vector) {
  378. var newVector = vector.clone();
  379. newVector.normalize();
  380. return newVector;
  381. };
  382. Vector2.Minimize = function (left, right) {
  383. var x = (left.x < right.x) ? left.x : right.x;
  384. var y = (left.y < right.y) ? left.y : right.y;
  385. return new Vector2(x, y);
  386. };
  387. Vector2.Maximize = function (left, right) {
  388. var x = (left.x > right.x) ? left.x : right.x;
  389. var y = (left.y > right.y) ? left.y : right.y;
  390. return new Vector2(x, y);
  391. };
  392. Vector2.Transform = function (vector, transformation) {
  393. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  394. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Distance = function (value1, value2) {
  398. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  399. };
  400. Vector2.DistanceSquared = function (value1, value2) {
  401. var x = value1.x - value2.x;
  402. var y = value1.y - value2.y;
  403. return (x * x) + (y * y);
  404. };
  405. return Vector2;
  406. })();
  407. BABYLON.Vector2 = Vector2;
  408. var Vector3 = (function () {
  409. function Vector3(x, y, z) {
  410. this.x = x;
  411. this.y = y;
  412. this.z = z;
  413. }
  414. Vector3.prototype.toString = function () {
  415. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  416. };
  417. // Operators
  418. Vector3.prototype.asArray = function () {
  419. var result = [];
  420. this.toArray(result, 0);
  421. return result;
  422. };
  423. Vector3.prototype.toArray = function (array, index) {
  424. if (index === void 0) { index = 0; }
  425. array[index] = this.x;
  426. array[index + 1] = this.y;
  427. array[index + 2] = this.z;
  428. return this;
  429. };
  430. Vector3.prototype.toQuaternion = function () {
  431. var result = new Quaternion(0, 0, 0, 1);
  432. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  433. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  434. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  435. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  436. var cosy = Math.cos(this.y * 0.5);
  437. var siny = Math.sin(this.y * 0.5);
  438. result.x = coszMinusx * siny;
  439. result.y = -sinzMinusx * siny;
  440. result.z = sinxPlusz * cosy;
  441. result.w = cosxPlusz * cosy;
  442. return result;
  443. };
  444. Vector3.prototype.addInPlace = function (otherVector) {
  445. this.x += otherVector.x;
  446. this.y += otherVector.y;
  447. this.z += otherVector.z;
  448. return this;
  449. };
  450. Vector3.prototype.add = function (otherVector) {
  451. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  452. };
  453. Vector3.prototype.addToRef = function (otherVector, result) {
  454. result.x = this.x + otherVector.x;
  455. result.y = this.y + otherVector.y;
  456. result.z = this.z + otherVector.z;
  457. return this;
  458. };
  459. Vector3.prototype.subtractInPlace = function (otherVector) {
  460. this.x -= otherVector.x;
  461. this.y -= otherVector.y;
  462. this.z -= otherVector.z;
  463. return this;
  464. };
  465. Vector3.prototype.subtract = function (otherVector) {
  466. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  467. };
  468. Vector3.prototype.subtractToRef = function (otherVector, result) {
  469. result.x = this.x - otherVector.x;
  470. result.y = this.y - otherVector.y;
  471. result.z = this.z - otherVector.z;
  472. return this;
  473. };
  474. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  475. return new Vector3(this.x - x, this.y - y, this.z - z);
  476. };
  477. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  478. result.x = this.x - x;
  479. result.y = this.y - y;
  480. result.z = this.z - z;
  481. return this;
  482. };
  483. Vector3.prototype.negate = function () {
  484. return new Vector3(-this.x, -this.y, -this.z);
  485. };
  486. Vector3.prototype.scaleInPlace = function (scale) {
  487. this.x *= scale;
  488. this.y *= scale;
  489. this.z *= scale;
  490. return this;
  491. };
  492. Vector3.prototype.scale = function (scale) {
  493. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  494. };
  495. Vector3.prototype.scaleToRef = function (scale, result) {
  496. result.x = this.x * scale;
  497. result.y = this.y * scale;
  498. result.z = this.z * scale;
  499. };
  500. Vector3.prototype.equals = function (otherVector) {
  501. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  502. };
  503. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  504. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  505. };
  506. Vector3.prototype.equalsToFloats = function (x, y, z) {
  507. return this.x === x && this.y === y && this.z === z;
  508. };
  509. Vector3.prototype.multiplyInPlace = function (otherVector) {
  510. this.x *= otherVector.x;
  511. this.y *= otherVector.y;
  512. this.z *= otherVector.z;
  513. return this;
  514. };
  515. Vector3.prototype.multiply = function (otherVector) {
  516. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  517. };
  518. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  519. result.x = this.x * otherVector.x;
  520. result.y = this.y * otherVector.y;
  521. result.z = this.z * otherVector.z;
  522. return this;
  523. };
  524. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  525. return new Vector3(this.x * x, this.y * y, this.z * z);
  526. };
  527. Vector3.prototype.divide = function (otherVector) {
  528. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  529. };
  530. Vector3.prototype.divideToRef = function (otherVector, result) {
  531. result.x = this.x / otherVector.x;
  532. result.y = this.y / otherVector.y;
  533. result.z = this.z / otherVector.z;
  534. return this;
  535. };
  536. Vector3.prototype.MinimizeInPlace = function (other) {
  537. if (other.x < this.x)
  538. this.x = other.x;
  539. if (other.y < this.y)
  540. this.y = other.y;
  541. if (other.z < this.z)
  542. this.z = other.z;
  543. return this;
  544. };
  545. Vector3.prototype.MaximizeInPlace = function (other) {
  546. if (other.x > this.x)
  547. this.x = other.x;
  548. if (other.y > this.y)
  549. this.y = other.y;
  550. if (other.z > this.z)
  551. this.z = other.z;
  552. return this;
  553. };
  554. // Properties
  555. Vector3.prototype.length = function () {
  556. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  557. };
  558. Vector3.prototype.lengthSquared = function () {
  559. return (this.x * this.x + this.y * this.y + this.z * this.z);
  560. };
  561. // Methods
  562. Vector3.prototype.normalize = function () {
  563. var len = this.length();
  564. if (len === 0)
  565. return this;
  566. var num = 1.0 / len;
  567. this.x *= num;
  568. this.y *= num;
  569. this.z *= num;
  570. return this;
  571. };
  572. Vector3.prototype.clone = function () {
  573. return new Vector3(this.x, this.y, this.z);
  574. };
  575. Vector3.prototype.copyFrom = function (source) {
  576. this.x = source.x;
  577. this.y = source.y;
  578. this.z = source.z;
  579. return this;
  580. };
  581. Vector3.prototype.copyFromFloats = function (x, y, z) {
  582. this.x = x;
  583. this.y = y;
  584. this.z = z;
  585. return this;
  586. };
  587. // Statics
  588. Vector3.FromArray = function (array, offset) {
  589. if (!offset) {
  590. offset = 0;
  591. }
  592. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  593. };
  594. Vector3.FromArrayToRef = function (array, offset, result) {
  595. result.x = array[offset];
  596. result.y = array[offset + 1];
  597. result.z = array[offset + 2];
  598. };
  599. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  600. result.x = array[offset];
  601. result.y = array[offset + 1];
  602. result.z = array[offset + 2];
  603. };
  604. Vector3.FromFloatsToRef = function (x, y, z, result) {
  605. result.x = x;
  606. result.y = y;
  607. result.z = z;
  608. };
  609. Vector3.Zero = function () {
  610. return new Vector3(0, 0, 0);
  611. };
  612. Vector3.Up = function () {
  613. return new Vector3(0, 1.0, 0);
  614. };
  615. Vector3.TransformCoordinates = function (vector, transformation) {
  616. var result = Vector3.Zero();
  617. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  618. return result;
  619. };
  620. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  621. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  622. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  623. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  624. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  625. result.x = x / w;
  626. result.y = y / w;
  627. result.z = z / w;
  628. };
  629. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  630. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  631. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  632. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  633. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  634. result.x = rx / rw;
  635. result.y = ry / rw;
  636. result.z = rz / rw;
  637. };
  638. Vector3.TransformNormal = function (vector, transformation) {
  639. var result = Vector3.Zero();
  640. Vector3.TransformNormalToRef(vector, transformation, result);
  641. return result;
  642. };
  643. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  644. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  645. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  646. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  647. };
  648. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  649. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  650. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  651. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  652. };
  653. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  654. var squared = amount * amount;
  655. var cubed = amount * squared;
  656. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  657. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  658. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  659. return new Vector3(x, y, z);
  660. };
  661. Vector3.Clamp = function (value, min, max) {
  662. var x = value.x;
  663. x = (x > max.x) ? max.x : x;
  664. x = (x < min.x) ? min.x : x;
  665. var y = value.y;
  666. y = (y > max.y) ? max.y : y;
  667. y = (y < min.y) ? min.y : y;
  668. var z = value.z;
  669. z = (z > max.z) ? max.z : z;
  670. z = (z < min.z) ? min.z : z;
  671. return new Vector3(x, y, z);
  672. };
  673. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  674. var squared = amount * amount;
  675. var cubed = amount * squared;
  676. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  677. var part2 = (-2.0 * cubed) + (3.0 * squared);
  678. var part3 = (cubed - (2.0 * squared)) + amount;
  679. var part4 = cubed - squared;
  680. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  681. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  682. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  683. return new Vector3(x, y, z);
  684. };
  685. Vector3.Lerp = function (start, end, amount) {
  686. var x = start.x + ((end.x - start.x) * amount);
  687. var y = start.y + ((end.y - start.y) * amount);
  688. var z = start.z + ((end.z - start.z) * amount);
  689. return new Vector3(x, y, z);
  690. };
  691. Vector3.Dot = function (left, right) {
  692. return (left.x * right.x + left.y * right.y + left.z * right.z);
  693. };
  694. Vector3.Cross = function (left, right) {
  695. var result = Vector3.Zero();
  696. Vector3.CrossToRef(left, right, result);
  697. return result;
  698. };
  699. Vector3.CrossToRef = function (left, right, result) {
  700. result.x = left.y * right.z - left.z * right.y;
  701. result.y = left.z * right.x - left.x * right.z;
  702. result.z = left.x * right.y - left.y * right.x;
  703. };
  704. Vector3.Normalize = function (vector) {
  705. var result = Vector3.Zero();
  706. Vector3.NormalizeToRef(vector, result);
  707. return result;
  708. };
  709. Vector3.NormalizeToRef = function (vector, result) {
  710. result.copyFrom(vector);
  711. result.normalize();
  712. };
  713. Vector3.Project = function (vector, world, transform, viewport) {
  714. var cw = viewport.width;
  715. var ch = viewport.height;
  716. var cx = viewport.x;
  717. var cy = viewport.y;
  718. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  719. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  720. return Vector3.TransformCoordinates(vector, finalMatrix);
  721. };
  722. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  723. var matrix = world.multiply(transform);
  724. matrix.invert();
  725. source.x = source.x / viewportWidth * 2 - 1;
  726. source.y = -(source.y / viewportHeight * 2 - 1);
  727. var vector = Vector3.TransformCoordinates(source, matrix);
  728. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  729. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  730. vector = vector.scale(1.0 / num);
  731. }
  732. return vector;
  733. };
  734. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  735. var matrix = world.multiply(view).multiply(projection);
  736. matrix.invert();
  737. source.x = source.x / viewportWidth * 2 - 1;
  738. source.y = -(source.y / viewportHeight * 2 - 1);
  739. var vector = Vector3.TransformCoordinates(source, matrix);
  740. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  741. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  742. vector = vector.scale(1.0 / num);
  743. }
  744. return vector;
  745. };
  746. Vector3.Minimize = function (left, right) {
  747. var min = left.clone();
  748. min.MinimizeInPlace(right);
  749. return min;
  750. };
  751. Vector3.Maximize = function (left, right) {
  752. var max = left.clone();
  753. max.MaximizeInPlace(right);
  754. return max;
  755. };
  756. Vector3.Distance = function (value1, value2) {
  757. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  758. };
  759. Vector3.DistanceSquared = function (value1, value2) {
  760. var x = value1.x - value2.x;
  761. var y = value1.y - value2.y;
  762. var z = value1.z - value2.z;
  763. return (x * x) + (y * y) + (z * z);
  764. };
  765. Vector3.Center = function (value1, value2) {
  766. var center = value1.add(value2);
  767. center.scaleInPlace(0.5);
  768. return center;
  769. };
  770. return Vector3;
  771. })();
  772. BABYLON.Vector3 = Vector3;
  773. //Vector4 class created for EulerAngle class conversion to Quaternion
  774. var Vector4 = (function () {
  775. function Vector4(x, y, z, w) {
  776. this.x = x;
  777. this.y = y;
  778. this.z = z;
  779. this.w = w;
  780. }
  781. Vector4.prototype.toString = function () {
  782. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  783. };
  784. // Operators
  785. Vector4.prototype.asArray = function () {
  786. var result = [];
  787. this.toArray(result, 0);
  788. return result;
  789. };
  790. Vector4.prototype.toArray = function (array, index) {
  791. if (index === undefined) {
  792. index = 0;
  793. }
  794. array[index] = this.x;
  795. array[index + 1] = this.y;
  796. array[index + 2] = this.z;
  797. array[index + 3] = this.w;
  798. return this;
  799. };
  800. Vector4.prototype.addInPlace = function (otherVector) {
  801. this.x += otherVector.x;
  802. this.y += otherVector.y;
  803. this.z += otherVector.z;
  804. this.w += otherVector.w;
  805. return this;
  806. };
  807. Vector4.prototype.add = function (otherVector) {
  808. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  809. };
  810. Vector4.prototype.addToRef = function (otherVector, result) {
  811. result.x = this.x + otherVector.x;
  812. result.y = this.y + otherVector.y;
  813. result.z = this.z + otherVector.z;
  814. result.w = this.w + otherVector.w;
  815. return this;
  816. };
  817. Vector4.prototype.subtractInPlace = function (otherVector) {
  818. this.x -= otherVector.x;
  819. this.y -= otherVector.y;
  820. this.z -= otherVector.z;
  821. this.w -= otherVector.w;
  822. return this;
  823. };
  824. Vector4.prototype.subtract = function (otherVector) {
  825. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  826. };
  827. Vector4.prototype.subtractToRef = function (otherVector, result) {
  828. result.x = this.x - otherVector.x;
  829. result.y = this.y - otherVector.y;
  830. result.z = this.z - otherVector.z;
  831. result.w = this.w - otherVector.w;
  832. return this;
  833. };
  834. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  835. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  836. };
  837. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  838. result.x = this.x - x;
  839. result.y = this.y - y;
  840. result.z = this.z - z;
  841. result.w = this.w - w;
  842. return this;
  843. };
  844. Vector4.prototype.negate = function () {
  845. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  846. };
  847. Vector4.prototype.scaleInPlace = function (scale) {
  848. this.x *= scale;
  849. this.y *= scale;
  850. this.z *= scale;
  851. this.w *= scale;
  852. return this;
  853. };
  854. Vector4.prototype.scale = function (scale) {
  855. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  856. };
  857. Vector4.prototype.scaleToRef = function (scale, result) {
  858. result.x = this.x * scale;
  859. result.y = this.y * scale;
  860. result.z = this.z * scale;
  861. result.w = this.w * scale;
  862. };
  863. Vector4.prototype.equals = function (otherVector) {
  864. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  865. };
  866. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  867. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  868. };
  869. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  870. return this.x === x && this.y === y && this.z === z && this.w === w;
  871. };
  872. Vector4.prototype.multiplyInPlace = function (otherVector) {
  873. this.x *= otherVector.x;
  874. this.y *= otherVector.y;
  875. this.z *= otherVector.z;
  876. this.w *= otherVector.w;
  877. return this;
  878. };
  879. Vector4.prototype.multiply = function (otherVector) {
  880. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  881. };
  882. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  883. result.x = this.x * otherVector.x;
  884. result.y = this.y * otherVector.y;
  885. result.z = this.z * otherVector.z;
  886. result.w = this.w * otherVector.w;
  887. return this;
  888. };
  889. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  890. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  891. };
  892. Vector4.prototype.divide = function (otherVector) {
  893. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  894. };
  895. Vector4.prototype.divideToRef = function (otherVector, result) {
  896. result.x = this.x / otherVector.x;
  897. result.y = this.y / otherVector.y;
  898. result.z = this.z / otherVector.z;
  899. result.w = this.w / otherVector.w;
  900. return this;
  901. };
  902. Vector4.prototype.MinimizeInPlace = function (other) {
  903. if (other.x < this.x)
  904. this.x = other.x;
  905. if (other.y < this.y)
  906. this.y = other.y;
  907. if (other.z < this.z)
  908. this.z = other.z;
  909. if (other.w < this.w)
  910. this.w = other.w;
  911. return this;
  912. };
  913. Vector4.prototype.MaximizeInPlace = function (other) {
  914. if (other.x > this.x)
  915. this.x = other.x;
  916. if (other.y > this.y)
  917. this.y = other.y;
  918. if (other.z > this.z)
  919. this.z = other.z;
  920. if (other.w > this.w)
  921. this.w = other.w;
  922. return this;
  923. };
  924. // Properties
  925. Vector4.prototype.length = function () {
  926. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  927. };
  928. Vector4.prototype.lengthSquared = function () {
  929. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  930. };
  931. // Methods
  932. Vector4.prototype.normalize = function () {
  933. var len = this.length();
  934. if (len === 0)
  935. return this;
  936. var num = 1.0 / len;
  937. this.x *= num;
  938. this.y *= num;
  939. this.z *= num;
  940. this.w *= num;
  941. return this;
  942. };
  943. Vector4.prototype.clone = function () {
  944. return new Vector4(this.x, this.y, this.z, this.w);
  945. };
  946. Vector4.prototype.copyFrom = function (source) {
  947. this.x = source.x;
  948. this.y = source.y;
  949. this.z = source.z;
  950. this.w = source.w;
  951. return this;
  952. };
  953. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  954. this.x = x;
  955. this.y = y;
  956. this.z = z;
  957. this.w = w;
  958. return this;
  959. };
  960. // Statics
  961. Vector4.FromArray = function (array, offset) {
  962. if (!offset) {
  963. offset = 0;
  964. }
  965. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  966. };
  967. Vector4.FromArrayToRef = function (array, offset, result) {
  968. result.x = array[offset];
  969. result.y = array[offset + 1];
  970. result.z = array[offset + 2];
  971. result.w = array[offset + 3];
  972. };
  973. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  974. result.x = array[offset];
  975. result.y = array[offset + 1];
  976. result.z = array[offset + 2];
  977. result.w = array[offset + 3];
  978. };
  979. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  980. result.x = x;
  981. result.y = y;
  982. result.z = z;
  983. result.w = w;
  984. };
  985. Vector4.Zero = function () {
  986. return new Vector4(0, 0, 0, 0);
  987. };
  988. Vector4.Normalize = function (vector) {
  989. var result = Vector4.Zero();
  990. Vector4.NormalizeToRef(vector, result);
  991. return result;
  992. };
  993. Vector4.NormalizeToRef = function (vector, result) {
  994. result.copyFrom(vector);
  995. result.normalize();
  996. };
  997. Vector4.Minimize = function (left, right) {
  998. var min = left.clone();
  999. min.MinimizeInPlace(right);
  1000. return min;
  1001. };
  1002. Vector4.Maximize = function (left, right) {
  1003. var max = left.clone();
  1004. max.MaximizeInPlace(right);
  1005. return max;
  1006. };
  1007. Vector4.Distance = function (value1, value2) {
  1008. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1009. };
  1010. Vector4.DistanceSquared = function (value1, value2) {
  1011. var x = value1.x - value2.x;
  1012. var y = value1.y - value2.y;
  1013. var z = value1.z - value2.z;
  1014. var w = value1.w - value2.w;
  1015. return (x * x) + (y * y) + (z * z) + (w * w);
  1016. };
  1017. Vector4.Center = function (value1, value2) {
  1018. var center = value1.add(value2);
  1019. center.scaleInPlace(0.5);
  1020. return center;
  1021. };
  1022. return Vector4;
  1023. })();
  1024. BABYLON.Vector4 = Vector4;
  1025. var Quaternion = (function () {
  1026. function Quaternion(x, y, z, w) {
  1027. if (x === void 0) { x = 0; }
  1028. if (y === void 0) { y = 0; }
  1029. if (z === void 0) { z = 0; }
  1030. if (w === void 0) { w = 1; }
  1031. this.x = x;
  1032. this.y = y;
  1033. this.z = z;
  1034. this.w = w;
  1035. }
  1036. Quaternion.prototype.toString = function () {
  1037. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1038. };
  1039. Quaternion.prototype.asArray = function () {
  1040. return [this.x, this.y, this.z, this.w];
  1041. };
  1042. Quaternion.prototype.equals = function (otherQuaternion) {
  1043. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1044. };
  1045. Quaternion.prototype.clone = function () {
  1046. return new Quaternion(this.x, this.y, this.z, this.w);
  1047. };
  1048. Quaternion.prototype.copyFrom = function (other) {
  1049. this.x = other.x;
  1050. this.y = other.y;
  1051. this.z = other.z;
  1052. this.w = other.w;
  1053. return this;
  1054. };
  1055. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1056. this.x = x;
  1057. this.y = y;
  1058. this.z = z;
  1059. this.w = w;
  1060. return this;
  1061. };
  1062. Quaternion.prototype.add = function (other) {
  1063. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1064. };
  1065. Quaternion.prototype.subtract = function (other) {
  1066. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1067. };
  1068. Quaternion.prototype.scale = function (value) {
  1069. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1070. };
  1071. Quaternion.prototype.multiply = function (q1) {
  1072. var result = new Quaternion(0, 0, 0, 1.0);
  1073. this.multiplyToRef(q1, result);
  1074. return result;
  1075. };
  1076. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1077. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1078. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1079. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1080. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1081. return this;
  1082. };
  1083. Quaternion.prototype.length = function () {
  1084. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1085. };
  1086. Quaternion.prototype.normalize = function () {
  1087. var length = 1.0 / this.length();
  1088. this.x *= length;
  1089. this.y *= length;
  1090. this.z *= length;
  1091. this.w *= length;
  1092. return this;
  1093. };
  1094. Quaternion.prototype.toEulerAngles = function () {
  1095. var result = Vector3.Zero();
  1096. this.toEulerAnglesToRef(result);
  1097. return result;
  1098. };
  1099. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1100. //result is an EulerAngles in the in the z-x-z convention
  1101. var qx = this.x;
  1102. var qy = this.y;
  1103. var qz = this.z;
  1104. var qw = this.w;
  1105. var qxy = qx * qy;
  1106. var qxz = qx * qz;
  1107. var qwy = qw * qy;
  1108. var qwz = qw * qz;
  1109. var qwx = qw * qx;
  1110. var qyz = qy * qz;
  1111. var sqx = qx * qx;
  1112. var sqy = qy * qy;
  1113. var determinant = sqx + sqy;
  1114. if (determinant !== 0.000 && determinant !== 1.000) {
  1115. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1116. result.y = Math.acos(1 - 2 * determinant);
  1117. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1118. }
  1119. else {
  1120. if (determinant === 0.0) {
  1121. result.x = 0.0;
  1122. result.y = 0.0;
  1123. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1124. }
  1125. else {
  1126. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1127. result.y = Math.PI;
  1128. result.z = 0.0;
  1129. }
  1130. }
  1131. return this;
  1132. };
  1133. Quaternion.prototype.toRotationMatrix = function (result) {
  1134. var xx = this.x * this.x;
  1135. var yy = this.y * this.y;
  1136. var zz = this.z * this.z;
  1137. var xy = this.x * this.y;
  1138. var zw = this.z * this.w;
  1139. var zx = this.z * this.x;
  1140. var yw = this.y * this.w;
  1141. var yz = this.y * this.z;
  1142. var xw = this.x * this.w;
  1143. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1144. result.m[1] = 2.0 * (xy + zw);
  1145. result.m[2] = 2.0 * (zx - yw);
  1146. result.m[3] = 0;
  1147. result.m[4] = 2.0 * (xy - zw);
  1148. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1149. result.m[6] = 2.0 * (yz + xw);
  1150. result.m[7] = 0;
  1151. result.m[8] = 2.0 * (zx + yw);
  1152. result.m[9] = 2.0 * (yz - xw);
  1153. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1154. result.m[11] = 0;
  1155. result.m[12] = 0;
  1156. result.m[13] = 0;
  1157. result.m[14] = 0;
  1158. result.m[15] = 1.0;
  1159. return this;
  1160. };
  1161. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1162. Quaternion.FromRotationMatrixToRef(matrix, this);
  1163. return this;
  1164. };
  1165. // Statics
  1166. Quaternion.FromRotationMatrix = function (matrix) {
  1167. var result = new Quaternion();
  1168. Quaternion.FromRotationMatrixToRef(matrix, result);
  1169. return result;
  1170. };
  1171. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1172. var data = matrix.m;
  1173. var m11 = data[0], m12 = data[4], m13 = data[8];
  1174. var m21 = data[1], m22 = data[5], m23 = data[9];
  1175. var m31 = data[2], m32 = data[6], m33 = data[10];
  1176. var trace = m11 + m22 + m33;
  1177. var s;
  1178. if (trace > 0) {
  1179. s = 0.5 / Math.sqrt(trace + 1.0);
  1180. result.w = 0.25 / s;
  1181. result.x = (m32 - m23) * s;
  1182. result.y = (m13 - m31) * s;
  1183. result.z = (m21 - m12) * s;
  1184. }
  1185. else if (m11 > m22 && m11 > m33) {
  1186. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1187. result.w = (m32 - m23) / s;
  1188. result.x = 0.25 * s;
  1189. result.y = (m12 + m21) / s;
  1190. result.z = (m13 + m31) / s;
  1191. }
  1192. else if (m22 > m33) {
  1193. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1194. result.w = (m13 - m31) / s;
  1195. result.x = (m12 + m21) / s;
  1196. result.y = 0.25 * s;
  1197. result.z = (m23 + m32) / s;
  1198. }
  1199. else {
  1200. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1201. result.w = (m21 - m12) / s;
  1202. result.x = (m13 + m31) / s;
  1203. result.y = (m23 + m32) / s;
  1204. result.z = 0.25 * s;
  1205. }
  1206. };
  1207. Quaternion.Inverse = function (q) {
  1208. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1209. };
  1210. Quaternion.Identity = function () {
  1211. return new Quaternion(0, 0, 0, 1);
  1212. };
  1213. Quaternion.RotationAxis = function (axis, angle) {
  1214. var result = new Quaternion();
  1215. var sin = Math.sin(angle / 2);
  1216. result.w = Math.cos(angle / 2);
  1217. result.x = axis.x * sin;
  1218. result.y = axis.y * sin;
  1219. result.z = axis.z * sin;
  1220. return result;
  1221. };
  1222. Quaternion.FromArray = function (array, offset) {
  1223. if (!offset) {
  1224. offset = 0;
  1225. }
  1226. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1227. };
  1228. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1229. var result = new Quaternion();
  1230. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1231. return result;
  1232. };
  1233. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1234. var halfRoll = roll * 0.5;
  1235. var halfPitch = pitch * 0.5;
  1236. var halfYaw = yaw * 0.5;
  1237. var sinRoll = Math.sin(halfRoll);
  1238. var cosRoll = Math.cos(halfRoll);
  1239. var sinPitch = Math.sin(halfPitch);
  1240. var cosPitch = Math.cos(halfPitch);
  1241. var sinYaw = Math.sin(halfYaw);
  1242. var cosYaw = Math.cos(halfYaw);
  1243. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1244. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1245. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1246. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1247. };
  1248. Quaternion.Slerp = function (left, right, amount) {
  1249. var num2;
  1250. var num3;
  1251. var num = amount;
  1252. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1253. var flag = false;
  1254. if (num4 < 0) {
  1255. flag = true;
  1256. num4 = -num4;
  1257. }
  1258. if (num4 > 0.999999) {
  1259. num3 = 1 - num;
  1260. num2 = flag ? -num : num;
  1261. }
  1262. else {
  1263. var num5 = Math.acos(num4);
  1264. var num6 = (1.0 / Math.sin(num5));
  1265. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1266. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1267. }
  1268. 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));
  1269. };
  1270. return Quaternion;
  1271. })();
  1272. BABYLON.Quaternion = Quaternion;
  1273. var Matrix = (function () {
  1274. function Matrix() {
  1275. this.m = new Float32Array(16);
  1276. }
  1277. // Properties
  1278. Matrix.prototype.isIdentity = function () {
  1279. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1280. return false;
  1281. 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)
  1282. return false;
  1283. return true;
  1284. };
  1285. Matrix.prototype.determinant = function () {
  1286. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1287. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1288. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1289. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1290. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1291. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1292. 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))));
  1293. };
  1294. // Methods
  1295. Matrix.prototype.toArray = function () {
  1296. return this.m;
  1297. };
  1298. Matrix.prototype.asArray = function () {
  1299. return this.toArray();
  1300. };
  1301. Matrix.prototype.invert = function () {
  1302. this.invertToRef(this);
  1303. return this;
  1304. };
  1305. Matrix.prototype.invertToRef = function (other) {
  1306. var l1 = this.m[0];
  1307. var l2 = this.m[1];
  1308. var l3 = this.m[2];
  1309. var l4 = this.m[3];
  1310. var l5 = this.m[4];
  1311. var l6 = this.m[5];
  1312. var l7 = this.m[6];
  1313. var l8 = this.m[7];
  1314. var l9 = this.m[8];
  1315. var l10 = this.m[9];
  1316. var l11 = this.m[10];
  1317. var l12 = this.m[11];
  1318. var l13 = this.m[12];
  1319. var l14 = this.m[13];
  1320. var l15 = this.m[14];
  1321. var l16 = this.m[15];
  1322. var l17 = (l11 * l16) - (l12 * l15);
  1323. var l18 = (l10 * l16) - (l12 * l14);
  1324. var l19 = (l10 * l15) - (l11 * l14);
  1325. var l20 = (l9 * l16) - (l12 * l13);
  1326. var l21 = (l9 * l15) - (l11 * l13);
  1327. var l22 = (l9 * l14) - (l10 * l13);
  1328. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1329. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1330. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1331. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1332. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1333. var l28 = (l7 * l16) - (l8 * l15);
  1334. var l29 = (l6 * l16) - (l8 * l14);
  1335. var l30 = (l6 * l15) - (l7 * l14);
  1336. var l31 = (l5 * l16) - (l8 * l13);
  1337. var l32 = (l5 * l15) - (l7 * l13);
  1338. var l33 = (l5 * l14) - (l6 * l13);
  1339. var l34 = (l7 * l12) - (l8 * l11);
  1340. var l35 = (l6 * l12) - (l8 * l10);
  1341. var l36 = (l6 * l11) - (l7 * l10);
  1342. var l37 = (l5 * l12) - (l8 * l9);
  1343. var l38 = (l5 * l11) - (l7 * l9);
  1344. var l39 = (l5 * l10) - (l6 * l9);
  1345. other.m[0] = l23 * l27;
  1346. other.m[4] = l24 * l27;
  1347. other.m[8] = l25 * l27;
  1348. other.m[12] = l26 * l27;
  1349. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1350. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1351. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1352. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1353. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1354. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1355. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1356. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1357. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1358. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1359. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1360. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1361. return this;
  1362. };
  1363. Matrix.prototype.setTranslation = function (vector3) {
  1364. this.m[12] = vector3.x;
  1365. this.m[13] = vector3.y;
  1366. this.m[14] = vector3.z;
  1367. return this;
  1368. };
  1369. Matrix.prototype.multiply = function (other) {
  1370. var result = new Matrix();
  1371. this.multiplyToRef(other, result);
  1372. return result;
  1373. };
  1374. Matrix.prototype.copyFrom = function (other) {
  1375. for (var index = 0; index < 16; index++) {
  1376. this.m[index] = other.m[index];
  1377. }
  1378. return this;
  1379. };
  1380. Matrix.prototype.copyToArray = function (array, offset) {
  1381. if (offset === void 0) { offset = 0; }
  1382. for (var index = 0; index < 16; index++) {
  1383. array[offset + index] = this.m[index];
  1384. }
  1385. return this;
  1386. };
  1387. Matrix.prototype.multiplyToRef = function (other, result) {
  1388. this.multiplyToArray(other, result.m, 0);
  1389. return this;
  1390. };
  1391. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1392. var tm0 = this.m[0];
  1393. var tm1 = this.m[1];
  1394. var tm2 = this.m[2];
  1395. var tm3 = this.m[3];
  1396. var tm4 = this.m[4];
  1397. var tm5 = this.m[5];
  1398. var tm6 = this.m[6];
  1399. var tm7 = this.m[7];
  1400. var tm8 = this.m[8];
  1401. var tm9 = this.m[9];
  1402. var tm10 = this.m[10];
  1403. var tm11 = this.m[11];
  1404. var tm12 = this.m[12];
  1405. var tm13 = this.m[13];
  1406. var tm14 = this.m[14];
  1407. var tm15 = this.m[15];
  1408. var om0 = other.m[0];
  1409. var om1 = other.m[1];
  1410. var om2 = other.m[2];
  1411. var om3 = other.m[3];
  1412. var om4 = other.m[4];
  1413. var om5 = other.m[5];
  1414. var om6 = other.m[6];
  1415. var om7 = other.m[7];
  1416. var om8 = other.m[8];
  1417. var om9 = other.m[9];
  1418. var om10 = other.m[10];
  1419. var om11 = other.m[11];
  1420. var om12 = other.m[12];
  1421. var om13 = other.m[13];
  1422. var om14 = other.m[14];
  1423. var om15 = other.m[15];
  1424. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1425. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1426. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1427. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1428. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1429. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1430. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1431. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1432. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1433. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1434. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1435. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1436. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1437. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1438. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1439. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1440. return this;
  1441. };
  1442. Matrix.prototype.equals = function (value) {
  1443. 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]);
  1444. };
  1445. Matrix.prototype.clone = function () {
  1446. 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]);
  1447. };
  1448. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1449. translation.x = this.m[12];
  1450. translation.y = this.m[13];
  1451. translation.z = this.m[14];
  1452. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1453. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1454. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1455. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1456. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1457. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1458. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1459. rotation.x = 0;
  1460. rotation.y = 0;
  1461. rotation.z = 0;
  1462. rotation.w = 1;
  1463. return false;
  1464. }
  1465. 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);
  1466. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1467. return true;
  1468. };
  1469. // Statics
  1470. Matrix.FromArray = function (array, offset) {
  1471. var result = new Matrix();
  1472. if (!offset) {
  1473. offset = 0;
  1474. }
  1475. Matrix.FromArrayToRef(array, offset, result);
  1476. return result;
  1477. };
  1478. Matrix.FromArrayToRef = function (array, offset, result) {
  1479. for (var index = 0; index < 16; index++) {
  1480. result.m[index] = array[index + offset];
  1481. }
  1482. };
  1483. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1484. result.m[0] = initialM11;
  1485. result.m[1] = initialM12;
  1486. result.m[2] = initialM13;
  1487. result.m[3] = initialM14;
  1488. result.m[4] = initialM21;
  1489. result.m[5] = initialM22;
  1490. result.m[6] = initialM23;
  1491. result.m[7] = initialM24;
  1492. result.m[8] = initialM31;
  1493. result.m[9] = initialM32;
  1494. result.m[10] = initialM33;
  1495. result.m[11] = initialM34;
  1496. result.m[12] = initialM41;
  1497. result.m[13] = initialM42;
  1498. result.m[14] = initialM43;
  1499. result.m[15] = initialM44;
  1500. };
  1501. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1502. var result = new Matrix();
  1503. result.m[0] = initialM11;
  1504. result.m[1] = initialM12;
  1505. result.m[2] = initialM13;
  1506. result.m[3] = initialM14;
  1507. result.m[4] = initialM21;
  1508. result.m[5] = initialM22;
  1509. result.m[6] = initialM23;
  1510. result.m[7] = initialM24;
  1511. result.m[8] = initialM31;
  1512. result.m[9] = initialM32;
  1513. result.m[10] = initialM33;
  1514. result.m[11] = initialM34;
  1515. result.m[12] = initialM41;
  1516. result.m[13] = initialM42;
  1517. result.m[14] = initialM43;
  1518. result.m[15] = initialM44;
  1519. return result;
  1520. };
  1521. Matrix.Compose = function (scale, rotation, translation) {
  1522. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1523. var rotationMatrix = Matrix.Identity();
  1524. rotation.toRotationMatrix(rotationMatrix);
  1525. result = result.multiply(rotationMatrix);
  1526. result.setTranslation(translation);
  1527. return result;
  1528. };
  1529. Matrix.Identity = function () {
  1530. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1531. };
  1532. Matrix.IdentityToRef = function (result) {
  1533. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1534. };
  1535. Matrix.Zero = function () {
  1536. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1537. };
  1538. Matrix.RotationX = function (angle) {
  1539. var result = new Matrix();
  1540. Matrix.RotationXToRef(angle, result);
  1541. return result;
  1542. };
  1543. Matrix.Invert = function (source) {
  1544. var result = new Matrix();
  1545. source.invertToRef(result);
  1546. return result;
  1547. };
  1548. Matrix.RotationXToRef = function (angle, result) {
  1549. var s = Math.sin(angle);
  1550. var c = Math.cos(angle);
  1551. result.m[0] = 1.0;
  1552. result.m[15] = 1.0;
  1553. result.m[5] = c;
  1554. result.m[10] = c;
  1555. result.m[9] = -s;
  1556. result.m[6] = s;
  1557. result.m[1] = 0;
  1558. result.m[2] = 0;
  1559. result.m[3] = 0;
  1560. result.m[4] = 0;
  1561. result.m[7] = 0;
  1562. result.m[8] = 0;
  1563. result.m[11] = 0;
  1564. result.m[12] = 0;
  1565. result.m[13] = 0;
  1566. result.m[14] = 0;
  1567. };
  1568. Matrix.RotationY = function (angle) {
  1569. var result = new Matrix();
  1570. Matrix.RotationYToRef(angle, result);
  1571. return result;
  1572. };
  1573. Matrix.RotationYToRef = function (angle, result) {
  1574. var s = Math.sin(angle);
  1575. var c = Math.cos(angle);
  1576. result.m[5] = 1.0;
  1577. result.m[15] = 1.0;
  1578. result.m[0] = c;
  1579. result.m[2] = -s;
  1580. result.m[8] = s;
  1581. result.m[10] = c;
  1582. result.m[1] = 0;
  1583. result.m[3] = 0;
  1584. result.m[4] = 0;
  1585. result.m[6] = 0;
  1586. result.m[7] = 0;
  1587. result.m[9] = 0;
  1588. result.m[11] = 0;
  1589. result.m[12] = 0;
  1590. result.m[13] = 0;
  1591. result.m[14] = 0;
  1592. };
  1593. Matrix.RotationZ = function (angle) {
  1594. var result = new Matrix();
  1595. Matrix.RotationZToRef(angle, result);
  1596. return result;
  1597. };
  1598. Matrix.RotationZToRef = function (angle, result) {
  1599. var s = Math.sin(angle);
  1600. var c = Math.cos(angle);
  1601. result.m[10] = 1.0;
  1602. result.m[15] = 1.0;
  1603. result.m[0] = c;
  1604. result.m[1] = s;
  1605. result.m[4] = -s;
  1606. result.m[5] = c;
  1607. result.m[2] = 0;
  1608. result.m[3] = 0;
  1609. result.m[6] = 0;
  1610. result.m[7] = 0;
  1611. result.m[8] = 0;
  1612. result.m[9] = 0;
  1613. result.m[11] = 0;
  1614. result.m[12] = 0;
  1615. result.m[13] = 0;
  1616. result.m[14] = 0;
  1617. };
  1618. Matrix.RotationAxis = function (axis, angle) {
  1619. var s = Math.sin(-angle);
  1620. var c = Math.cos(-angle);
  1621. var c1 = 1 - c;
  1622. axis.normalize();
  1623. var result = Matrix.Zero();
  1624. result.m[0] = (axis.x * axis.x) * c1 + c;
  1625. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1626. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1627. result.m[3] = 0.0;
  1628. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1629. result.m[5] = (axis.y * axis.y) * c1 + c;
  1630. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1631. result.m[7] = 0.0;
  1632. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1633. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1634. result.m[10] = (axis.z * axis.z) * c1 + c;
  1635. result.m[11] = 0.0;
  1636. result.m[15] = 1.0;
  1637. return result;
  1638. };
  1639. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1640. var result = new Matrix();
  1641. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1642. return result;
  1643. };
  1644. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1645. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1646. this._tempQuaternion.toRotationMatrix(result);
  1647. };
  1648. Matrix.Scaling = function (x, y, z) {
  1649. var result = Matrix.Zero();
  1650. Matrix.ScalingToRef(x, y, z, result);
  1651. return result;
  1652. };
  1653. Matrix.ScalingToRef = function (x, y, z, result) {
  1654. result.m[0] = x;
  1655. result.m[1] = 0;
  1656. result.m[2] = 0;
  1657. result.m[3] = 0;
  1658. result.m[4] = 0;
  1659. result.m[5] = y;
  1660. result.m[6] = 0;
  1661. result.m[7] = 0;
  1662. result.m[8] = 0;
  1663. result.m[9] = 0;
  1664. result.m[10] = z;
  1665. result.m[11] = 0;
  1666. result.m[12] = 0;
  1667. result.m[13] = 0;
  1668. result.m[14] = 0;
  1669. result.m[15] = 1.0;
  1670. };
  1671. Matrix.Translation = function (x, y, z) {
  1672. var result = Matrix.Identity();
  1673. Matrix.TranslationToRef(x, y, z, result);
  1674. return result;
  1675. };
  1676. Matrix.TranslationToRef = function (x, y, z, result) {
  1677. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1678. };
  1679. Matrix.LookAtLH = function (eye, target, up) {
  1680. var result = Matrix.Zero();
  1681. Matrix.LookAtLHToRef(eye, target, up, result);
  1682. return result;
  1683. };
  1684. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1685. // Z axis
  1686. target.subtractToRef(eye, this._zAxis);
  1687. this._zAxis.normalize();
  1688. // X axis
  1689. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1690. this._xAxis.normalize();
  1691. // Y axis
  1692. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1693. this._yAxis.normalize();
  1694. // Eye angles
  1695. var ex = -Vector3.Dot(this._xAxis, eye);
  1696. var ey = -Vector3.Dot(this._yAxis, eye);
  1697. var ez = -Vector3.Dot(this._zAxis, eye);
  1698. 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);
  1699. };
  1700. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1701. var hw = 2.0 / width;
  1702. var hh = 2.0 / height;
  1703. var id = 1.0 / (zfar - znear);
  1704. var nid = znear / (znear - zfar);
  1705. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1706. };
  1707. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1708. var matrix = Matrix.Zero();
  1709. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1710. return matrix;
  1711. };
  1712. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1713. result.m[0] = 2.0 / (right - left);
  1714. result.m[1] = result.m[2] = result.m[3] = 0;
  1715. result.m[5] = 2.0 / (top - bottom);
  1716. result.m[4] = result.m[6] = result.m[7] = 0;
  1717. result.m[10] = -1.0 / (znear - zfar);
  1718. result.m[8] = result.m[9] = result.m[11] = 0;
  1719. result.m[12] = (left + right) / (left - right);
  1720. result.m[13] = (top + bottom) / (bottom - top);
  1721. result.m[14] = znear / (znear - zfar);
  1722. result.m[15] = 1.0;
  1723. };
  1724. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1725. var matrix = Matrix.Zero();
  1726. matrix.m[0] = (2.0 * znear) / width;
  1727. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1728. matrix.m[5] = (2.0 * znear) / height;
  1729. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1730. matrix.m[10] = -zfar / (znear - zfar);
  1731. matrix.m[8] = matrix.m[9] = 0.0;
  1732. matrix.m[11] = 1.0;
  1733. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1734. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1735. return matrix;
  1736. };
  1737. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1738. var matrix = Matrix.Zero();
  1739. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1740. return matrix;
  1741. };
  1742. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1743. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1744. var tan = 1.0 / (Math.tan(fov * 0.5));
  1745. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1746. if (v_fixed) {
  1747. result.m[0] = tan / aspect;
  1748. }
  1749. else {
  1750. result.m[0] = tan;
  1751. }
  1752. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1753. if (v_fixed) {
  1754. result.m[5] = tan;
  1755. }
  1756. else {
  1757. result.m[5] = tan * aspect;
  1758. }
  1759. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1760. result.m[8] = result.m[9] = 0.0;
  1761. result.m[10] = -zfar / (znear - zfar);
  1762. result.m[11] = 1.0;
  1763. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1764. result.m[14] = (znear * zfar) / (znear - zfar);
  1765. };
  1766. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1767. var cw = viewport.width;
  1768. var ch = viewport.height;
  1769. var cx = viewport.x;
  1770. var cy = viewport.y;
  1771. 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);
  1772. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1773. };
  1774. Matrix.Transpose = function (matrix) {
  1775. var result = new Matrix();
  1776. result.m[0] = matrix.m[0];
  1777. result.m[1] = matrix.m[4];
  1778. result.m[2] = matrix.m[8];
  1779. result.m[3] = matrix.m[12];
  1780. result.m[4] = matrix.m[1];
  1781. result.m[5] = matrix.m[5];
  1782. result.m[6] = matrix.m[9];
  1783. result.m[7] = matrix.m[13];
  1784. result.m[8] = matrix.m[2];
  1785. result.m[9] = matrix.m[6];
  1786. result.m[10] = matrix.m[10];
  1787. result.m[11] = matrix.m[14];
  1788. result.m[12] = matrix.m[3];
  1789. result.m[13] = matrix.m[7];
  1790. result.m[14] = matrix.m[11];
  1791. result.m[15] = matrix.m[15];
  1792. return result;
  1793. };
  1794. Matrix.Reflection = function (plane) {
  1795. var matrix = new Matrix();
  1796. Matrix.ReflectionToRef(plane, matrix);
  1797. return matrix;
  1798. };
  1799. Matrix.ReflectionToRef = function (plane, result) {
  1800. plane.normalize();
  1801. var x = plane.normal.x;
  1802. var y = plane.normal.y;
  1803. var z = plane.normal.z;
  1804. var temp = -2 * x;
  1805. var temp2 = -2 * y;
  1806. var temp3 = -2 * z;
  1807. result.m[0] = (temp * x) + 1;
  1808. result.m[1] = temp2 * x;
  1809. result.m[2] = temp3 * x;
  1810. result.m[3] = 0.0;
  1811. result.m[4] = temp * y;
  1812. result.m[5] = (temp2 * y) + 1;
  1813. result.m[6] = temp3 * y;
  1814. result.m[7] = 0.0;
  1815. result.m[8] = temp * z;
  1816. result.m[9] = temp2 * z;
  1817. result.m[10] = (temp3 * z) + 1;
  1818. result.m[11] = 0.0;
  1819. result.m[12] = temp * plane.d;
  1820. result.m[13] = temp2 * plane.d;
  1821. result.m[14] = temp3 * plane.d;
  1822. result.m[15] = 1.0;
  1823. };
  1824. Matrix._tempQuaternion = new Quaternion();
  1825. Matrix._xAxis = Vector3.Zero();
  1826. Matrix._yAxis = Vector3.Zero();
  1827. Matrix._zAxis = Vector3.Zero();
  1828. return Matrix;
  1829. })();
  1830. BABYLON.Matrix = Matrix;
  1831. var Plane = (function () {
  1832. function Plane(a, b, c, d) {
  1833. this.normal = new Vector3(a, b, c);
  1834. this.d = d;
  1835. }
  1836. Plane.prototype.asArray = function () {
  1837. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1838. };
  1839. // Methods
  1840. Plane.prototype.clone = function () {
  1841. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1842. };
  1843. Plane.prototype.normalize = function () {
  1844. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1845. var magnitude = 0;
  1846. if (norm !== 0) {
  1847. magnitude = 1.0 / norm;
  1848. }
  1849. this.normal.x *= magnitude;
  1850. this.normal.y *= magnitude;
  1851. this.normal.z *= magnitude;
  1852. this.d *= magnitude;
  1853. return this;
  1854. };
  1855. Plane.prototype.transform = function (transformation) {
  1856. var transposedMatrix = Matrix.Transpose(transformation);
  1857. var x = this.normal.x;
  1858. var y = this.normal.y;
  1859. var z = this.normal.z;
  1860. var d = this.d;
  1861. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1862. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1863. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1864. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1865. return new Plane(normalX, normalY, normalZ, finalD);
  1866. };
  1867. Plane.prototype.dotCoordinate = function (point) {
  1868. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1869. };
  1870. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1871. var x1 = point2.x - point1.x;
  1872. var y1 = point2.y - point1.y;
  1873. var z1 = point2.z - point1.z;
  1874. var x2 = point3.x - point1.x;
  1875. var y2 = point3.y - point1.y;
  1876. var z2 = point3.z - point1.z;
  1877. var yz = (y1 * z2) - (z1 * y2);
  1878. var xz = (z1 * x2) - (x1 * z2);
  1879. var xy = (x1 * y2) - (y1 * x2);
  1880. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1881. var invPyth;
  1882. if (pyth !== 0) {
  1883. invPyth = 1.0 / pyth;
  1884. }
  1885. else {
  1886. invPyth = 0;
  1887. }
  1888. this.normal.x = yz * invPyth;
  1889. this.normal.y = xz * invPyth;
  1890. this.normal.z = xy * invPyth;
  1891. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1892. return this;
  1893. };
  1894. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1895. var dot = Vector3.Dot(this.normal, direction);
  1896. return (dot <= epsilon);
  1897. };
  1898. Plane.prototype.signedDistanceTo = function (point) {
  1899. return Vector3.Dot(point, this.normal) + this.d;
  1900. };
  1901. // Statics
  1902. Plane.FromArray = function (array) {
  1903. return new Plane(array[0], array[1], array[2], array[3]);
  1904. };
  1905. Plane.FromPoints = function (point1, point2, point3) {
  1906. var result = new Plane(0, 0, 0, 0);
  1907. result.copyFromPoints(point1, point2, point3);
  1908. return result;
  1909. };
  1910. Plane.FromPositionAndNormal = function (origin, normal) {
  1911. var result = new Plane(0, 0, 0, 0);
  1912. normal.normalize();
  1913. result.normal = normal;
  1914. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1915. return result;
  1916. };
  1917. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1918. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1919. return Vector3.Dot(point, normal) + d;
  1920. };
  1921. return Plane;
  1922. })();
  1923. BABYLON.Plane = Plane;
  1924. var Viewport = (function () {
  1925. function Viewport(x, y, width, height) {
  1926. this.x = x;
  1927. this.y = y;
  1928. this.width = width;
  1929. this.height = height;
  1930. }
  1931. Viewport.prototype.toGlobal = function (engine) {
  1932. var width = engine.getRenderWidth();
  1933. var height = engine.getRenderHeight();
  1934. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1935. };
  1936. return Viewport;
  1937. })();
  1938. BABYLON.Viewport = Viewport;
  1939. var Frustum = (function () {
  1940. function Frustum() {
  1941. }
  1942. Frustum.GetPlanes = function (transform) {
  1943. var frustumPlanes = [];
  1944. for (var index = 0; index < 6; index++) {
  1945. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1946. }
  1947. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1948. return frustumPlanes;
  1949. };
  1950. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1951. // Near
  1952. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1953. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1954. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1955. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1956. frustumPlanes[0].normalize();
  1957. // Far
  1958. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1959. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1960. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1961. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1962. frustumPlanes[1].normalize();
  1963. // Left
  1964. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1965. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1966. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1967. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1968. frustumPlanes[2].normalize();
  1969. // Right
  1970. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1971. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1972. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1973. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1974. frustumPlanes[3].normalize();
  1975. // Top
  1976. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1977. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1978. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1979. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1980. frustumPlanes[4].normalize();
  1981. // Bottom
  1982. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1983. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1984. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1985. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1986. frustumPlanes[5].normalize();
  1987. };
  1988. return Frustum;
  1989. })();
  1990. BABYLON.Frustum = Frustum;
  1991. var Ray = (function () {
  1992. function Ray(origin, direction, length) {
  1993. if (length === void 0) { length = Number.MAX_VALUE; }
  1994. this.origin = origin;
  1995. this.direction = direction;
  1996. this.length = length;
  1997. }
  1998. // Methods
  1999. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2000. var d = 0.0;
  2001. var maxValue = Number.MAX_VALUE;
  2002. if (Math.abs(this.direction.x) < 0.0000001) {
  2003. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2004. return false;
  2005. }
  2006. }
  2007. else {
  2008. var inv = 1.0 / this.direction.x;
  2009. var min = (minimum.x - this.origin.x) * inv;
  2010. var max = (maximum.x - this.origin.x) * inv;
  2011. if (max === -Infinity) {
  2012. max = Infinity;
  2013. }
  2014. if (min > max) {
  2015. var temp = min;
  2016. min = max;
  2017. max = temp;
  2018. }
  2019. d = Math.max(min, d);
  2020. maxValue = Math.min(max, maxValue);
  2021. if (d > maxValue) {
  2022. return false;
  2023. }
  2024. }
  2025. if (Math.abs(this.direction.y) < 0.0000001) {
  2026. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2027. return false;
  2028. }
  2029. }
  2030. else {
  2031. inv = 1.0 / this.direction.y;
  2032. min = (minimum.y - this.origin.y) * inv;
  2033. max = (maximum.y - this.origin.y) * inv;
  2034. if (max === -Infinity) {
  2035. max = Infinity;
  2036. }
  2037. if (min > max) {
  2038. temp = min;
  2039. min = max;
  2040. max = temp;
  2041. }
  2042. d = Math.max(min, d);
  2043. maxValue = Math.min(max, maxValue);
  2044. if (d > maxValue) {
  2045. return false;
  2046. }
  2047. }
  2048. if (Math.abs(this.direction.z) < 0.0000001) {
  2049. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2050. return false;
  2051. }
  2052. }
  2053. else {
  2054. inv = 1.0 / this.direction.z;
  2055. min = (minimum.z - this.origin.z) * inv;
  2056. max = (maximum.z - this.origin.z) * inv;
  2057. if (max === -Infinity) {
  2058. max = Infinity;
  2059. }
  2060. if (min > max) {
  2061. temp = min;
  2062. min = max;
  2063. max = temp;
  2064. }
  2065. d = Math.max(min, d);
  2066. maxValue = Math.min(max, maxValue);
  2067. if (d > maxValue) {
  2068. return false;
  2069. }
  2070. }
  2071. return true;
  2072. };
  2073. Ray.prototype.intersectsBox = function (box) {
  2074. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2075. };
  2076. Ray.prototype.intersectsSphere = function (sphere) {
  2077. var x = sphere.center.x - this.origin.x;
  2078. var y = sphere.center.y - this.origin.y;
  2079. var z = sphere.center.z - this.origin.z;
  2080. var pyth = (x * x) + (y * y) + (z * z);
  2081. var rr = sphere.radius * sphere.radius;
  2082. if (pyth <= rr) {
  2083. return true;
  2084. }
  2085. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2086. if (dot < 0.0) {
  2087. return false;
  2088. }
  2089. var temp = pyth - (dot * dot);
  2090. return temp <= rr;
  2091. };
  2092. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2093. if (!this._edge1) {
  2094. this._edge1 = Vector3.Zero();
  2095. this._edge2 = Vector3.Zero();
  2096. this._pvec = Vector3.Zero();
  2097. this._tvec = Vector3.Zero();
  2098. this._qvec = Vector3.Zero();
  2099. }
  2100. vertex1.subtractToRef(vertex0, this._edge1);
  2101. vertex2.subtractToRef(vertex0, this._edge2);
  2102. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2103. var det = Vector3.Dot(this._edge1, this._pvec);
  2104. if (det === 0) {
  2105. return null;
  2106. }
  2107. var invdet = 1 / det;
  2108. this.origin.subtractToRef(vertex0, this._tvec);
  2109. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2110. if (bu < 0 || bu > 1.0) {
  2111. return null;
  2112. }
  2113. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2114. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2115. if (bv < 0 || bu + bv > 1.0) {
  2116. return null;
  2117. }
  2118. //check if the distance is longer than the predefined length.
  2119. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2120. if (distance > this.length) {
  2121. return null;
  2122. }
  2123. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2124. };
  2125. // Statics
  2126. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2127. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2128. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2129. var direction = end.subtract(start);
  2130. direction.normalize();
  2131. return new Ray(start, direction);
  2132. };
  2133. /**
  2134. * 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
  2135. * transformed to the given world matrix.
  2136. * @param origin The origin point
  2137. * @param end The end point
  2138. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2139. */
  2140. Ray.CreateNewFromTo = function (origin, end, world) {
  2141. if (world === void 0) { world = Matrix.Identity(); }
  2142. var direction = end.subtract(origin);
  2143. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2144. direction.normalize();
  2145. return Ray.Transform(new Ray(origin, direction, length), world);
  2146. };
  2147. Ray.Transform = function (ray, matrix) {
  2148. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2149. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2150. return new Ray(newOrigin, newDirection, ray.length);
  2151. };
  2152. return Ray;
  2153. })();
  2154. BABYLON.Ray = Ray;
  2155. (function (Space) {
  2156. Space[Space["LOCAL"] = 0] = "LOCAL";
  2157. Space[Space["WORLD"] = 1] = "WORLD";
  2158. })(BABYLON.Space || (BABYLON.Space = {}));
  2159. var Space = BABYLON.Space;
  2160. var Axis = (function () {
  2161. function Axis() {
  2162. }
  2163. Axis.X = new Vector3(1, 0, 0);
  2164. Axis.Y = new Vector3(0, 1, 0);
  2165. Axis.Z = new Vector3(0, 0, 1);
  2166. return Axis;
  2167. })();
  2168. BABYLON.Axis = Axis;
  2169. ;
  2170. var BezierCurve = (function () {
  2171. function BezierCurve() {
  2172. }
  2173. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2174. // Extract X (which is equal to time here)
  2175. var f0 = 1 - 3 * x2 + 3 * x1;
  2176. var f1 = 3 * x2 - 6 * x1;
  2177. var f2 = 3 * x1;
  2178. var refinedT = t;
  2179. for (var i = 0; i < 5; i++) {
  2180. var refinedT2 = refinedT * refinedT;
  2181. var refinedT3 = refinedT2 * refinedT;
  2182. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2183. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2184. refinedT -= (x - t) * slope;
  2185. refinedT = Math.min(1, Math.max(0, refinedT));
  2186. }
  2187. // Resolve cubic bezier for the given x
  2188. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2189. };
  2190. return BezierCurve;
  2191. })();
  2192. BABYLON.BezierCurve = BezierCurve;
  2193. (function (Orientation) {
  2194. Orientation[Orientation["CW"] = 0] = "CW";
  2195. Orientation[Orientation["CCW"] = 1] = "CCW";
  2196. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2197. var Orientation = BABYLON.Orientation;
  2198. var Angle = (function () {
  2199. function Angle(radians) {
  2200. var _this = this;
  2201. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2202. this.radians = function () { return _this._radians; };
  2203. this._radians = radians;
  2204. if (this._radians < 0)
  2205. this._radians += (2 * Math.PI);
  2206. }
  2207. Angle.BetweenTwoPoints = function (a, b) {
  2208. var delta = b.subtract(a);
  2209. var theta = Math.atan2(delta.y, delta.x);
  2210. return new Angle(theta);
  2211. };
  2212. Angle.FromRadians = function (radians) {
  2213. return new Angle(radians);
  2214. };
  2215. Angle.FromDegrees = function (degrees) {
  2216. return new Angle(degrees * Math.PI / 180);
  2217. };
  2218. return Angle;
  2219. })();
  2220. BABYLON.Angle = Angle;
  2221. var Arc2 = (function () {
  2222. function Arc2(startPoint, midPoint, endPoint) {
  2223. this.startPoint = startPoint;
  2224. this.midPoint = midPoint;
  2225. this.endPoint = endPoint;
  2226. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2227. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2228. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2229. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2230. 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);
  2231. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2232. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2233. var a1 = this.startAngle.degrees();
  2234. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2235. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2236. // angles correction
  2237. if (a2 - a1 > +180.0)
  2238. a2 -= 360.0;
  2239. if (a2 - a1 < -180.0)
  2240. a2 += 360.0;
  2241. if (a3 - a2 > +180.0)
  2242. a3 -= 360.0;
  2243. if (a3 - a2 < -180.0)
  2244. a3 += 360.0;
  2245. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2246. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2247. }
  2248. return Arc2;
  2249. })();
  2250. BABYLON.Arc2 = Arc2;
  2251. var PathCursor = (function () {
  2252. function PathCursor(path) {
  2253. this.path = path;
  2254. this._onchange = new Array();
  2255. this.value = 0;
  2256. this.animations = new Array();
  2257. }
  2258. PathCursor.prototype.getPoint = function () {
  2259. var point = this.path.getPointAtLengthPosition(this.value);
  2260. return new Vector3(point.x, 0, point.y);
  2261. };
  2262. PathCursor.prototype.moveAhead = function (step) {
  2263. if (step === void 0) { step = 0.002; }
  2264. this.move(step);
  2265. return this;
  2266. };
  2267. PathCursor.prototype.moveBack = function (step) {
  2268. if (step === void 0) { step = 0.002; }
  2269. this.move(-step);
  2270. return this;
  2271. };
  2272. PathCursor.prototype.move = function (step) {
  2273. if (Math.abs(step) > 1) {
  2274. throw "step size should be less than 1.";
  2275. }
  2276. this.value += step;
  2277. this.ensureLimits();
  2278. this.raiseOnChange();
  2279. return this;
  2280. };
  2281. PathCursor.prototype.ensureLimits = function () {
  2282. while (this.value > 1) {
  2283. this.value -= 1;
  2284. }
  2285. while (this.value < 0) {
  2286. this.value += 1;
  2287. }
  2288. return this;
  2289. };
  2290. // used by animation engine
  2291. PathCursor.prototype.markAsDirty = function (propertyName) {
  2292. this.ensureLimits();
  2293. this.raiseOnChange();
  2294. return this;
  2295. };
  2296. PathCursor.prototype.raiseOnChange = function () {
  2297. var _this = this;
  2298. this._onchange.forEach(function (f) { return f(_this); });
  2299. return this;
  2300. };
  2301. PathCursor.prototype.onchange = function (f) {
  2302. this._onchange.push(f);
  2303. return this;
  2304. };
  2305. return PathCursor;
  2306. })();
  2307. BABYLON.PathCursor = PathCursor;
  2308. var Path2 = (function () {
  2309. function Path2(x, y) {
  2310. this._points = [];
  2311. this._length = 0;
  2312. this.closed = false;
  2313. this._points.push(new Vector2(x, y));
  2314. }
  2315. Path2.prototype.addLineTo = function (x, y) {
  2316. if (closed) {
  2317. BABYLON.Tools.Error("cannot add lines to closed paths");
  2318. return this;
  2319. }
  2320. var newPoint = new Vector2(x, y);
  2321. var previousPoint = this._points[this._points.length - 1];
  2322. this._points.push(newPoint);
  2323. this._length += newPoint.subtract(previousPoint).length();
  2324. return this;
  2325. };
  2326. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2327. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2328. if (closed) {
  2329. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2330. return this;
  2331. }
  2332. var startPoint = this._points[this._points.length - 1];
  2333. var midPoint = new Vector2(midX, midY);
  2334. var endPoint = new Vector2(endX, endY);
  2335. var arc = new Arc2(startPoint, midPoint, endPoint);
  2336. var increment = arc.angle.radians() / numberOfSegments;
  2337. if (arc.orientation === 0 /* CW */)
  2338. increment *= -1;
  2339. var currentAngle = arc.startAngle.radians() + increment;
  2340. for (var i = 0; i < numberOfSegments; i++) {
  2341. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2342. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2343. this.addLineTo(x, y);
  2344. currentAngle += increment;
  2345. }
  2346. return this;
  2347. };
  2348. Path2.prototype.close = function () {
  2349. this.closed = true;
  2350. return this;
  2351. };
  2352. Path2.prototype.length = function () {
  2353. var result = this._length;
  2354. if (!this.closed) {
  2355. var lastPoint = this._points[this._points.length - 1];
  2356. var firstPoint = this._points[0];
  2357. result += (firstPoint.subtract(lastPoint).length());
  2358. }
  2359. return result;
  2360. };
  2361. Path2.prototype.getPoints = function () {
  2362. return this._points;
  2363. };
  2364. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2365. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2366. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2367. return Vector2.Zero();
  2368. }
  2369. var lengthPosition = normalizedLengthPosition * this.length();
  2370. var previousOffset = 0;
  2371. for (var i = 0; i < this._points.length; i++) {
  2372. var j = (i + 1) % this._points.length;
  2373. var a = this._points[i];
  2374. var b = this._points[j];
  2375. var bToA = b.subtract(a);
  2376. var nextOffset = (bToA.length() + previousOffset);
  2377. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2378. var dir = bToA.normalize();
  2379. var localOffset = lengthPosition - previousOffset;
  2380. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2381. }
  2382. previousOffset = nextOffset;
  2383. }
  2384. BABYLON.Tools.Error("internal error");
  2385. return Vector2.Zero();
  2386. };
  2387. Path2.StartingAt = function (x, y) {
  2388. return new Path2(x, y);
  2389. };
  2390. return Path2;
  2391. })();
  2392. BABYLON.Path2 = Path2;
  2393. })(BABYLON || (BABYLON = {}));
  2394. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2395. (function (BABYLON) {
  2396. // Screenshots
  2397. var screenshotCanvas;
  2398. var cloneValue = function (source, destinationObject) {
  2399. if (!source)
  2400. return null;
  2401. if (source instanceof BABYLON.Mesh) {
  2402. return null;
  2403. }
  2404. if (source instanceof BABYLON.SubMesh) {
  2405. return source.clone(destinationObject);
  2406. }
  2407. else if (source.clone) {
  2408. return source.clone();
  2409. }
  2410. return null;
  2411. };
  2412. var Tools = (function () {
  2413. function Tools() {
  2414. }
  2415. Tools.GetFilename = function (path) {
  2416. var index = path.lastIndexOf("/");
  2417. if (index < 0)
  2418. return path;
  2419. return path.substring(index + 1);
  2420. };
  2421. Tools.GetDOMTextContent = function (element) {
  2422. var result = "";
  2423. var child = element.firstChild;
  2424. while (child) {
  2425. if (child.nodeType === 3) {
  2426. result += child.textContent;
  2427. }
  2428. child = child.nextSibling;
  2429. }
  2430. return result;
  2431. };
  2432. Tools.ToDegrees = function (angle) {
  2433. return angle * 180 / Math.PI;
  2434. };
  2435. Tools.ToRadians = function (angle) {
  2436. return angle * Math.PI / 180;
  2437. };
  2438. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2439. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2440. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2441. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2442. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2443. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2444. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2445. }
  2446. return {
  2447. minimum: minimum,
  2448. maximum: maximum
  2449. };
  2450. };
  2451. Tools.ExtractMinAndMax = function (positions, start, count) {
  2452. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2453. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2454. for (var index = start; index < start + count; index++) {
  2455. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2456. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2457. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2458. }
  2459. return {
  2460. minimum: minimum,
  2461. maximum: maximum
  2462. };
  2463. };
  2464. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2465. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2466. return undefined;
  2467. return Array.isArray(obj) ? obj : [obj];
  2468. };
  2469. // Misc.
  2470. Tools.GetPointerPrefix = function () {
  2471. var eventPrefix = "pointer";
  2472. // Check if hand.js is referenced or if the browser natively supports pointer events
  2473. if (!navigator.pointerEnabled) {
  2474. eventPrefix = "mouse";
  2475. }
  2476. return eventPrefix;
  2477. };
  2478. Tools.QueueNewFrame = function (func) {
  2479. if (window.requestAnimationFrame)
  2480. window.requestAnimationFrame(func);
  2481. else if (window.msRequestAnimationFrame)
  2482. window.msRequestAnimationFrame(func);
  2483. else if (window.webkitRequestAnimationFrame)
  2484. window.webkitRequestAnimationFrame(func);
  2485. else if (window.mozRequestAnimationFrame)
  2486. window.mozRequestAnimationFrame(func);
  2487. else if (window.oRequestAnimationFrame)
  2488. window.oRequestAnimationFrame(func);
  2489. else {
  2490. window.setTimeout(func, 16);
  2491. }
  2492. };
  2493. Tools.RequestFullscreen = function (element) {
  2494. if (element.requestFullscreen)
  2495. element.requestFullscreen();
  2496. else if (element.msRequestFullscreen)
  2497. element.msRequestFullscreen();
  2498. else if (element.webkitRequestFullscreen)
  2499. element.webkitRequestFullscreen();
  2500. else if (element.mozRequestFullScreen)
  2501. element.mozRequestFullScreen();
  2502. };
  2503. Tools.ExitFullscreen = function () {
  2504. if (document.exitFullscreen) {
  2505. document.exitFullscreen();
  2506. }
  2507. else if (document.mozCancelFullScreen) {
  2508. document.mozCancelFullScreen();
  2509. }
  2510. else if (document.webkitCancelFullScreen) {
  2511. document.webkitCancelFullScreen();
  2512. }
  2513. else if (document.msCancelFullScreen) {
  2514. document.msCancelFullScreen();
  2515. }
  2516. };
  2517. // External files
  2518. Tools.CleanUrl = function (url) {
  2519. url = url.replace(/#/mg, "%23");
  2520. return url;
  2521. };
  2522. Tools.LoadImage = function (url, onload, onerror, database) {
  2523. url = Tools.CleanUrl(url);
  2524. var img = new Image();
  2525. if (url.substr(0, 5) !== "data:")
  2526. img.crossOrigin = 'anonymous';
  2527. img.onload = function () {
  2528. onload(img);
  2529. };
  2530. img.onerror = function (err) {
  2531. onerror(img, err);
  2532. };
  2533. var noIndexedDB = function () {
  2534. img.src = url;
  2535. };
  2536. var loadFromIndexedDB = function () {
  2537. database.loadImageFromDB(url, img);
  2538. };
  2539. //ANY database to do!
  2540. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2541. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2542. }
  2543. else {
  2544. if (url.indexOf("file:") === -1) {
  2545. noIndexedDB();
  2546. }
  2547. else {
  2548. try {
  2549. var textureName = url.substring(5);
  2550. var blobURL;
  2551. try {
  2552. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2553. }
  2554. catch (ex) {
  2555. // Chrome doesn't support oneTimeOnly parameter
  2556. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2557. }
  2558. img.src = blobURL;
  2559. }
  2560. catch (e) {
  2561. Tools.Log("Error while trying to load texture: " + textureName);
  2562. img.src = null;
  2563. }
  2564. }
  2565. }
  2566. return img;
  2567. };
  2568. //ANY
  2569. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2570. url = Tools.CleanUrl(url);
  2571. var noIndexedDB = function () {
  2572. var request = new XMLHttpRequest();
  2573. var loadUrl = Tools.BaseUrl + url;
  2574. request.open('GET', loadUrl, true);
  2575. if (useArrayBuffer) {
  2576. request.responseType = "arraybuffer";
  2577. }
  2578. request.onprogress = progressCallBack;
  2579. request.onreadystatechange = function () {
  2580. if (request.readyState === 4) {
  2581. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2582. callback(!useArrayBuffer ? request.responseText : request.response);
  2583. }
  2584. else {
  2585. if (onError) {
  2586. onError();
  2587. }
  2588. else {
  2589. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2590. }
  2591. }
  2592. }
  2593. };
  2594. request.send(null);
  2595. };
  2596. var loadFromIndexedDB = function () {
  2597. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2598. };
  2599. if (url.indexOf("file:") !== -1) {
  2600. var fileName = url.substring(5);
  2601. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2602. }
  2603. else {
  2604. // Caching all files
  2605. if (database && database.enableSceneOffline) {
  2606. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2607. }
  2608. else {
  2609. noIndexedDB();
  2610. }
  2611. }
  2612. };
  2613. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2614. var reader = new FileReader();
  2615. reader.onload = function (e) {
  2616. callback(e.target.result);
  2617. };
  2618. reader.onprogress = progressCallback;
  2619. reader.readAsDataURL(fileToLoad);
  2620. };
  2621. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2622. var reader = new FileReader();
  2623. reader.onload = function (e) {
  2624. callback(e.target.result);
  2625. };
  2626. reader.onprogress = progressCallBack;
  2627. if (!useArrayBuffer) {
  2628. // Asynchronous read
  2629. reader.readAsText(fileToLoad);
  2630. }
  2631. else {
  2632. reader.readAsArrayBuffer(fileToLoad);
  2633. }
  2634. };
  2635. // Misc.
  2636. Tools.Clamp = function (value, min, max) {
  2637. if (min === void 0) { min = 0; }
  2638. if (max === void 0) { max = 1; }
  2639. return Math.min(max, Math.max(min, value));
  2640. };
  2641. // Returns -1 when value is a negative number and
  2642. // +1 when value is a positive number.
  2643. Tools.Sign = function (value) {
  2644. value = +value; // convert to a number
  2645. if (value === 0 || isNaN(value))
  2646. return value;
  2647. return value > 0 ? 1 : -1;
  2648. };
  2649. Tools.Format = function (value, decimals) {
  2650. if (decimals === void 0) { decimals = 2; }
  2651. return value.toFixed(decimals);
  2652. };
  2653. Tools.CheckExtends = function (v, min, max) {
  2654. if (v.x < min.x)
  2655. min.x = v.x;
  2656. if (v.y < min.y)
  2657. min.y = v.y;
  2658. if (v.z < min.z)
  2659. min.z = v.z;
  2660. if (v.x > max.x)
  2661. max.x = v.x;
  2662. if (v.y > max.y)
  2663. max.y = v.y;
  2664. if (v.z > max.z)
  2665. max.z = v.z;
  2666. };
  2667. Tools.WithinEpsilon = function (a, b, epsilon) {
  2668. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  2669. var num = a - b;
  2670. return -epsilon <= num && num <= epsilon;
  2671. };
  2672. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2673. for (var prop in source) {
  2674. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2675. continue;
  2676. }
  2677. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2678. continue;
  2679. }
  2680. var sourceValue = source[prop];
  2681. var typeOfSourceValue = typeof sourceValue;
  2682. if (typeOfSourceValue === "function") {
  2683. continue;
  2684. }
  2685. if (typeOfSourceValue === "object") {
  2686. if (sourceValue instanceof Array) {
  2687. destination[prop] = [];
  2688. if (sourceValue.length > 0) {
  2689. if (typeof sourceValue[0] == "object") {
  2690. for (var index = 0; index < sourceValue.length; index++) {
  2691. var clonedValue = cloneValue(sourceValue[index], destination);
  2692. if (destination[prop].indexOf(clonedValue) === -1) {
  2693. destination[prop].push(clonedValue);
  2694. }
  2695. }
  2696. }
  2697. else {
  2698. destination[prop] = sourceValue.slice(0);
  2699. }
  2700. }
  2701. }
  2702. else {
  2703. destination[prop] = cloneValue(sourceValue, destination);
  2704. }
  2705. }
  2706. else {
  2707. destination[prop] = sourceValue;
  2708. }
  2709. }
  2710. };
  2711. Tools.IsEmpty = function (obj) {
  2712. for (var i in obj) {
  2713. return false;
  2714. }
  2715. return true;
  2716. };
  2717. Tools.RegisterTopRootEvents = function (events) {
  2718. for (var index = 0; index < events.length; index++) {
  2719. var event = events[index];
  2720. window.addEventListener(event.name, event.handler, false);
  2721. try {
  2722. if (window.parent) {
  2723. window.parent.addEventListener(event.name, event.handler, false);
  2724. }
  2725. }
  2726. catch (e) {
  2727. }
  2728. }
  2729. };
  2730. Tools.UnregisterTopRootEvents = function (events) {
  2731. for (var index = 0; index < events.length; index++) {
  2732. var event = events[index];
  2733. window.removeEventListener(event.name, event.handler);
  2734. try {
  2735. if (window.parent) {
  2736. window.parent.removeEventListener(event.name, event.handler);
  2737. }
  2738. }
  2739. catch (e) {
  2740. }
  2741. }
  2742. };
  2743. Tools.CreateScreenshot = function (engine, camera, size) {
  2744. var width;
  2745. var height;
  2746. var scene = camera.getScene();
  2747. var previousCamera = null;
  2748. if (scene.activeCamera !== camera) {
  2749. previousCamera = scene.activeCamera;
  2750. scene.activeCamera = camera;
  2751. }
  2752. //If a precision value is specified
  2753. if (size.precision) {
  2754. width = Math.round(engine.getRenderWidth() * size.precision);
  2755. height = Math.round(width / engine.getAspectRatio(camera));
  2756. size = { width: width, height: height };
  2757. }
  2758. else if (size.width && size.height) {
  2759. width = size.width;
  2760. height = size.height;
  2761. }
  2762. else if (size.width && !size.height) {
  2763. width = size.width;
  2764. height = Math.round(width / engine.getAspectRatio(camera));
  2765. size = { width: width, height: height };
  2766. }
  2767. else if (size.height && !size.width) {
  2768. height = size.height;
  2769. width = Math.round(height * engine.getAspectRatio(camera));
  2770. size = { width: width, height: height };
  2771. }
  2772. else if (!isNaN(size)) {
  2773. height = size;
  2774. width = size;
  2775. }
  2776. else {
  2777. Tools.Error("Invalid 'size' parameter !");
  2778. return;
  2779. }
  2780. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2781. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  2782. texture.renderList = scene.meshes;
  2783. texture.onAfterRender = function () {
  2784. // Read the contents of the framebuffer
  2785. var numberOfChannelsByLine = width * 4;
  2786. var halfHeight = height / 2;
  2787. //Reading datas from WebGL
  2788. var data = engine.readPixels(0, 0, width, height);
  2789. for (var i = 0; i < halfHeight; i++) {
  2790. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2791. var currentCell = j + i * numberOfChannelsByLine;
  2792. var targetLine = height - i - 1;
  2793. var targetCell = j + targetLine * numberOfChannelsByLine;
  2794. var temp = data[currentCell];
  2795. data[currentCell] = data[targetCell];
  2796. data[targetCell] = temp;
  2797. }
  2798. }
  2799. // Create a 2D canvas to store the result
  2800. if (!screenshotCanvas) {
  2801. screenshotCanvas = document.createElement('canvas');
  2802. }
  2803. screenshotCanvas.width = width;
  2804. screenshotCanvas.height = height;
  2805. var context = screenshotCanvas.getContext('2d');
  2806. // Copy the pixels to a 2D canvas
  2807. var imageData = context.createImageData(width, height);
  2808. imageData.data.set(data);
  2809. context.putImageData(imageData, 0, 0);
  2810. var base64Image = screenshotCanvas.toDataURL();
  2811. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2812. if (("download" in document.createElement("a"))) {
  2813. var a = window.document.createElement("a");
  2814. a.href = base64Image;
  2815. var date = new Date();
  2816. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2817. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2818. window.document.body.appendChild(a);
  2819. a.addEventListener("click", function () {
  2820. a.parentElement.removeChild(a);
  2821. });
  2822. a.click();
  2823. }
  2824. else {
  2825. var newWindow = window.open("");
  2826. var img = newWindow.document.createElement("img");
  2827. img.src = base64Image;
  2828. newWindow.document.body.appendChild(img);
  2829. }
  2830. };
  2831. scene.incrementRenderId();
  2832. texture.render(true);
  2833. texture.dispose();
  2834. if (previousCamera) {
  2835. scene.activeCamera = previousCamera;
  2836. }
  2837. };
  2838. // XHR response validator for local file scenario
  2839. Tools.ValidateXHRData = function (xhr, dataType) {
  2840. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  2841. if (dataType === void 0) { dataType = 7; }
  2842. try {
  2843. if (dataType & 1) {
  2844. if (xhr.responseText && xhr.responseText.length > 0) {
  2845. return true;
  2846. }
  2847. else if (dataType === 1) {
  2848. return false;
  2849. }
  2850. }
  2851. if (dataType & 2) {
  2852. // Check header width and height since there is no "TGA" magic number
  2853. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2854. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2855. return true;
  2856. }
  2857. else if (dataType === 2) {
  2858. return false;
  2859. }
  2860. }
  2861. if (dataType & 4) {
  2862. // Check for the "DDS" magic number
  2863. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2864. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  2865. return true;
  2866. }
  2867. else {
  2868. return false;
  2869. }
  2870. }
  2871. }
  2872. catch (e) {
  2873. }
  2874. return false;
  2875. };
  2876. Object.defineProperty(Tools, "NoneLogLevel", {
  2877. get: function () {
  2878. return Tools._NoneLogLevel;
  2879. },
  2880. enumerable: true,
  2881. configurable: true
  2882. });
  2883. Object.defineProperty(Tools, "MessageLogLevel", {
  2884. get: function () {
  2885. return Tools._MessageLogLevel;
  2886. },
  2887. enumerable: true,
  2888. configurable: true
  2889. });
  2890. Object.defineProperty(Tools, "WarningLogLevel", {
  2891. get: function () {
  2892. return Tools._WarningLogLevel;
  2893. },
  2894. enumerable: true,
  2895. configurable: true
  2896. });
  2897. Object.defineProperty(Tools, "ErrorLogLevel", {
  2898. get: function () {
  2899. return Tools._ErrorLogLevel;
  2900. },
  2901. enumerable: true,
  2902. configurable: true
  2903. });
  2904. Object.defineProperty(Tools, "AllLogLevel", {
  2905. get: function () {
  2906. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2907. },
  2908. enumerable: true,
  2909. configurable: true
  2910. });
  2911. Tools._AddLogEntry = function (entry) {
  2912. Tools._LogCache = entry + Tools._LogCache;
  2913. if (Tools.OnNewCacheEntry) {
  2914. Tools.OnNewCacheEntry(entry);
  2915. }
  2916. };
  2917. Tools._FormatMessage = function (message) {
  2918. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  2919. var date = new Date();
  2920. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2921. };
  2922. Tools._LogDisabled = function (message) {
  2923. // nothing to do
  2924. };
  2925. Tools._LogEnabled = function (message) {
  2926. var formattedMessage = Tools._FormatMessage(message);
  2927. console.log("BJS - " + formattedMessage);
  2928. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2929. Tools._AddLogEntry(entry);
  2930. };
  2931. Tools._WarnDisabled = function (message) {
  2932. // nothing to do
  2933. };
  2934. Tools._WarnEnabled = function (message) {
  2935. var formattedMessage = Tools._FormatMessage(message);
  2936. console.warn("BJS - " + formattedMessage);
  2937. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2938. Tools._AddLogEntry(entry);
  2939. };
  2940. Tools._ErrorDisabled = function (message) {
  2941. // nothing to do
  2942. };
  2943. Tools._ErrorEnabled = function (message) {
  2944. var formattedMessage = Tools._FormatMessage(message);
  2945. console.error("BJS - " + formattedMessage);
  2946. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2947. Tools._AddLogEntry(entry);
  2948. };
  2949. Object.defineProperty(Tools, "LogCache", {
  2950. get: function () {
  2951. return Tools._LogCache;
  2952. },
  2953. enumerable: true,
  2954. configurable: true
  2955. });
  2956. Object.defineProperty(Tools, "LogLevels", {
  2957. set: function (level) {
  2958. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2959. Tools.Log = Tools._LogEnabled;
  2960. }
  2961. else {
  2962. Tools.Log = Tools._LogDisabled;
  2963. }
  2964. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2965. Tools.Warn = Tools._WarnEnabled;
  2966. }
  2967. else {
  2968. Tools.Warn = Tools._WarnDisabled;
  2969. }
  2970. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2971. Tools.Error = Tools._ErrorEnabled;
  2972. }
  2973. else {
  2974. Tools.Error = Tools._ErrorDisabled;
  2975. }
  2976. },
  2977. enumerable: true,
  2978. configurable: true
  2979. });
  2980. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2981. get: function () {
  2982. return Tools._PerformanceNoneLogLevel;
  2983. },
  2984. enumerable: true,
  2985. configurable: true
  2986. });
  2987. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2988. get: function () {
  2989. return Tools._PerformanceUserMarkLogLevel;
  2990. },
  2991. enumerable: true,
  2992. configurable: true
  2993. });
  2994. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2995. get: function () {
  2996. return Tools._PerformanceConsoleLogLevel;
  2997. },
  2998. enumerable: true,
  2999. configurable: true
  3000. });
  3001. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3002. set: function (level) {
  3003. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3004. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3005. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3006. return;
  3007. }
  3008. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3009. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3010. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3011. return;
  3012. }
  3013. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3014. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3015. },
  3016. enumerable: true,
  3017. configurable: true
  3018. });
  3019. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3020. };
  3021. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3022. };
  3023. Tools._StartUserMark = function (counterName, condition) {
  3024. if (condition === void 0) { condition = true; }
  3025. if (!condition || !Tools._performance.mark) {
  3026. return;
  3027. }
  3028. Tools._performance.mark(counterName + "-Begin");
  3029. };
  3030. Tools._EndUserMark = function (counterName, condition) {
  3031. if (condition === void 0) { condition = true; }
  3032. if (!condition || !Tools._performance.mark) {
  3033. return;
  3034. }
  3035. Tools._performance.mark(counterName + "-End");
  3036. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3037. };
  3038. Tools._StartPerformanceConsole = function (counterName, condition) {
  3039. if (condition === void 0) { condition = true; }
  3040. if (!condition) {
  3041. return;
  3042. }
  3043. Tools._StartUserMark(counterName, condition);
  3044. if (console.time) {
  3045. console.time(counterName);
  3046. }
  3047. };
  3048. Tools._EndPerformanceConsole = function (counterName, condition) {
  3049. if (condition === void 0) { condition = true; }
  3050. if (!condition) {
  3051. return;
  3052. }
  3053. Tools._EndUserMark(counterName, condition);
  3054. if (console.time) {
  3055. console.timeEnd(counterName);
  3056. }
  3057. };
  3058. Object.defineProperty(Tools, "Now", {
  3059. get: function () {
  3060. if (window.performance && window.performance.now) {
  3061. return window.performance.now();
  3062. }
  3063. return new Date().getTime();
  3064. },
  3065. enumerable: true,
  3066. configurable: true
  3067. });
  3068. // Deprecated
  3069. Tools.GetFps = function () {
  3070. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3071. return 0;
  3072. };
  3073. Tools.BaseUrl = "";
  3074. Tools.GetExponantOfTwo = function (value, max) {
  3075. var count = 1;
  3076. do {
  3077. count *= 2;
  3078. } while (count < value);
  3079. if (count > max)
  3080. count = max;
  3081. return count;
  3082. };
  3083. // Logs
  3084. Tools._NoneLogLevel = 0;
  3085. Tools._MessageLogLevel = 1;
  3086. Tools._WarningLogLevel = 2;
  3087. Tools._ErrorLogLevel = 4;
  3088. Tools._LogCache = "";
  3089. Tools.Log = Tools._LogEnabled;
  3090. Tools.Warn = Tools._WarnEnabled;
  3091. Tools.Error = Tools._ErrorEnabled;
  3092. // Performances
  3093. Tools._PerformanceNoneLogLevel = 0;
  3094. Tools._PerformanceUserMarkLogLevel = 1;
  3095. Tools._PerformanceConsoleLogLevel = 2;
  3096. Tools._performance = window.performance;
  3097. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3098. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3099. return Tools;
  3100. })();
  3101. BABYLON.Tools = Tools;
  3102. /**
  3103. * An implementation of a loop for asynchronous functions.
  3104. */
  3105. var AsyncLoop = (function () {
  3106. /**
  3107. * Constroctor.
  3108. * @param iterations the number of iterations.
  3109. * @param _fn the function to run each iteration
  3110. * @param _successCallback the callback that will be called upon succesful execution
  3111. * @param offset starting offset.
  3112. */
  3113. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3114. if (offset === void 0) { offset = 0; }
  3115. this.iterations = iterations;
  3116. this._fn = _fn;
  3117. this._successCallback = _successCallback;
  3118. this.index = offset - 1;
  3119. this._done = false;
  3120. }
  3121. /**
  3122. * Execute the next iteration. Must be called after the last iteration was finished.
  3123. */
  3124. AsyncLoop.prototype.executeNext = function () {
  3125. if (!this._done) {
  3126. if (this.index + 1 < this.iterations) {
  3127. ++this.index;
  3128. this._fn(this);
  3129. }
  3130. else {
  3131. this.breakLoop();
  3132. }
  3133. }
  3134. };
  3135. /**
  3136. * Break the loop and run the success callback.
  3137. */
  3138. AsyncLoop.prototype.breakLoop = function () {
  3139. this._done = true;
  3140. this._successCallback();
  3141. };
  3142. /**
  3143. * Helper function
  3144. */
  3145. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3146. if (offset === void 0) { offset = 0; }
  3147. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3148. loop.executeNext();
  3149. return loop;
  3150. };
  3151. /**
  3152. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3153. * @param iterations total number of iterations
  3154. * @param syncedIterations number of synchronous iterations in each async iteration.
  3155. * @param fn the function to call each iteration.
  3156. * @param callback a success call back that will be called when iterating stops.
  3157. * @param breakFunction a break condition (optional)
  3158. * @param timeout timeout settings for the setTimeout function. default - 0.
  3159. * @constructor
  3160. */
  3161. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3162. if (timeout === void 0) { timeout = 0; }
  3163. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3164. if (breakFunction && breakFunction())
  3165. loop.breakLoop();
  3166. else {
  3167. setTimeout(function () {
  3168. for (var i = 0; i < syncedIterations; ++i) {
  3169. var iteration = (loop.index * syncedIterations) + i;
  3170. if (iteration >= iterations)
  3171. break;
  3172. fn(iteration);
  3173. if (breakFunction && breakFunction()) {
  3174. loop.breakLoop();
  3175. break;
  3176. }
  3177. }
  3178. loop.executeNext();
  3179. }, timeout);
  3180. }
  3181. }, callback);
  3182. };
  3183. return AsyncLoop;
  3184. })();
  3185. BABYLON.AsyncLoop = AsyncLoop;
  3186. })(BABYLON || (BABYLON = {}));
  3187. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3188. (function (BABYLON) {
  3189. var _DepthCullingState = (function () {
  3190. function _DepthCullingState() {
  3191. this._isDepthTestDirty = false;
  3192. this._isDepthMaskDirty = false;
  3193. this._isDepthFuncDirty = false;
  3194. this._isCullFaceDirty = false;
  3195. this._isCullDirty = false;
  3196. }
  3197. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3198. get: function () {
  3199. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3200. },
  3201. enumerable: true,
  3202. configurable: true
  3203. });
  3204. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3205. get: function () {
  3206. return this._cullFace;
  3207. },
  3208. set: function (value) {
  3209. if (this._cullFace === value) {
  3210. return;
  3211. }
  3212. this._cullFace = value;
  3213. this._isCullFaceDirty = true;
  3214. },
  3215. enumerable: true,
  3216. configurable: true
  3217. });
  3218. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3219. get: function () {
  3220. return this._cull;
  3221. },
  3222. set: function (value) {
  3223. if (this._cull === value) {
  3224. return;
  3225. }
  3226. this._cull = value;
  3227. this._isCullDirty = true;
  3228. },
  3229. enumerable: true,
  3230. configurable: true
  3231. });
  3232. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3233. get: function () {
  3234. return this._depthFunc;
  3235. },
  3236. set: function (value) {
  3237. if (this._depthFunc === value) {
  3238. return;
  3239. }
  3240. this._depthFunc = value;
  3241. this._isDepthFuncDirty = true;
  3242. },
  3243. enumerable: true,
  3244. configurable: true
  3245. });
  3246. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3247. get: function () {
  3248. return this._depthMask;
  3249. },
  3250. set: function (value) {
  3251. if (this._depthMask === value) {
  3252. return;
  3253. }
  3254. this._depthMask = value;
  3255. this._isDepthMaskDirty = true;
  3256. },
  3257. enumerable: true,
  3258. configurable: true
  3259. });
  3260. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3261. get: function () {
  3262. return this._depthTest;
  3263. },
  3264. set: function (value) {
  3265. if (this._depthTest === value) {
  3266. return;
  3267. }
  3268. this._depthTest = value;
  3269. this._isDepthTestDirty = true;
  3270. },
  3271. enumerable: true,
  3272. configurable: true
  3273. });
  3274. _DepthCullingState.prototype.reset = function () {
  3275. this._depthMask = true;
  3276. this._depthTest = true;
  3277. this._depthFunc = null;
  3278. this._cull = null;
  3279. this._cullFace = null;
  3280. this._isDepthTestDirty = true;
  3281. this._isDepthMaskDirty = true;
  3282. this._isDepthFuncDirty = false;
  3283. this._isCullFaceDirty = false;
  3284. this._isCullDirty = false;
  3285. };
  3286. _DepthCullingState.prototype.apply = function (gl) {
  3287. if (!this.isDirty) {
  3288. return;
  3289. }
  3290. // Cull
  3291. if (this._isCullDirty) {
  3292. if (this.cull) {
  3293. gl.enable(gl.CULL_FACE);
  3294. }
  3295. else {
  3296. gl.disable(gl.CULL_FACE);
  3297. }
  3298. this._isCullDirty = false;
  3299. }
  3300. // Cull face
  3301. if (this._isCullFaceDirty) {
  3302. gl.cullFace(this.cullFace);
  3303. this._isCullFaceDirty = false;
  3304. }
  3305. // Depth mask
  3306. if (this._isDepthMaskDirty) {
  3307. gl.depthMask(this.depthMask);
  3308. this._isDepthMaskDirty = false;
  3309. }
  3310. // Depth test
  3311. if (this._isDepthTestDirty) {
  3312. if (this.depthTest) {
  3313. gl.enable(gl.DEPTH_TEST);
  3314. }
  3315. else {
  3316. gl.disable(gl.DEPTH_TEST);
  3317. }
  3318. this._isDepthTestDirty = false;
  3319. }
  3320. // Depth func
  3321. if (this._isDepthFuncDirty) {
  3322. gl.depthFunc(this.depthFunc);
  3323. this._isDepthFuncDirty = false;
  3324. }
  3325. };
  3326. return _DepthCullingState;
  3327. })();
  3328. BABYLON._DepthCullingState = _DepthCullingState;
  3329. var _AlphaState = (function () {
  3330. function _AlphaState() {
  3331. this._isAlphaBlendDirty = false;
  3332. this._isBlendFunctionParametersDirty = false;
  3333. this._alphaBlend = false;
  3334. this._blendFunctionParameters = new Array(4);
  3335. }
  3336. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3337. get: function () {
  3338. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3339. },
  3340. enumerable: true,
  3341. configurable: true
  3342. });
  3343. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3344. get: function () {
  3345. return this._alphaBlend;
  3346. },
  3347. set: function (value) {
  3348. if (this._alphaBlend === value) {
  3349. return;
  3350. }
  3351. this._alphaBlend = value;
  3352. this._isAlphaBlendDirty = true;
  3353. },
  3354. enumerable: true,
  3355. configurable: true
  3356. });
  3357. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3358. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3359. return;
  3360. }
  3361. this._blendFunctionParameters[0] = value0;
  3362. this._blendFunctionParameters[1] = value1;
  3363. this._blendFunctionParameters[2] = value2;
  3364. this._blendFunctionParameters[3] = value3;
  3365. this._isBlendFunctionParametersDirty = true;
  3366. };
  3367. _AlphaState.prototype.reset = function () {
  3368. this._alphaBlend = false;
  3369. this._blendFunctionParameters[0] = null;
  3370. this._blendFunctionParameters[1] = null;
  3371. this._blendFunctionParameters[2] = null;
  3372. this._blendFunctionParameters[3] = null;
  3373. this._isAlphaBlendDirty = true;
  3374. this._isBlendFunctionParametersDirty = false;
  3375. };
  3376. _AlphaState.prototype.apply = function (gl) {
  3377. if (!this.isDirty) {
  3378. return;
  3379. }
  3380. // Alpha blend
  3381. if (this._isAlphaBlendDirty) {
  3382. if (this._alphaBlend) {
  3383. gl.enable(gl.BLEND);
  3384. }
  3385. else {
  3386. gl.disable(gl.BLEND);
  3387. }
  3388. this._isAlphaBlendDirty = false;
  3389. }
  3390. // Alpha function
  3391. if (this._isBlendFunctionParametersDirty) {
  3392. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3393. this._isBlendFunctionParametersDirty = false;
  3394. }
  3395. };
  3396. return _AlphaState;
  3397. })();
  3398. BABYLON._AlphaState = _AlphaState;
  3399. var compileShader = function (gl, source, type, defines) {
  3400. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3401. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3402. gl.compileShader(shader);
  3403. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3404. throw new Error(gl.getShaderInfoLog(shader));
  3405. }
  3406. return shader;
  3407. };
  3408. var getWebGLTextureType = function (gl, type) {
  3409. var textureType = gl.UNSIGNED_BYTE;
  3410. if (type === Engine.TEXTURETYPE_FLOAT)
  3411. textureType = gl.FLOAT;
  3412. return textureType;
  3413. };
  3414. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3415. var magFilter = gl.NEAREST;
  3416. var minFilter = gl.NEAREST;
  3417. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3418. magFilter = gl.LINEAR;
  3419. if (generateMipMaps) {
  3420. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3421. }
  3422. else {
  3423. minFilter = gl.LINEAR;
  3424. }
  3425. }
  3426. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3427. magFilter = gl.LINEAR;
  3428. if (generateMipMaps) {
  3429. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3430. }
  3431. else {
  3432. minFilter = gl.LINEAR;
  3433. }
  3434. }
  3435. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3436. magFilter = gl.NEAREST;
  3437. if (generateMipMaps) {
  3438. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3439. }
  3440. else {
  3441. minFilter = gl.NEAREST;
  3442. }
  3443. }
  3444. return {
  3445. min: minFilter,
  3446. mag: magFilter
  3447. };
  3448. };
  3449. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3450. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3451. var engine = scene.getEngine();
  3452. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3453. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3454. gl.bindTexture(gl.TEXTURE_2D, texture);
  3455. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3456. processFunction(potWidth, potHeight);
  3457. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3458. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3459. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3460. if (!noMipmap && !isCompressed) {
  3461. gl.generateMipmap(gl.TEXTURE_2D);
  3462. }
  3463. gl.bindTexture(gl.TEXTURE_2D, null);
  3464. engine._activeTexturesCache = [];
  3465. texture._baseWidth = width;
  3466. texture._baseHeight = height;
  3467. texture._width = potWidth;
  3468. texture._height = potHeight;
  3469. texture.isReady = true;
  3470. texture.samplingMode = samplingMode;
  3471. scene._removePendingData(texture);
  3472. };
  3473. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3474. var onload = function () {
  3475. loadedImages[index] = img;
  3476. loadedImages._internalCount++;
  3477. scene._removePendingData(img);
  3478. if (loadedImages._internalCount === 6) {
  3479. onfinish(loadedImages);
  3480. }
  3481. };
  3482. var onerror = function () {
  3483. scene._removePendingData(img);
  3484. };
  3485. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3486. scene._addPendingData(img);
  3487. };
  3488. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3489. var loadedImages = [];
  3490. loadedImages._internalCount = 0;
  3491. for (var index = 0; index < 6; index++) {
  3492. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3493. }
  3494. };
  3495. var EngineCapabilities = (function () {
  3496. function EngineCapabilities() {
  3497. }
  3498. return EngineCapabilities;
  3499. })();
  3500. BABYLON.EngineCapabilities = EngineCapabilities;
  3501. /**
  3502. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3503. */
  3504. var Engine = (function () {
  3505. /**
  3506. * @constructor
  3507. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3508. * @param {boolean} [antialias] - enable antialias
  3509. * @param options - further options to be sent to the getContext function
  3510. */
  3511. function Engine(canvas, antialias, options) {
  3512. var _this = this;
  3513. // Public members
  3514. this.isFullscreen = false;
  3515. this.isPointerLock = false;
  3516. this.cullBackFaces = true;
  3517. this.renderEvenInBackground = true;
  3518. this.scenes = new Array();
  3519. this._windowIsBackground = false;
  3520. this._loadingDivBackgroundColor = "black";
  3521. this._drawCalls = 0;
  3522. this._renderingQueueLaunched = false;
  3523. this._activeRenderLoops = [];
  3524. // FPS
  3525. this.fpsRange = 60;
  3526. this.previousFramesDuration = [];
  3527. this.fps = 60;
  3528. this.deltaTime = 0;
  3529. // States
  3530. this._depthCullingState = new _DepthCullingState();
  3531. this._alphaState = new _AlphaState();
  3532. this._alphaMode = Engine.ALPHA_DISABLE;
  3533. // Cache
  3534. this._loadedTexturesCache = new Array();
  3535. this._activeTexturesCache = new Array();
  3536. this._compiledEffects = {};
  3537. this._uintIndicesCurrentlySet = false;
  3538. this._renderingCanvas = canvas;
  3539. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3540. options = options || {};
  3541. options.antialias = antialias;
  3542. try {
  3543. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3544. }
  3545. catch (e) {
  3546. throw new Error("WebGL not supported");
  3547. }
  3548. if (!this._gl) {
  3549. throw new Error("WebGL not supported");
  3550. }
  3551. this._onBlur = function () {
  3552. _this._windowIsBackground = true;
  3553. };
  3554. this._onFocus = function () {
  3555. _this._windowIsBackground = false;
  3556. };
  3557. window.addEventListener("blur", this._onBlur);
  3558. window.addEventListener("focus", this._onFocus);
  3559. // Textures
  3560. this._workingCanvas = document.createElement("canvas");
  3561. this._workingContext = this._workingCanvas.getContext("2d");
  3562. // Viewport
  3563. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3564. this.resize();
  3565. // Caps
  3566. this._caps = new EngineCapabilities();
  3567. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3568. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3569. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3570. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3571. // Infos
  3572. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3573. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3574. if (rendererInfo != null) {
  3575. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3576. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3577. }
  3578. if (!this._glVendor) {
  3579. this._glVendor = "Unknown vendor";
  3580. }
  3581. if (!this._glRenderer) {
  3582. this._glRenderer = "Unknown renderer";
  3583. }
  3584. // Extensions
  3585. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3586. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3587. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3588. 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');
  3589. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3590. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3591. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3592. // Depth buffer
  3593. this.setDepthBuffer(true);
  3594. this.setDepthFunctionToLessOrEqual();
  3595. this.setDepthWrite(true);
  3596. // Fullscreen
  3597. this._onFullscreenChange = function () {
  3598. if (document.fullscreen !== undefined) {
  3599. _this.isFullscreen = document.fullscreen;
  3600. }
  3601. else if (document.mozFullScreen !== undefined) {
  3602. _this.isFullscreen = document.mozFullScreen;
  3603. }
  3604. else if (document.webkitIsFullScreen !== undefined) {
  3605. _this.isFullscreen = document.webkitIsFullScreen;
  3606. }
  3607. else if (document.msIsFullScreen !== undefined) {
  3608. _this.isFullscreen = document.msIsFullScreen;
  3609. }
  3610. // Pointer lock
  3611. if (_this.isFullscreen && _this._pointerLockRequested) {
  3612. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3613. if (canvas.requestPointerLock) {
  3614. canvas.requestPointerLock();
  3615. }
  3616. }
  3617. };
  3618. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3619. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3620. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3621. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3622. // Pointer lock
  3623. this._onPointerLockChange = function () {
  3624. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3625. };
  3626. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3627. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3628. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3629. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3630. if (!Engine.audioEngine) {
  3631. Engine.audioEngine = new BABYLON.AudioEngine();
  3632. }
  3633. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3634. }
  3635. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3636. get: function () {
  3637. return Engine._ALPHA_DISABLE;
  3638. },
  3639. enumerable: true,
  3640. configurable: true
  3641. });
  3642. Object.defineProperty(Engine, "ALPHA_ADD", {
  3643. get: function () {
  3644. return Engine._ALPHA_ADD;
  3645. },
  3646. enumerable: true,
  3647. configurable: true
  3648. });
  3649. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3650. get: function () {
  3651. return Engine._ALPHA_COMBINE;
  3652. },
  3653. enumerable: true,
  3654. configurable: true
  3655. });
  3656. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3657. get: function () {
  3658. return Engine._DELAYLOADSTATE_NONE;
  3659. },
  3660. enumerable: true,
  3661. configurable: true
  3662. });
  3663. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3664. get: function () {
  3665. return Engine._DELAYLOADSTATE_LOADED;
  3666. },
  3667. enumerable: true,
  3668. configurable: true
  3669. });
  3670. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3671. get: function () {
  3672. return Engine._DELAYLOADSTATE_LOADING;
  3673. },
  3674. enumerable: true,
  3675. configurable: true
  3676. });
  3677. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3678. get: function () {
  3679. return Engine._DELAYLOADSTATE_NOTLOADED;
  3680. },
  3681. enumerable: true,
  3682. configurable: true
  3683. });
  3684. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3685. get: function () {
  3686. return Engine._TEXTUREFORMAT_ALPHA;
  3687. },
  3688. enumerable: true,
  3689. configurable: true
  3690. });
  3691. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3692. get: function () {
  3693. return Engine._TEXTUREFORMAT_LUMINANCE;
  3694. },
  3695. enumerable: true,
  3696. configurable: true
  3697. });
  3698. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3699. get: function () {
  3700. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3701. },
  3702. enumerable: true,
  3703. configurable: true
  3704. });
  3705. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3706. get: function () {
  3707. return Engine._TEXTUREFORMAT_RGB;
  3708. },
  3709. enumerable: true,
  3710. configurable: true
  3711. });
  3712. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3713. get: function () {
  3714. return Engine._TEXTUREFORMAT_RGBA;
  3715. },
  3716. enumerable: true,
  3717. configurable: true
  3718. });
  3719. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  3720. get: function () {
  3721. return Engine._TEXTURETYPE_UNSIGNED_INT;
  3722. },
  3723. enumerable: true,
  3724. configurable: true
  3725. });
  3726. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  3727. get: function () {
  3728. return Engine._TEXTURETYPE_FLOAT;
  3729. },
  3730. enumerable: true,
  3731. configurable: true
  3732. });
  3733. Object.defineProperty(Engine, "Version", {
  3734. get: function () {
  3735. return "2.0.0";
  3736. },
  3737. enumerable: true,
  3738. configurable: true
  3739. });
  3740. Engine.prototype.getGlInfo = function () {
  3741. return {
  3742. vendor: this._glVendor,
  3743. renderer: this._glRenderer,
  3744. version: this._glVersion
  3745. };
  3746. };
  3747. Engine.prototype.getAspectRatio = function (camera) {
  3748. var viewport = camera.viewport;
  3749. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3750. };
  3751. Engine.prototype.getRenderWidth = function () {
  3752. if (this._currentRenderTarget) {
  3753. return this._currentRenderTarget._width;
  3754. }
  3755. return this._renderingCanvas.width;
  3756. };
  3757. Engine.prototype.getRenderHeight = function () {
  3758. if (this._currentRenderTarget) {
  3759. return this._currentRenderTarget._height;
  3760. }
  3761. return this._renderingCanvas.height;
  3762. };
  3763. Engine.prototype.getRenderingCanvas = function () {
  3764. return this._renderingCanvas;
  3765. };
  3766. Engine.prototype.getRenderingCanvasClientRect = function () {
  3767. return this._renderingCanvas.getBoundingClientRect();
  3768. };
  3769. Engine.prototype.setHardwareScalingLevel = function (level) {
  3770. this._hardwareScalingLevel = level;
  3771. this.resize();
  3772. };
  3773. Engine.prototype.getHardwareScalingLevel = function () {
  3774. return this._hardwareScalingLevel;
  3775. };
  3776. Engine.prototype.getLoadedTexturesCache = function () {
  3777. return this._loadedTexturesCache;
  3778. };
  3779. Engine.prototype.getCaps = function () {
  3780. return this._caps;
  3781. };
  3782. Object.defineProperty(Engine.prototype, "drawCalls", {
  3783. get: function () {
  3784. return this._drawCalls;
  3785. },
  3786. enumerable: true,
  3787. configurable: true
  3788. });
  3789. // Methods
  3790. Engine.prototype.resetDrawCalls = function () {
  3791. this._drawCalls = 0;
  3792. };
  3793. Engine.prototype.setDepthFunctionToGreater = function () {
  3794. this._depthCullingState.depthFunc = this._gl.GREATER;
  3795. };
  3796. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3797. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3798. };
  3799. Engine.prototype.setDepthFunctionToLess = function () {
  3800. this._depthCullingState.depthFunc = this._gl.LESS;
  3801. };
  3802. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3803. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3804. };
  3805. /**
  3806. * stop executing a render loop function and remove it from the execution array
  3807. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  3808. */
  3809. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3810. if (!renderFunction) {
  3811. this._activeRenderLoops = [];
  3812. return;
  3813. }
  3814. var index = this._activeRenderLoops.indexOf(renderFunction);
  3815. if (index >= 0) {
  3816. this._activeRenderLoops.splice(index, 1);
  3817. }
  3818. };
  3819. Engine.prototype._renderLoop = function () {
  3820. var _this = this;
  3821. var shouldRender = true;
  3822. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3823. shouldRender = false;
  3824. }
  3825. if (shouldRender) {
  3826. // Start new frame
  3827. this.beginFrame();
  3828. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3829. var renderFunction = this._activeRenderLoops[index];
  3830. renderFunction();
  3831. }
  3832. // Present
  3833. this.endFrame();
  3834. }
  3835. if (this._activeRenderLoops.length > 0) {
  3836. // Register new frame
  3837. BABYLON.Tools.QueueNewFrame(function () {
  3838. _this._renderLoop();
  3839. });
  3840. }
  3841. else {
  3842. this._renderingQueueLaunched = false;
  3843. }
  3844. };
  3845. /**
  3846. * Register and execute a render loop. The engine can have more than one render function.
  3847. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  3848. * @example
  3849. * engine.runRenderLoop(function () {
  3850. * scene.render()
  3851. * })
  3852. */
  3853. Engine.prototype.runRenderLoop = function (renderFunction) {
  3854. var _this = this;
  3855. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3856. return;
  3857. }
  3858. this._activeRenderLoops.push(renderFunction);
  3859. if (!this._renderingQueueLaunched) {
  3860. this._renderingQueueLaunched = true;
  3861. BABYLON.Tools.QueueNewFrame(function () {
  3862. _this._renderLoop();
  3863. });
  3864. }
  3865. };
  3866. /**
  3867. * Toggle full screen mode.
  3868. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  3869. */
  3870. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3871. if (this.isFullscreen) {
  3872. BABYLON.Tools.ExitFullscreen();
  3873. }
  3874. else {
  3875. this._pointerLockRequested = requestPointerLock;
  3876. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3877. }
  3878. };
  3879. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3880. this.applyStates();
  3881. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3882. if (this._depthCullingState.depthMask) {
  3883. this._gl.clearDepth(1.0);
  3884. }
  3885. var mode = 0;
  3886. if (backBuffer)
  3887. mode |= this._gl.COLOR_BUFFER_BIT;
  3888. if (depthStencil && this._depthCullingState.depthMask)
  3889. mode |= this._gl.DEPTH_BUFFER_BIT;
  3890. this._gl.clear(mode);
  3891. };
  3892. /**
  3893. * Set the WebGL's viewport
  3894. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  3895. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  3896. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  3897. */
  3898. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3899. var width = requiredWidth || this._renderingCanvas.width;
  3900. var height = requiredHeight || this._renderingCanvas.height;
  3901. var x = viewport.x || 0;
  3902. var y = viewport.y || 0;
  3903. this._cachedViewport = viewport;
  3904. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3905. };
  3906. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3907. this._cachedViewport = null;
  3908. this._gl.viewport(x, y, width, height);
  3909. };
  3910. Engine.prototype.beginFrame = function () {
  3911. this._measureFps();
  3912. };
  3913. Engine.prototype.endFrame = function () {
  3914. //this.flushFramebuffer();
  3915. };
  3916. /**
  3917. * resize the view according to the canvas' size.
  3918. * @example
  3919. * window.addEventListener("resize", function () {
  3920. * engine.resize();
  3921. * });
  3922. */
  3923. Engine.prototype.resize = function () {
  3924. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3925. };
  3926. /**
  3927. * force a specific size of the canvas
  3928. * @param {number} width - the new canvas' width
  3929. * @param {number} height - the new canvas' height
  3930. */
  3931. Engine.prototype.setSize = function (width, height) {
  3932. this._renderingCanvas.width = width;
  3933. this._renderingCanvas.height = height;
  3934. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3935. };
  3936. Engine.prototype.bindFramebuffer = function (texture) {
  3937. this._currentRenderTarget = texture;
  3938. var gl = this._gl;
  3939. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3940. this._gl.viewport(0, 0, texture._width, texture._height);
  3941. this.wipeCaches();
  3942. };
  3943. Engine.prototype.unBindFramebuffer = function (texture) {
  3944. this._currentRenderTarget = null;
  3945. if (texture.generateMipMaps) {
  3946. var gl = this._gl;
  3947. gl.bindTexture(gl.TEXTURE_2D, texture);
  3948. gl.generateMipmap(gl.TEXTURE_2D);
  3949. gl.bindTexture(gl.TEXTURE_2D, null);
  3950. }
  3951. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3952. };
  3953. Engine.prototype.flushFramebuffer = function () {
  3954. this._gl.flush();
  3955. };
  3956. Engine.prototype.restoreDefaultFramebuffer = function () {
  3957. this._currentRenderTarget = null;
  3958. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3959. this.setViewport(this._cachedViewport);
  3960. this.wipeCaches();
  3961. };
  3962. // VBOs
  3963. Engine.prototype._resetVertexBufferBinding = function () {
  3964. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3965. this._cachedVertexBuffers = null;
  3966. };
  3967. Engine.prototype.createVertexBuffer = function (vertices) {
  3968. var vbo = this._gl.createBuffer();
  3969. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3970. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3971. this._resetVertexBufferBinding();
  3972. vbo.references = 1;
  3973. return vbo;
  3974. };
  3975. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3976. var vbo = this._gl.createBuffer();
  3977. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3978. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3979. this._resetVertexBufferBinding();
  3980. vbo.references = 1;
  3981. return vbo;
  3982. };
  3983. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  3984. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3985. if (offset === undefined) {
  3986. offset = 0;
  3987. }
  3988. if (vertices instanceof Float32Array) {
  3989. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  3990. }
  3991. else {
  3992. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  3993. }
  3994. this._resetVertexBufferBinding();
  3995. };
  3996. Engine.prototype._resetIndexBufferBinding = function () {
  3997. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3998. this._cachedIndexBuffer = null;
  3999. };
  4000. Engine.prototype.createIndexBuffer = function (indices) {
  4001. var vbo = this._gl.createBuffer();
  4002. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4003. // Check for 32 bits indices
  4004. var arrayBuffer;
  4005. var need32Bits = false;
  4006. if (this._caps.uintIndices) {
  4007. for (var index = 0; index < indices.length; index++) {
  4008. if (indices[index] > 65535) {
  4009. need32Bits = true;
  4010. break;
  4011. }
  4012. }
  4013. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4014. }
  4015. else {
  4016. arrayBuffer = new Uint16Array(indices);
  4017. }
  4018. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4019. this._resetIndexBufferBinding();
  4020. vbo.references = 1;
  4021. vbo.is32Bits = need32Bits;
  4022. return vbo;
  4023. };
  4024. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4025. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4026. this._cachedVertexBuffers = vertexBuffer;
  4027. this._cachedEffectForVertexBuffers = effect;
  4028. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4029. var offset = 0;
  4030. for (var index = 0; index < vertexDeclaration.length; index++) {
  4031. var order = effect.getAttributeLocation(index);
  4032. if (order >= 0) {
  4033. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4034. }
  4035. offset += vertexDeclaration[index] * 4;
  4036. }
  4037. }
  4038. if (this._cachedIndexBuffer !== indexBuffer) {
  4039. this._cachedIndexBuffer = indexBuffer;
  4040. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4041. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4042. }
  4043. };
  4044. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4045. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4046. this._cachedVertexBuffers = vertexBuffers;
  4047. this._cachedEffectForVertexBuffers = effect;
  4048. var attributes = effect.getAttributesNames();
  4049. for (var index = 0; index < attributes.length; index++) {
  4050. var order = effect.getAttributeLocation(index);
  4051. if (order >= 0) {
  4052. var vertexBuffer = vertexBuffers[attributes[index]];
  4053. if (!vertexBuffer) {
  4054. continue;
  4055. }
  4056. var stride = vertexBuffer.getStrideSize();
  4057. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4058. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4059. }
  4060. }
  4061. }
  4062. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4063. this._cachedIndexBuffer = indexBuffer;
  4064. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4065. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4066. }
  4067. };
  4068. Engine.prototype._releaseBuffer = function (buffer) {
  4069. buffer.references--;
  4070. if (buffer.references === 0) {
  4071. this._gl.deleteBuffer(buffer);
  4072. return true;
  4073. }
  4074. return false;
  4075. };
  4076. Engine.prototype.createInstancesBuffer = function (capacity) {
  4077. var buffer = this._gl.createBuffer();
  4078. buffer.capacity = capacity;
  4079. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4080. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4081. return buffer;
  4082. };
  4083. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4084. this._gl.deleteBuffer(buffer);
  4085. };
  4086. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4087. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4088. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4089. for (var index = 0; index < 4; index++) {
  4090. var offsetLocation = offsetLocations[index];
  4091. this._gl.enableVertexAttribArray(offsetLocation);
  4092. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4093. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4094. }
  4095. };
  4096. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4097. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4098. for (var index = 0; index < 4; index++) {
  4099. var offsetLocation = offsetLocations[index];
  4100. this._gl.disableVertexAttribArray(offsetLocation);
  4101. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4102. }
  4103. };
  4104. Engine.prototype.applyStates = function () {
  4105. this._depthCullingState.apply(this._gl);
  4106. this._alphaState.apply(this._gl);
  4107. };
  4108. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4109. // Apply states
  4110. this.applyStates();
  4111. this._drawCalls++;
  4112. // Render
  4113. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4114. if (instancesCount) {
  4115. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4116. return;
  4117. }
  4118. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4119. };
  4120. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4121. // Apply states
  4122. this.applyStates();
  4123. this._drawCalls++;
  4124. if (instancesCount) {
  4125. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4126. return;
  4127. }
  4128. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4129. };
  4130. // Shaders
  4131. Engine.prototype._releaseEffect = function (effect) {
  4132. if (this._compiledEffects[effect._key]) {
  4133. delete this._compiledEffects[effect._key];
  4134. if (effect.getProgram()) {
  4135. this._gl.deleteProgram(effect.getProgram());
  4136. }
  4137. }
  4138. };
  4139. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4140. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4141. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4142. var name = vertex + "+" + fragment + "@" + defines;
  4143. if (this._compiledEffects[name]) {
  4144. return this._compiledEffects[name];
  4145. }
  4146. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4147. effect._key = name;
  4148. this._compiledEffects[name] = effect;
  4149. return effect;
  4150. };
  4151. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4152. if (uniformsNames === void 0) { uniformsNames = []; }
  4153. if (samplers === void 0) { samplers = []; }
  4154. if (defines === void 0) { defines = ""; }
  4155. return this.createEffect({
  4156. vertex: "particles",
  4157. fragmentElement: fragmentName
  4158. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4159. };
  4160. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4161. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4162. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4163. var shaderProgram = this._gl.createProgram();
  4164. this._gl.attachShader(shaderProgram, vertexShader);
  4165. this._gl.attachShader(shaderProgram, fragmentShader);
  4166. this._gl.linkProgram(shaderProgram);
  4167. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4168. if (!linked) {
  4169. var error = this._gl.getProgramInfoLog(shaderProgram);
  4170. if (error) {
  4171. throw new Error(error);
  4172. }
  4173. }
  4174. this._gl.deleteShader(vertexShader);
  4175. this._gl.deleteShader(fragmentShader);
  4176. return shaderProgram;
  4177. };
  4178. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4179. var results = [];
  4180. for (var index = 0; index < uniformsNames.length; index++) {
  4181. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4182. }
  4183. return results;
  4184. };
  4185. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4186. var results = [];
  4187. for (var index = 0; index < attributesNames.length; index++) {
  4188. try {
  4189. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4190. }
  4191. catch (e) {
  4192. results.push(-1);
  4193. }
  4194. }
  4195. return results;
  4196. };
  4197. Engine.prototype.enableEffect = function (effect) {
  4198. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4199. if (effect && effect.onBind) {
  4200. effect.onBind(effect);
  4201. }
  4202. return;
  4203. }
  4204. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4205. // Use program
  4206. this._gl.useProgram(effect.getProgram());
  4207. for (var i in this._vertexAttribArrays) {
  4208. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4209. continue;
  4210. }
  4211. this._vertexAttribArrays[i] = false;
  4212. this._gl.disableVertexAttribArray(i);
  4213. }
  4214. var attributesCount = effect.getAttributesCount();
  4215. for (var index = 0; index < attributesCount; index++) {
  4216. // Attributes
  4217. var order = effect.getAttributeLocation(index);
  4218. if (order >= 0) {
  4219. this._vertexAttribArrays[order] = true;
  4220. this._gl.enableVertexAttribArray(order);
  4221. }
  4222. }
  4223. this._currentEffect = effect;
  4224. if (effect.onBind) {
  4225. effect.onBind(effect);
  4226. }
  4227. };
  4228. Engine.prototype.setArray = function (uniform, array) {
  4229. if (!uniform)
  4230. return;
  4231. this._gl.uniform1fv(uniform, array);
  4232. };
  4233. Engine.prototype.setArray2 = function (uniform, array) {
  4234. if (!uniform || array.length % 2 !== 0)
  4235. return;
  4236. this._gl.uniform2fv(uniform, array);
  4237. };
  4238. Engine.prototype.setArray3 = function (uniform, array) {
  4239. if (!uniform || array.length % 3 !== 0)
  4240. return;
  4241. this._gl.uniform3fv(uniform, array);
  4242. };
  4243. Engine.prototype.setArray4 = function (uniform, array) {
  4244. if (!uniform || array.length % 4 !== 0)
  4245. return;
  4246. this._gl.uniform4fv(uniform, array);
  4247. };
  4248. Engine.prototype.setMatrices = function (uniform, matrices) {
  4249. if (!uniform)
  4250. return;
  4251. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4252. };
  4253. Engine.prototype.setMatrix = function (uniform, matrix) {
  4254. if (!uniform)
  4255. return;
  4256. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4257. };
  4258. Engine.prototype.setFloat = function (uniform, value) {
  4259. if (!uniform)
  4260. return;
  4261. this._gl.uniform1f(uniform, value);
  4262. };
  4263. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4264. if (!uniform)
  4265. return;
  4266. this._gl.uniform2f(uniform, x, y);
  4267. };
  4268. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4269. if (!uniform)
  4270. return;
  4271. this._gl.uniform3f(uniform, x, y, z);
  4272. };
  4273. Engine.prototype.setBool = function (uniform, bool) {
  4274. if (!uniform)
  4275. return;
  4276. this._gl.uniform1i(uniform, bool);
  4277. };
  4278. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4279. if (!uniform)
  4280. return;
  4281. this._gl.uniform4f(uniform, x, y, z, w);
  4282. };
  4283. Engine.prototype.setColor3 = function (uniform, color3) {
  4284. if (!uniform)
  4285. return;
  4286. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4287. };
  4288. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4289. if (!uniform)
  4290. return;
  4291. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4292. };
  4293. // States
  4294. Engine.prototype.setState = function (culling, force) {
  4295. // Culling
  4296. if (this._depthCullingState.cull !== culling || force) {
  4297. if (culling) {
  4298. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4299. this._depthCullingState.cull = true;
  4300. }
  4301. else {
  4302. this._depthCullingState.cull = false;
  4303. }
  4304. }
  4305. };
  4306. Engine.prototype.setDepthBuffer = function (enable) {
  4307. this._depthCullingState.depthTest = enable;
  4308. };
  4309. Engine.prototype.getDepthWrite = function () {
  4310. return this._depthCullingState.depthMask;
  4311. };
  4312. Engine.prototype.setDepthWrite = function (enable) {
  4313. this._depthCullingState.depthMask = enable;
  4314. };
  4315. Engine.prototype.setColorWrite = function (enable) {
  4316. this._gl.colorMask(enable, enable, enable, enable);
  4317. };
  4318. Engine.prototype.setAlphaMode = function (mode) {
  4319. switch (mode) {
  4320. case Engine.ALPHA_DISABLE:
  4321. this.setDepthWrite(true);
  4322. this._alphaState.alphaBlend = false;
  4323. break;
  4324. case Engine.ALPHA_COMBINE:
  4325. this.setDepthWrite(false);
  4326. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4327. this._alphaState.alphaBlend = true;
  4328. break;
  4329. case Engine.ALPHA_ADD:
  4330. this.setDepthWrite(false);
  4331. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4332. this._alphaState.alphaBlend = true;
  4333. break;
  4334. }
  4335. this._alphaMode = mode;
  4336. };
  4337. Engine.prototype.getAlphaMode = function () {
  4338. return this._alphaMode;
  4339. };
  4340. Engine.prototype.setAlphaTesting = function (enable) {
  4341. this._alphaTest = enable;
  4342. };
  4343. Engine.prototype.getAlphaTesting = function () {
  4344. return this._alphaTest;
  4345. };
  4346. // Textures
  4347. Engine.prototype.wipeCaches = function () {
  4348. this._activeTexturesCache = [];
  4349. this._currentEffect = null;
  4350. this._depthCullingState.reset();
  4351. this._alphaState.reset();
  4352. this._cachedVertexBuffers = null;
  4353. this._cachedIndexBuffer = null;
  4354. this._cachedEffectForVertexBuffers = null;
  4355. };
  4356. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4357. var gl = this._gl;
  4358. gl.bindTexture(gl.TEXTURE_2D, texture);
  4359. var magFilter = gl.NEAREST;
  4360. var minFilter = gl.NEAREST;
  4361. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4362. magFilter = gl.LINEAR;
  4363. minFilter = gl.LINEAR;
  4364. }
  4365. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4366. magFilter = gl.LINEAR;
  4367. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4368. }
  4369. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4370. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4371. gl.bindTexture(gl.TEXTURE_2D, null);
  4372. texture.samplingMode = samplingMode;
  4373. };
  4374. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4375. var _this = this;
  4376. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4377. if (onLoad === void 0) { onLoad = null; }
  4378. if (onError === void 0) { onError = null; }
  4379. if (buffer === void 0) { buffer = null; }
  4380. var texture = this._gl.createTexture();
  4381. var extension;
  4382. var fromData = false;
  4383. if (url.substr(0, 5) === "data:") {
  4384. fromData = true;
  4385. }
  4386. if (!fromData)
  4387. extension = url.substr(url.length - 4, 4).toLowerCase();
  4388. else {
  4389. var oldUrl = url;
  4390. fromData = oldUrl.split(':');
  4391. url = oldUrl;
  4392. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4393. }
  4394. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4395. var isTGA = (extension === ".tga");
  4396. scene._addPendingData(texture);
  4397. texture.url = url;
  4398. texture.noMipmap = noMipmap;
  4399. texture.references = 1;
  4400. this._loadedTexturesCache.push(texture);
  4401. var onerror = function () {
  4402. scene._removePendingData(texture);
  4403. if (onError) {
  4404. onError();
  4405. }
  4406. };
  4407. if (isTGA) {
  4408. var callback = function (arrayBuffer) {
  4409. var data = new Uint8Array(arrayBuffer);
  4410. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4411. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4412. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4413. if (onLoad) {
  4414. onLoad();
  4415. }
  4416. }, samplingMode);
  4417. };
  4418. if (!(fromData instanceof Array))
  4419. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4420. callback(arrayBuffer);
  4421. }, onerror, scene.database, true);
  4422. else
  4423. callback(buffer);
  4424. }
  4425. else if (isDDS) {
  4426. callback = function (data) {
  4427. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4428. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4429. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4430. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4431. if (onLoad) {
  4432. onLoad();
  4433. }
  4434. }, samplingMode);
  4435. };
  4436. if (!(fromData instanceof Array))
  4437. BABYLON.Tools.LoadFile(url, function (data) {
  4438. callback(data);
  4439. }, onerror, scene.database, true);
  4440. else
  4441. callback(buffer);
  4442. }
  4443. else {
  4444. var onload = function (img) {
  4445. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4446. var isPot = (img.width === potWidth && img.height === potHeight);
  4447. if (!isPot) {
  4448. _this._workingCanvas.width = potWidth;
  4449. _this._workingCanvas.height = potHeight;
  4450. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4451. _this._workingContext.imageSmoothingEnabled = false;
  4452. _this._workingContext.mozImageSmoothingEnabled = false;
  4453. _this._workingContext.oImageSmoothingEnabled = false;
  4454. _this._workingContext.webkitImageSmoothingEnabled = false;
  4455. _this._workingContext.msImageSmoothingEnabled = false;
  4456. }
  4457. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4458. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4459. _this._workingContext.imageSmoothingEnabled = true;
  4460. _this._workingContext.mozImageSmoothingEnabled = true;
  4461. _this._workingContext.oImageSmoothingEnabled = true;
  4462. _this._workingContext.webkitImageSmoothingEnabled = true;
  4463. _this._workingContext.msImageSmoothingEnabled = true;
  4464. }
  4465. }
  4466. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4467. if (onLoad) {
  4468. onLoad();
  4469. }
  4470. }, samplingMode);
  4471. };
  4472. if (!(fromData instanceof Array))
  4473. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4474. else
  4475. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4476. }
  4477. return texture;
  4478. };
  4479. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4480. var texture = this._gl.createTexture();
  4481. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4482. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4483. // Format
  4484. var internalFormat = this._gl.RGBA;
  4485. switch (format) {
  4486. case Engine.TEXTUREFORMAT_ALPHA:
  4487. internalFormat = this._gl.ALPHA;
  4488. break;
  4489. case Engine.TEXTUREFORMAT_LUMINANCE:
  4490. internalFormat = this._gl.LUMINANCE;
  4491. break;
  4492. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4493. internalFormat = this._gl.LUMINANCE_ALPHA;
  4494. break;
  4495. case Engine.TEXTUREFORMAT_RGB:
  4496. internalFormat = this._gl.RGB;
  4497. break;
  4498. case Engine.TEXTUREFORMAT_RGBA:
  4499. internalFormat = this._gl.RGBA;
  4500. break;
  4501. }
  4502. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4503. if (generateMipMaps) {
  4504. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4505. }
  4506. // Filters
  4507. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4508. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4509. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4510. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4511. this._activeTexturesCache = [];
  4512. texture._baseWidth = width;
  4513. texture._baseHeight = height;
  4514. texture._width = width;
  4515. texture._height = height;
  4516. texture.isReady = true;
  4517. texture.references = 1;
  4518. texture.samplingMode = samplingMode;
  4519. this._loadedTexturesCache.push(texture);
  4520. return texture;
  4521. };
  4522. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4523. var texture = this._gl.createTexture();
  4524. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4525. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4526. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4527. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4528. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4529. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4530. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4531. this._activeTexturesCache = [];
  4532. texture._baseWidth = width;
  4533. texture._baseHeight = height;
  4534. texture._width = width;
  4535. texture._height = height;
  4536. texture.isReady = false;
  4537. texture.generateMipMaps = generateMipMaps;
  4538. texture.references = 1;
  4539. texture.samplingMode = samplingMode;
  4540. this._loadedTexturesCache.push(texture);
  4541. return texture;
  4542. };
  4543. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4544. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4545. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4546. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4547. if (texture.generateMipMaps) {
  4548. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4549. }
  4550. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4551. this._activeTexturesCache = [];
  4552. texture.isReady = true;
  4553. };
  4554. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4555. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4556. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4557. // Scale the video if it is a NPOT using the current working canvas
  4558. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4559. if (!texture._workingCanvas) {
  4560. texture._workingCanvas = document.createElement("canvas");
  4561. texture._workingContext = texture._workingCanvas.getContext("2d");
  4562. texture._workingCanvas.width = texture._width;
  4563. texture._workingCanvas.height = texture._height;
  4564. }
  4565. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4566. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4567. }
  4568. else {
  4569. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4570. }
  4571. if (texture.generateMipMaps) {
  4572. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4573. }
  4574. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4575. this._activeTexturesCache = [];
  4576. texture.isReady = true;
  4577. };
  4578. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4579. // old version had a "generateMipMaps" arg instead of options.
  4580. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4581. // in the same way, generateDepthBuffer is defaulted to true
  4582. var generateMipMaps = false;
  4583. var generateDepthBuffer = true;
  4584. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4585. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4586. if (options !== undefined) {
  4587. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4588. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4589. type = options.type === undefined ? type : options.type;
  4590. if (options.samplingMode !== undefined) {
  4591. samplingMode = options.samplingMode;
  4592. }
  4593. if (type === Engine.TEXTURETYPE_FLOAT) {
  4594. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4595. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4596. }
  4597. }
  4598. var gl = this._gl;
  4599. var texture = gl.createTexture();
  4600. gl.bindTexture(gl.TEXTURE_2D, texture);
  4601. var width = size.width || size;
  4602. var height = size.height || size;
  4603. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4604. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4605. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4606. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4607. }
  4608. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4609. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4610. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4611. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4612. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  4613. var depthBuffer;
  4614. // Create the depth buffer
  4615. if (generateDepthBuffer) {
  4616. depthBuffer = gl.createRenderbuffer();
  4617. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4618. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4619. }
  4620. // Create the framebuffer
  4621. var framebuffer = gl.createFramebuffer();
  4622. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4623. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4624. if (generateDepthBuffer) {
  4625. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4626. }
  4627. // Unbind
  4628. gl.bindTexture(gl.TEXTURE_2D, null);
  4629. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4630. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4631. texture._framebuffer = framebuffer;
  4632. if (generateDepthBuffer) {
  4633. texture._depthBuffer = depthBuffer;
  4634. }
  4635. texture._width = width;
  4636. texture._height = height;
  4637. texture.isReady = true;
  4638. texture.generateMipMaps = generateMipMaps;
  4639. texture.references = 1;
  4640. texture.samplingMode = samplingMode;
  4641. this._activeTexturesCache = [];
  4642. this._loadedTexturesCache.push(texture);
  4643. return texture;
  4644. };
  4645. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4646. var _this = this;
  4647. var gl = this._gl;
  4648. var texture = gl.createTexture();
  4649. texture.isCube = true;
  4650. texture.url = rootUrl;
  4651. texture.references = 1;
  4652. this._loadedTexturesCache.push(texture);
  4653. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4654. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4655. if (isDDS) {
  4656. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4657. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4658. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4659. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4660. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4661. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4662. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4663. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4664. }
  4665. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4666. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4667. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4668. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4669. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4670. _this._activeTexturesCache = [];
  4671. texture._width = info.width;
  4672. texture._height = info.height;
  4673. texture.isReady = true;
  4674. }, null, null, true);
  4675. }
  4676. else {
  4677. cascadeLoad(rootUrl, scene, function (imgs) {
  4678. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4679. var height = width;
  4680. _this._workingCanvas.width = width;
  4681. _this._workingCanvas.height = height;
  4682. var faces = [
  4683. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  4684. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  4685. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4686. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  4687. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  4688. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4689. ];
  4690. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4691. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4692. for (var index = 0; index < faces.length; index++) {
  4693. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4694. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4695. }
  4696. if (!noMipmap) {
  4697. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4698. }
  4699. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4700. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4701. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4702. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4703. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4704. _this._activeTexturesCache = [];
  4705. texture._width = width;
  4706. texture._height = height;
  4707. texture.isReady = true;
  4708. }, extensions);
  4709. }
  4710. return texture;
  4711. };
  4712. Engine.prototype._releaseTexture = function (texture) {
  4713. var gl = this._gl;
  4714. if (texture._framebuffer) {
  4715. gl.deleteFramebuffer(texture._framebuffer);
  4716. }
  4717. if (texture._depthBuffer) {
  4718. gl.deleteRenderbuffer(texture._depthBuffer);
  4719. }
  4720. gl.deleteTexture(texture);
  4721. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4722. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4723. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4724. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4725. this._activeTexturesCache[channel] = null;
  4726. }
  4727. var index = this._loadedTexturesCache.indexOf(texture);
  4728. if (index !== -1) {
  4729. this._loadedTexturesCache.splice(index, 1);
  4730. }
  4731. };
  4732. Engine.prototype.bindSamplers = function (effect) {
  4733. this._gl.useProgram(effect.getProgram());
  4734. var samplers = effect.getSamplers();
  4735. for (var index = 0; index < samplers.length; index++) {
  4736. var uniform = effect.getUniform(samplers[index]);
  4737. this._gl.uniform1i(uniform, index);
  4738. }
  4739. this._currentEffect = null;
  4740. };
  4741. Engine.prototype._bindTexture = function (channel, texture) {
  4742. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4743. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4744. this._activeTexturesCache[channel] = null;
  4745. };
  4746. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4747. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4748. };
  4749. Engine.prototype.setTexture = function (channel, texture) {
  4750. if (channel < 0) {
  4751. return;
  4752. }
  4753. // Not ready?
  4754. if (!texture || !texture.isReady()) {
  4755. if (this._activeTexturesCache[channel] != null) {
  4756. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4757. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4758. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4759. this._activeTexturesCache[channel] = null;
  4760. }
  4761. return;
  4762. }
  4763. // Video
  4764. if (texture instanceof BABYLON.VideoTexture) {
  4765. if (texture.update()) {
  4766. this._activeTexturesCache[channel] = null;
  4767. }
  4768. }
  4769. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4770. texture.delayLoad();
  4771. return;
  4772. }
  4773. if (this._activeTexturesCache[channel] === texture) {
  4774. return;
  4775. }
  4776. this._activeTexturesCache[channel] = texture;
  4777. var internalTexture = texture.getInternalTexture();
  4778. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4779. if (internalTexture.isCube) {
  4780. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4781. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4782. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4783. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4784. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4785. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4786. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4787. }
  4788. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4789. }
  4790. else {
  4791. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4792. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4793. internalTexture._cachedWrapU = texture.wrapU;
  4794. switch (texture.wrapU) {
  4795. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4796. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4797. break;
  4798. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4799. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4800. break;
  4801. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4802. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4803. break;
  4804. }
  4805. }
  4806. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4807. internalTexture._cachedWrapV = texture.wrapV;
  4808. switch (texture.wrapV) {
  4809. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4810. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4811. break;
  4812. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4813. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4814. break;
  4815. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4816. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4817. break;
  4818. }
  4819. }
  4820. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4821. }
  4822. };
  4823. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4824. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4825. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4826. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4827. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4828. }
  4829. };
  4830. Engine.prototype.readPixels = function (x, y, width, height) {
  4831. var data = new Uint8Array(height * width * 4);
  4832. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4833. return data;
  4834. };
  4835. // Dispose
  4836. Engine.prototype.dispose = function () {
  4837. this.hideLoadingUI();
  4838. this.stopRenderLoop();
  4839. while (this.scenes.length) {
  4840. this.scenes[0].dispose();
  4841. }
  4842. // Release audio engine
  4843. Engine.audioEngine.dispose();
  4844. for (var name in this._compiledEffects) {
  4845. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4846. }
  4847. for (var i in this._vertexAttribArrays) {
  4848. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4849. continue;
  4850. }
  4851. this._gl.disableVertexAttribArray(i);
  4852. }
  4853. // Events
  4854. window.removeEventListener("blur", this._onBlur);
  4855. window.removeEventListener("focus", this._onFocus);
  4856. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4857. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4858. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4859. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4860. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4861. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4862. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4863. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4864. };
  4865. // Loading screen
  4866. Engine.prototype.displayLoadingUI = function () {
  4867. var _this = this;
  4868. this._loadingDiv = document.createElement("div");
  4869. this._loadingDiv.style.opacity = "0";
  4870. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4871. // Loading text
  4872. this._loadingTextDiv = document.createElement("div");
  4873. this._loadingTextDiv.style.position = "absolute";
  4874. this._loadingTextDiv.style.left = "0";
  4875. this._loadingTextDiv.style.top = "50%";
  4876. this._loadingTextDiv.style.marginTop = "80px";
  4877. this._loadingTextDiv.style.width = "100%";
  4878. this._loadingTextDiv.style.height = "20px";
  4879. this._loadingTextDiv.style.fontFamily = "Arial";
  4880. this._loadingTextDiv.style.fontSize = "14px";
  4881. this._loadingTextDiv.style.color = "white";
  4882. this._loadingTextDiv.style.textAlign = "center";
  4883. this._loadingTextDiv.innerHTML = "Loading";
  4884. this._loadingDiv.appendChild(this._loadingTextDiv);
  4885. // Loading img
  4886. var imgBack = new Image();
  4887. 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==";
  4888. imgBack.style.position = "absolute";
  4889. imgBack.style.left = "50%";
  4890. imgBack.style.top = "50%";
  4891. imgBack.style.marginLeft = "-50px";
  4892. imgBack.style.marginTop = "-50px";
  4893. imgBack.style.transition = "transform 1.0s ease";
  4894. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4895. var deg = 360;
  4896. var onTransitionEnd = function () {
  4897. deg += 360;
  4898. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4899. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4900. };
  4901. imgBack.addEventListener("transitionend", onTransitionEnd);
  4902. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4903. this._loadingDiv.appendChild(imgBack);
  4904. // front image
  4905. var imgFront = new Image();
  4906. 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=";
  4907. imgFront.style.position = "absolute";
  4908. imgFront.style.left = "50%";
  4909. imgFront.style.top = "50%";
  4910. imgFront.style.marginLeft = "-50px";
  4911. imgFront.style.marginTop = "-50px";
  4912. this._loadingDiv.appendChild(imgFront);
  4913. // Resize
  4914. this._resizeLoadingUI = function () {
  4915. var canvasRect = _this.getRenderingCanvasClientRect();
  4916. _this._loadingDiv.style.position = "absolute";
  4917. _this._loadingDiv.style.left = canvasRect.left + "px";
  4918. _this._loadingDiv.style.top = canvasRect.top + "px";
  4919. _this._loadingDiv.style.width = canvasRect.width + "px";
  4920. _this._loadingDiv.style.height = canvasRect.height + "px";
  4921. };
  4922. this._resizeLoadingUI();
  4923. window.addEventListener("resize", this._resizeLoadingUI);
  4924. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4925. document.body.appendChild(this._loadingDiv);
  4926. setTimeout(function () {
  4927. _this._loadingDiv.style.opacity = "1";
  4928. imgBack.style.transform = "rotateZ(360deg)";
  4929. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4930. }, 0);
  4931. };
  4932. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4933. set: function (text) {
  4934. if (!this._loadingDiv) {
  4935. return;
  4936. }
  4937. this._loadingTextDiv.innerHTML = text;
  4938. },
  4939. enumerable: true,
  4940. configurable: true
  4941. });
  4942. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4943. get: function () {
  4944. return this._loadingDivBackgroundColor;
  4945. },
  4946. set: function (color) {
  4947. this._loadingDivBackgroundColor = color;
  4948. if (!this._loadingDiv) {
  4949. return;
  4950. }
  4951. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4952. },
  4953. enumerable: true,
  4954. configurable: true
  4955. });
  4956. Engine.prototype.hideLoadingUI = function () {
  4957. var _this = this;
  4958. if (!this._loadingDiv) {
  4959. return;
  4960. }
  4961. var onTransitionEnd = function () {
  4962. if (!_this._loadingDiv) {
  4963. return;
  4964. }
  4965. document.body.removeChild(_this._loadingDiv);
  4966. window.removeEventListener("resize", _this._resizeLoadingUI);
  4967. _this._loadingDiv = null;
  4968. };
  4969. this._loadingDiv.style.opacity = "0";
  4970. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4971. };
  4972. // FPS
  4973. Engine.prototype.getFps = function () {
  4974. return this.fps;
  4975. };
  4976. Engine.prototype.getDeltaTime = function () {
  4977. return this.deltaTime;
  4978. };
  4979. Engine.prototype._measureFps = function () {
  4980. this.previousFramesDuration.push(BABYLON.Tools.Now);
  4981. var length = this.previousFramesDuration.length;
  4982. if (length >= 2) {
  4983. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  4984. }
  4985. if (length >= this.fpsRange) {
  4986. if (length > this.fpsRange) {
  4987. this.previousFramesDuration.splice(0, 1);
  4988. length = this.previousFramesDuration.length;
  4989. }
  4990. var sum = 0;
  4991. for (var id = 0; id < length - 1; id++) {
  4992. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  4993. }
  4994. this.fps = 1000.0 / (sum / (length - 1));
  4995. }
  4996. };
  4997. // Statics
  4998. Engine.isSupported = function () {
  4999. try {
  5000. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5001. if (navigator.isCocoonJS) {
  5002. return true;
  5003. }
  5004. var tempcanvas = document.createElement("canvas");
  5005. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5006. return gl != null && !!window.WebGLRenderingContext;
  5007. }
  5008. catch (e) {
  5009. return false;
  5010. }
  5011. };
  5012. // Const statics
  5013. Engine._ALPHA_DISABLE = 0;
  5014. Engine._ALPHA_ADD = 1;
  5015. Engine._ALPHA_COMBINE = 2;
  5016. Engine._DELAYLOADSTATE_NONE = 0;
  5017. Engine._DELAYLOADSTATE_LOADED = 1;
  5018. Engine._DELAYLOADSTATE_LOADING = 2;
  5019. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5020. Engine._TEXTUREFORMAT_ALPHA = 0;
  5021. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5022. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5023. Engine._TEXTUREFORMAT_RGB = 4;
  5024. Engine._TEXTUREFORMAT_RGBA = 4;
  5025. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5026. Engine._TEXTURETYPE_FLOAT = 1;
  5027. // Updatable statics so stick with vars here
  5028. Engine.Epsilon = 0.001;
  5029. Engine.CollisionsEpsilon = 0.001;
  5030. Engine.ShadersRepository = "Babylon/Shaders/";
  5031. return Engine;
  5032. })();
  5033. BABYLON.Engine = Engine;
  5034. })(BABYLON || (BABYLON = {}));
  5035. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5036. (function (BABYLON) {
  5037. /**
  5038. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5039. */
  5040. var Node = (function () {
  5041. /**
  5042. * @constructor
  5043. * @param {string} name - the name and id to be given to this node
  5044. * @param {BABYLON.Scene} the scene this node will be added to
  5045. */
  5046. function Node(name, scene) {
  5047. this.state = "";
  5048. this.animations = new Array();
  5049. this._childrenFlag = -1;
  5050. this._isEnabled = true;
  5051. this._isReady = true;
  5052. this._currentRenderId = -1;
  5053. this.name = name;
  5054. this.id = name;
  5055. this._scene = scene;
  5056. this._initCache();
  5057. }
  5058. Node.prototype.getScene = function () {
  5059. return this._scene;
  5060. };
  5061. Node.prototype.getEngine = function () {
  5062. return this._scene.getEngine();
  5063. };
  5064. // override it in derived class
  5065. Node.prototype.getWorldMatrix = function () {
  5066. return BABYLON.Matrix.Identity();
  5067. };
  5068. // override it in derived class if you add new variables to the cache
  5069. // and call the parent class method
  5070. Node.prototype._initCache = function () {
  5071. this._cache = {};
  5072. this._cache.parent = undefined;
  5073. };
  5074. Node.prototype.updateCache = function (force) {
  5075. if (!force && this.isSynchronized())
  5076. return;
  5077. this._cache.parent = this.parent;
  5078. this._updateCache();
  5079. };
  5080. // override it in derived class if you add new variables to the cache
  5081. // and call the parent class method if !ignoreParentClass
  5082. Node.prototype._updateCache = function (ignoreParentClass) {
  5083. };
  5084. // override it in derived class if you add new variables to the cache
  5085. Node.prototype._isSynchronized = function () {
  5086. return true;
  5087. };
  5088. Node.prototype.isSynchronizedWithParent = function () {
  5089. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  5090. };
  5091. Node.prototype.isSynchronized = function (updateCache) {
  5092. var check = this.hasNewParent();
  5093. check = check || !this.isSynchronizedWithParent();
  5094. check = check || !this._isSynchronized();
  5095. if (updateCache)
  5096. this.updateCache(true);
  5097. return !check;
  5098. };
  5099. Node.prototype.hasNewParent = function (update) {
  5100. if (this._cache.parent === this.parent)
  5101. return false;
  5102. if (update)
  5103. this._cache.parent = this.parent;
  5104. return true;
  5105. };
  5106. /**
  5107. * Is this node ready to be used/rendered
  5108. * @return {boolean} is it ready
  5109. */
  5110. Node.prototype.isReady = function () {
  5111. return this._isReady;
  5112. };
  5113. /**
  5114. * Is this node enabled.
  5115. * If the node has a parent and is enabled, the parent will be inspected as well.
  5116. * @return {boolean} whether this node (and its parent) is enabled.
  5117. * @see setEnabled
  5118. */
  5119. Node.prototype.isEnabled = function () {
  5120. if (!this._isEnabled) {
  5121. return false;
  5122. }
  5123. if (this.parent) {
  5124. return this.parent.isEnabled();
  5125. }
  5126. return true;
  5127. };
  5128. /**
  5129. * Set the enabled state of this node.
  5130. * @param {boolean} value - the new enabled state
  5131. * @see isEnabled
  5132. */
  5133. Node.prototype.setEnabled = function (value) {
  5134. this._isEnabled = value;
  5135. };
  5136. /**
  5137. * Is this node a descendant of the given node.
  5138. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5139. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5140. * @see parent
  5141. */
  5142. Node.prototype.isDescendantOf = function (ancestor) {
  5143. if (this.parent) {
  5144. if (this.parent === ancestor) {
  5145. return true;
  5146. }
  5147. return this.parent.isDescendantOf(ancestor);
  5148. }
  5149. return false;
  5150. };
  5151. Node.prototype._getDescendants = function (list, results) {
  5152. for (var index = 0; index < list.length; index++) {
  5153. var item = list[index];
  5154. if (item.isDescendantOf(this)) {
  5155. results.push(item);
  5156. }
  5157. }
  5158. };
  5159. /**
  5160. * Will return all nodes that have this node as parent.
  5161. * @return {BABYLON.Node[]} all children nodes of all types.
  5162. */
  5163. Node.prototype.getDescendants = function () {
  5164. var results = [];
  5165. this._getDescendants(this._scene.meshes, results);
  5166. this._getDescendants(this._scene.lights, results);
  5167. this._getDescendants(this._scene.cameras, results);
  5168. return results;
  5169. };
  5170. Node.prototype._setReady = function (state) {
  5171. if (state == this._isReady) {
  5172. return;
  5173. }
  5174. if (!state) {
  5175. this._isReady = false;
  5176. return;
  5177. }
  5178. this._isReady = true;
  5179. if (this.onReady) {
  5180. this.onReady(this);
  5181. }
  5182. };
  5183. return Node;
  5184. })();
  5185. BABYLON.Node = Node;
  5186. })(BABYLON || (BABYLON = {}));
  5187. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5188. (function (BABYLON) {
  5189. var BoundingSphere = (function () {
  5190. function BoundingSphere(minimum, maximum) {
  5191. this.minimum = minimum;
  5192. this.maximum = maximum;
  5193. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5194. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5195. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5196. this.radius = distance * 0.5;
  5197. this.centerWorld = BABYLON.Vector3.Zero();
  5198. this._update(BABYLON.Matrix.Identity());
  5199. }
  5200. // Methods
  5201. BoundingSphere.prototype._update = function (world) {
  5202. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5203. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5204. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5205. };
  5206. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5207. for (var i = 0; i < 6; i++) {
  5208. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5209. return false;
  5210. }
  5211. return true;
  5212. };
  5213. BoundingSphere.prototype.intersectsPoint = function (point) {
  5214. var x = this.centerWorld.x - point.x;
  5215. var y = this.centerWorld.y - point.y;
  5216. var z = this.centerWorld.z - point.z;
  5217. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5218. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5219. return false;
  5220. return true;
  5221. };
  5222. // Statics
  5223. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5224. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5225. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5226. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5227. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5228. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5229. return false;
  5230. return true;
  5231. };
  5232. return BoundingSphere;
  5233. })();
  5234. BABYLON.BoundingSphere = BoundingSphere;
  5235. })(BABYLON || (BABYLON = {}));
  5236. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5237. (function (BABYLON) {
  5238. var BoundingBox = (function () {
  5239. function BoundingBox(minimum, maximum) {
  5240. this.minimum = minimum;
  5241. this.maximum = maximum;
  5242. this.vectors = new Array();
  5243. this.vectorsWorld = new Array();
  5244. // Bounding vectors
  5245. this.vectors.push(this.minimum.clone());
  5246. this.vectors.push(this.maximum.clone());
  5247. this.vectors.push(this.minimum.clone());
  5248. this.vectors[2].x = this.maximum.x;
  5249. this.vectors.push(this.minimum.clone());
  5250. this.vectors[3].y = this.maximum.y;
  5251. this.vectors.push(this.minimum.clone());
  5252. this.vectors[4].z = this.maximum.z;
  5253. this.vectors.push(this.maximum.clone());
  5254. this.vectors[5].z = this.minimum.z;
  5255. this.vectors.push(this.maximum.clone());
  5256. this.vectors[6].x = this.minimum.x;
  5257. this.vectors.push(this.maximum.clone());
  5258. this.vectors[7].y = this.minimum.y;
  5259. // OBB
  5260. this.center = this.maximum.add(this.minimum).scale(0.5);
  5261. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5262. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5263. for (var index = 0; index < this.vectors.length; index++) {
  5264. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5265. }
  5266. this.minimumWorld = BABYLON.Vector3.Zero();
  5267. this.maximumWorld = BABYLON.Vector3.Zero();
  5268. this._update(BABYLON.Matrix.Identity());
  5269. }
  5270. // Methods
  5271. BoundingBox.prototype.getWorldMatrix = function () {
  5272. return this._worldMatrix;
  5273. };
  5274. BoundingBox.prototype._update = function (world) {
  5275. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5276. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5277. for (var index = 0; index < this.vectors.length; index++) {
  5278. var v = this.vectorsWorld[index];
  5279. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5280. if (v.x < this.minimumWorld.x)
  5281. this.minimumWorld.x = v.x;
  5282. if (v.y < this.minimumWorld.y)
  5283. this.minimumWorld.y = v.y;
  5284. if (v.z < this.minimumWorld.z)
  5285. this.minimumWorld.z = v.z;
  5286. if (v.x > this.maximumWorld.x)
  5287. this.maximumWorld.x = v.x;
  5288. if (v.y > this.maximumWorld.y)
  5289. this.maximumWorld.y = v.y;
  5290. if (v.z > this.maximumWorld.z)
  5291. this.maximumWorld.z = v.z;
  5292. }
  5293. // OBB
  5294. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5295. this.center.scaleInPlace(0.5);
  5296. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5297. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5298. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5299. this._worldMatrix = world;
  5300. };
  5301. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5302. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5303. };
  5304. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5305. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5306. };
  5307. BoundingBox.prototype.intersectsPoint = function (point) {
  5308. var delta = BABYLON.Engine.Epsilon;
  5309. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5310. return false;
  5311. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5312. return false;
  5313. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5314. return false;
  5315. return true;
  5316. };
  5317. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5318. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5319. };
  5320. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5321. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5322. return false;
  5323. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5324. return false;
  5325. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5326. return false;
  5327. return true;
  5328. };
  5329. // Statics
  5330. BoundingBox.Intersects = function (box0, box1) {
  5331. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5332. return false;
  5333. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5334. return false;
  5335. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5336. return false;
  5337. return true;
  5338. };
  5339. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5340. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5341. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5342. return (num <= (sphereRadius * sphereRadius));
  5343. };
  5344. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5345. for (var p = 0; p < 6; p++) {
  5346. for (var i = 0; i < 8; i++) {
  5347. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5348. return false;
  5349. }
  5350. }
  5351. }
  5352. return true;
  5353. };
  5354. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5355. for (var p = 0; p < 6; p++) {
  5356. var inCount = 8;
  5357. for (var i = 0; i < 8; i++) {
  5358. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5359. --inCount;
  5360. }
  5361. else {
  5362. break;
  5363. }
  5364. }
  5365. if (inCount === 0)
  5366. return false;
  5367. }
  5368. return true;
  5369. };
  5370. return BoundingBox;
  5371. })();
  5372. BABYLON.BoundingBox = BoundingBox;
  5373. })(BABYLON || (BABYLON = {}));
  5374. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5375. (function (BABYLON) {
  5376. var computeBoxExtents = function (axis, box) {
  5377. var p = BABYLON.Vector3.Dot(box.center, axis);
  5378. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5379. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5380. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5381. var r = r0 + r1 + r2;
  5382. return {
  5383. min: p - r,
  5384. max: p + r
  5385. };
  5386. };
  5387. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5388. var axisOverlap = function (axis, box0, box1) {
  5389. var result0 = computeBoxExtents(axis, box0);
  5390. var result1 = computeBoxExtents(axis, box1);
  5391. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5392. };
  5393. var BoundingInfo = (function () {
  5394. function BoundingInfo(minimum, maximum) {
  5395. this.minimum = minimum;
  5396. this.maximum = maximum;
  5397. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5398. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5399. }
  5400. // Methods
  5401. BoundingInfo.prototype._update = function (world) {
  5402. this.boundingBox._update(world);
  5403. this.boundingSphere._update(world);
  5404. };
  5405. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5406. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5407. return false;
  5408. return this.boundingBox.isInFrustum(frustumPlanes);
  5409. };
  5410. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5411. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5412. };
  5413. BoundingInfo.prototype._checkCollision = function (collider) {
  5414. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5415. };
  5416. BoundingInfo.prototype.intersectsPoint = function (point) {
  5417. if (!this.boundingSphere.centerWorld) {
  5418. return false;
  5419. }
  5420. if (!this.boundingSphere.intersectsPoint(point)) {
  5421. return false;
  5422. }
  5423. if (!this.boundingBox.intersectsPoint(point)) {
  5424. return false;
  5425. }
  5426. return true;
  5427. };
  5428. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5429. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5430. return false;
  5431. }
  5432. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5433. return false;
  5434. }
  5435. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5436. return false;
  5437. }
  5438. if (!precise) {
  5439. return true;
  5440. }
  5441. var box0 = this.boundingBox;
  5442. var box1 = boundingInfo.boundingBox;
  5443. if (!axisOverlap(box0.directions[0], box0, box1))
  5444. return false;
  5445. if (!axisOverlap(box0.directions[1], box0, box1))
  5446. return false;
  5447. if (!axisOverlap(box0.directions[2], box0, box1))
  5448. return false;
  5449. if (!axisOverlap(box1.directions[0], box0, box1))
  5450. return false;
  5451. if (!axisOverlap(box1.directions[1], box0, box1))
  5452. return false;
  5453. if (!axisOverlap(box1.directions[2], box0, box1))
  5454. return false;
  5455. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5456. return false;
  5457. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5458. return false;
  5459. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5460. return false;
  5461. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5462. return false;
  5463. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5464. return false;
  5465. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5466. return false;
  5467. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5468. return false;
  5469. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5470. return false;
  5471. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5472. return false;
  5473. return true;
  5474. };
  5475. return BoundingInfo;
  5476. })();
  5477. BABYLON.BoundingInfo = BoundingInfo;
  5478. })(BABYLON || (BABYLON = {}));
  5479. //# sourceMappingURL=babylon.boundingInfo.js.map
  5480. var BABYLON;
  5481. (function (BABYLON) {
  5482. var Light = (function (_super) {
  5483. __extends(Light, _super);
  5484. function Light(name, scene) {
  5485. _super.call(this, name, scene);
  5486. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5487. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5488. this.intensity = 1.0;
  5489. this.range = Number.MAX_VALUE;
  5490. this.includedOnlyMeshes = new Array();
  5491. this.excludedMeshes = new Array();
  5492. this._excludedMeshesIds = new Array();
  5493. this._includedOnlyMeshesIds = new Array();
  5494. scene.lights.push(this);
  5495. }
  5496. Light.prototype.getShadowGenerator = function () {
  5497. return this._shadowGenerator;
  5498. };
  5499. Light.prototype.getAbsolutePosition = function () {
  5500. return BABYLON.Vector3.Zero();
  5501. };
  5502. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5503. };
  5504. Light.prototype._getWorldMatrix = function () {
  5505. return BABYLON.Matrix.Identity();
  5506. };
  5507. Light.prototype.canAffectMesh = function (mesh) {
  5508. if (!mesh) {
  5509. return true;
  5510. }
  5511. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5512. return false;
  5513. }
  5514. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5515. return false;
  5516. }
  5517. return true;
  5518. };
  5519. Light.prototype.getWorldMatrix = function () {
  5520. this._currentRenderId = this.getScene().getRenderId();
  5521. var worldMatrix = this._getWorldMatrix();
  5522. if (this.parent && this.parent.getWorldMatrix) {
  5523. if (!this._parentedWorldMatrix) {
  5524. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5525. }
  5526. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5527. return this._parentedWorldMatrix;
  5528. }
  5529. return worldMatrix;
  5530. };
  5531. Light.prototype.dispose = function () {
  5532. if (this._shadowGenerator) {
  5533. this._shadowGenerator.dispose();
  5534. this._shadowGenerator = null;
  5535. }
  5536. // Remove from scene
  5537. var index = this.getScene().lights.indexOf(this);
  5538. this.getScene().lights.splice(index, 1);
  5539. };
  5540. return Light;
  5541. })(BABYLON.Node);
  5542. BABYLON.Light = Light;
  5543. })(BABYLON || (BABYLON = {}));
  5544. //# sourceMappingURL=babylon.light.js.map
  5545. var BABYLON;
  5546. (function (BABYLON) {
  5547. var PointLight = (function (_super) {
  5548. __extends(PointLight, _super);
  5549. function PointLight(name, position, scene) {
  5550. _super.call(this, name, scene);
  5551. this.position = position;
  5552. }
  5553. PointLight.prototype.getAbsolutePosition = function () {
  5554. return this._transformedPosition ? this._transformedPosition : this.position;
  5555. };
  5556. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5557. if (this.parent && this.parent.getWorldMatrix) {
  5558. if (!this._transformedPosition) {
  5559. this._transformedPosition = BABYLON.Vector3.Zero();
  5560. }
  5561. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5562. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5563. return;
  5564. }
  5565. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5566. };
  5567. PointLight.prototype.getShadowGenerator = function () {
  5568. return null;
  5569. };
  5570. PointLight.prototype._getWorldMatrix = function () {
  5571. if (!this._worldMatrix) {
  5572. this._worldMatrix = BABYLON.Matrix.Identity();
  5573. }
  5574. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5575. return this._worldMatrix;
  5576. };
  5577. return PointLight;
  5578. })(BABYLON.Light);
  5579. BABYLON.PointLight = PointLight;
  5580. })(BABYLON || (BABYLON = {}));
  5581. //# sourceMappingURL=babylon.pointLight.js.map
  5582. var BABYLON;
  5583. (function (BABYLON) {
  5584. var SpotLight = (function (_super) {
  5585. __extends(SpotLight, _super);
  5586. function SpotLight(name, position, direction, angle, exponent, scene) {
  5587. _super.call(this, name, scene);
  5588. this.position = position;
  5589. this.direction = direction;
  5590. this.angle = angle;
  5591. this.exponent = exponent;
  5592. }
  5593. SpotLight.prototype.getAbsolutePosition = function () {
  5594. return this.transformedPosition ? this.transformedPosition : this.position;
  5595. };
  5596. SpotLight.prototype.setDirectionToTarget = function (target) {
  5597. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5598. return this.direction;
  5599. };
  5600. SpotLight.prototype.computeTransformedPosition = function () {
  5601. if (this.parent && this.parent.getWorldMatrix) {
  5602. if (!this.transformedPosition) {
  5603. this.transformedPosition = BABYLON.Vector3.Zero();
  5604. }
  5605. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5606. return true;
  5607. }
  5608. return false;
  5609. };
  5610. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5611. var normalizeDirection;
  5612. if (this.parent && this.parent.getWorldMatrix) {
  5613. if (!this._transformedDirection) {
  5614. this._transformedDirection = BABYLON.Vector3.Zero();
  5615. }
  5616. this.computeTransformedPosition();
  5617. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5618. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5619. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5620. }
  5621. else {
  5622. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5623. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5624. }
  5625. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5626. };
  5627. SpotLight.prototype._getWorldMatrix = function () {
  5628. if (!this._worldMatrix) {
  5629. this._worldMatrix = BABYLON.Matrix.Identity();
  5630. }
  5631. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5632. return this._worldMatrix;
  5633. };
  5634. return SpotLight;
  5635. })(BABYLON.Light);
  5636. BABYLON.SpotLight = SpotLight;
  5637. })(BABYLON || (BABYLON = {}));
  5638. //# sourceMappingURL=babylon.spotLight.js.map
  5639. var BABYLON;
  5640. (function (BABYLON) {
  5641. var DirectionalLight = (function (_super) {
  5642. __extends(DirectionalLight, _super);
  5643. function DirectionalLight(name, direction, scene) {
  5644. _super.call(this, name, scene);
  5645. this.direction = direction;
  5646. this.position = direction.scale(-1);
  5647. }
  5648. DirectionalLight.prototype.getAbsolutePosition = function () {
  5649. return this.transformedPosition ? this.transformedPosition : this.position;
  5650. };
  5651. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5652. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5653. return this.direction;
  5654. };
  5655. DirectionalLight.prototype.computeTransformedPosition = function () {
  5656. if (this.parent && this.parent.getWorldMatrix) {
  5657. if (!this.transformedPosition) {
  5658. this.transformedPosition = BABYLON.Vector3.Zero();
  5659. }
  5660. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5661. return true;
  5662. }
  5663. return false;
  5664. };
  5665. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5666. if (this.parent && this.parent.getWorldMatrix) {
  5667. if (!this._transformedDirection) {
  5668. this._transformedDirection = BABYLON.Vector3.Zero();
  5669. }
  5670. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5671. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5672. return;
  5673. }
  5674. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5675. };
  5676. DirectionalLight.prototype._getWorldMatrix = function () {
  5677. if (!this._worldMatrix) {
  5678. this._worldMatrix = BABYLON.Matrix.Identity();
  5679. }
  5680. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5681. return this._worldMatrix;
  5682. };
  5683. return DirectionalLight;
  5684. })(BABYLON.Light);
  5685. BABYLON.DirectionalLight = DirectionalLight;
  5686. })(BABYLON || (BABYLON = {}));
  5687. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  5688. (function (BABYLON) {
  5689. var ShadowGenerator = (function () {
  5690. function ShadowGenerator(mapSize, light) {
  5691. var _this = this;
  5692. // Members
  5693. this.filter = ShadowGenerator.FILTER_NONE;
  5694. this._darkness = 0;
  5695. this._transparencyShadow = false;
  5696. this._viewMatrix = BABYLON.Matrix.Zero();
  5697. this._projectionMatrix = BABYLON.Matrix.Zero();
  5698. this._transformMatrix = BABYLON.Matrix.Zero();
  5699. this._worldViewProjection = BABYLON.Matrix.Zero();
  5700. this._light = light;
  5701. this._scene = light.getScene();
  5702. light._shadowGenerator = this;
  5703. // Render target
  5704. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5705. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5706. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5707. this._shadowMap.renderParticles = false;
  5708. // Custom render function
  5709. var renderSubMesh = function (subMesh) {
  5710. var mesh = subMesh.getRenderingMesh();
  5711. var scene = _this._scene;
  5712. var engine = scene.getEngine();
  5713. // Culling
  5714. engine.setState(subMesh.getMaterial().backFaceCulling);
  5715. // Managing instances
  5716. var batch = mesh._getInstancesRenderList(subMesh._id);
  5717. if (batch.mustReturn) {
  5718. return;
  5719. }
  5720. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5721. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5722. engine.enableEffect(_this._effect);
  5723. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5724. var material = subMesh.getMaterial();
  5725. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5726. // Alpha test
  5727. if (material && material.needAlphaTesting()) {
  5728. var alphaTexture = material.getAlphaTestTexture();
  5729. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5730. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5731. }
  5732. // Bones
  5733. if (mesh.useBones) {
  5734. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5735. }
  5736. // Draw
  5737. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  5738. }
  5739. else {
  5740. // Need to reset refresh rate of the shadowMap
  5741. _this._shadowMap.resetRefreshCounter();
  5742. }
  5743. };
  5744. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5745. var index;
  5746. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5747. renderSubMesh(opaqueSubMeshes.data[index]);
  5748. }
  5749. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5750. renderSubMesh(alphaTestSubMeshes.data[index]);
  5751. }
  5752. if (_this._transparencyShadow) {
  5753. for (index = 0; index < transparentSubMeshes.length; index++) {
  5754. renderSubMesh(transparentSubMeshes.data[index]);
  5755. }
  5756. }
  5757. };
  5758. }
  5759. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5760. // Static
  5761. get: function () {
  5762. return ShadowGenerator._FILTER_NONE;
  5763. },
  5764. enumerable: true,
  5765. configurable: true
  5766. });
  5767. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5768. get: function () {
  5769. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5770. },
  5771. enumerable: true,
  5772. configurable: true
  5773. });
  5774. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5775. get: function () {
  5776. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5777. },
  5778. enumerable: true,
  5779. configurable: true
  5780. });
  5781. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5782. get: function () {
  5783. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5784. },
  5785. set: function (value) {
  5786. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5787. },
  5788. enumerable: true,
  5789. configurable: true
  5790. });
  5791. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5792. get: function () {
  5793. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5794. },
  5795. set: function (value) {
  5796. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5797. },
  5798. enumerable: true,
  5799. configurable: true
  5800. });
  5801. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5802. var defines = [];
  5803. if (this.useVarianceShadowMap) {
  5804. defines.push("#define VSM");
  5805. }
  5806. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5807. var mesh = subMesh.getMesh();
  5808. var material = subMesh.getMaterial();
  5809. // Alpha test
  5810. if (material && material.needAlphaTesting()) {
  5811. defines.push("#define ALPHATEST");
  5812. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5813. attribs.push(BABYLON.VertexBuffer.UVKind);
  5814. defines.push("#define UV1");
  5815. }
  5816. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5817. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5818. defines.push("#define UV2");
  5819. }
  5820. }
  5821. // Bones
  5822. if (mesh.useBones) {
  5823. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5824. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5825. defines.push("#define BONES");
  5826. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5827. }
  5828. // Instances
  5829. if (useInstances) {
  5830. defines.push("#define INSTANCES");
  5831. attribs.push("world0");
  5832. attribs.push("world1");
  5833. attribs.push("world2");
  5834. attribs.push("world3");
  5835. }
  5836. // Get correct effect
  5837. var join = defines.join("\n");
  5838. if (this._cachedDefines !== join) {
  5839. this._cachedDefines = join;
  5840. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5841. }
  5842. return this._effect.isReady();
  5843. };
  5844. ShadowGenerator.prototype.getShadowMap = function () {
  5845. return this._shadowMap;
  5846. };
  5847. ShadowGenerator.prototype.getLight = function () {
  5848. return this._light;
  5849. };
  5850. // Methods
  5851. ShadowGenerator.prototype.getTransformMatrix = function () {
  5852. var lightPosition = this._light.position;
  5853. var lightDirection = this._light.direction;
  5854. if (this._light.computeTransformedPosition()) {
  5855. lightPosition = this._light.transformedPosition;
  5856. }
  5857. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5858. this._cachedPosition = lightPosition.clone();
  5859. this._cachedDirection = lightDirection.clone();
  5860. var activeCamera = this._scene.activeCamera;
  5861. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5862. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5863. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5864. }
  5865. return this._transformMatrix;
  5866. };
  5867. ShadowGenerator.prototype.getDarkness = function () {
  5868. return this._darkness;
  5869. };
  5870. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5871. if (darkness >= 1.0)
  5872. this._darkness = 1.0;
  5873. else if (darkness <= 0.0)
  5874. this._darkness = 0.0;
  5875. else
  5876. this._darkness = darkness;
  5877. };
  5878. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5879. this._transparencyShadow = hasShadow;
  5880. };
  5881. ShadowGenerator.prototype.dispose = function () {
  5882. this._shadowMap.dispose();
  5883. };
  5884. ShadowGenerator._FILTER_NONE = 0;
  5885. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5886. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5887. return ShadowGenerator;
  5888. })();
  5889. BABYLON.ShadowGenerator = ShadowGenerator;
  5890. })(BABYLON || (BABYLON = {}));
  5891. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5892. var BABYLON;
  5893. (function (BABYLON) {
  5894. var HemisphericLight = (function (_super) {
  5895. __extends(HemisphericLight, _super);
  5896. function HemisphericLight(name, direction, scene) {
  5897. _super.call(this, name, scene);
  5898. this.direction = direction;
  5899. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5900. }
  5901. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5902. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5903. return this.direction;
  5904. };
  5905. HemisphericLight.prototype.getShadowGenerator = function () {
  5906. return null;
  5907. };
  5908. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5909. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5910. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5911. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5912. };
  5913. HemisphericLight.prototype._getWorldMatrix = function () {
  5914. if (!this._worldMatrix) {
  5915. this._worldMatrix = BABYLON.Matrix.Identity();
  5916. }
  5917. return this._worldMatrix;
  5918. };
  5919. return HemisphericLight;
  5920. })(BABYLON.Light);
  5921. BABYLON.HemisphericLight = HemisphericLight;
  5922. })(BABYLON || (BABYLON = {}));
  5923. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  5924. (function (BABYLON) {
  5925. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5926. if (boxMin.x > sphereCenter.x + sphereRadius)
  5927. return false;
  5928. if (sphereCenter.x - sphereRadius > boxMax.x)
  5929. return false;
  5930. if (boxMin.y > sphereCenter.y + sphereRadius)
  5931. return false;
  5932. if (sphereCenter.y - sphereRadius > boxMax.y)
  5933. return false;
  5934. if (boxMin.z > sphereCenter.z + sphereRadius)
  5935. return false;
  5936. if (sphereCenter.z - sphereRadius > boxMax.z)
  5937. return false;
  5938. return true;
  5939. };
  5940. var getLowestRoot = function (a, b, c, maxR) {
  5941. var determinant = b * b - 4.0 * a * c;
  5942. var result = { root: 0, found: false };
  5943. if (determinant < 0)
  5944. return result;
  5945. var sqrtD = Math.sqrt(determinant);
  5946. var r1 = (-b - sqrtD) / (2.0 * a);
  5947. var r2 = (-b + sqrtD) / (2.0 * a);
  5948. if (r1 > r2) {
  5949. var temp = r2;
  5950. r2 = r1;
  5951. r1 = temp;
  5952. }
  5953. if (r1 > 0 && r1 < maxR) {
  5954. result.root = r1;
  5955. result.found = true;
  5956. return result;
  5957. }
  5958. if (r2 > 0 && r2 < maxR) {
  5959. result.root = r2;
  5960. result.found = true;
  5961. return result;
  5962. }
  5963. return result;
  5964. };
  5965. var Collider = (function () {
  5966. function Collider() {
  5967. this.radius = new BABYLON.Vector3(1, 1, 1);
  5968. this.retry = 0;
  5969. this.basePointWorld = BABYLON.Vector3.Zero();
  5970. this.velocityWorld = BABYLON.Vector3.Zero();
  5971. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5972. this._collisionPoint = BABYLON.Vector3.Zero();
  5973. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5974. this._tempVector = BABYLON.Vector3.Zero();
  5975. this._tempVector2 = BABYLON.Vector3.Zero();
  5976. this._tempVector3 = BABYLON.Vector3.Zero();
  5977. this._tempVector4 = BABYLON.Vector3.Zero();
  5978. this._edge = BABYLON.Vector3.Zero();
  5979. this._baseToVertex = BABYLON.Vector3.Zero();
  5980. this._destinationPoint = BABYLON.Vector3.Zero();
  5981. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5982. this._displacementVector = BABYLON.Vector3.Zero();
  5983. }
  5984. // Methods
  5985. Collider.prototype._initialize = function (source, dir, e) {
  5986. this.velocity = dir;
  5987. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5988. this.basePoint = source;
  5989. source.multiplyToRef(this.radius, this.basePointWorld);
  5990. dir.multiplyToRef(this.radius, this.velocityWorld);
  5991. this.velocityWorldLength = this.velocityWorld.length();
  5992. this.epsilon = e;
  5993. this.collisionFound = false;
  5994. };
  5995. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5996. pa.subtractToRef(point, this._tempVector);
  5997. pb.subtractToRef(point, this._tempVector2);
  5998. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5999. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6000. if (d < 0)
  6001. return false;
  6002. pc.subtractToRef(point, this._tempVector3);
  6003. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6004. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6005. if (d < 0)
  6006. return false;
  6007. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6008. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6009. return d >= 0;
  6010. };
  6011. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6012. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6013. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6014. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6015. return false;
  6016. }
  6017. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6018. return false;
  6019. return true;
  6020. };
  6021. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6022. var t0;
  6023. var embeddedInPlane = false;
  6024. if (!subMesh._trianglePlanes) {
  6025. subMesh._trianglePlanes = [];
  6026. }
  6027. if (!subMesh._trianglePlanes[faceIndex]) {
  6028. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6029. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6030. }
  6031. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6032. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6033. return;
  6034. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6035. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6036. if (normalDotVelocity == 0) {
  6037. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6038. return;
  6039. embeddedInPlane = true;
  6040. t0 = 0;
  6041. }
  6042. else {
  6043. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6044. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6045. if (t0 > t1) {
  6046. var temp = t1;
  6047. t1 = t0;
  6048. t0 = temp;
  6049. }
  6050. if (t0 > 1.0 || t1 < 0.0)
  6051. return;
  6052. if (t0 < 0)
  6053. t0 = 0;
  6054. if (t0 > 1.0)
  6055. t0 = 1.0;
  6056. }
  6057. this._collisionPoint.copyFromFloats(0, 0, 0);
  6058. var found = false;
  6059. var t = 1.0;
  6060. if (!embeddedInPlane) {
  6061. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6062. this.velocity.scaleToRef(t0, this._tempVector);
  6063. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6064. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6065. found = true;
  6066. t = t0;
  6067. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6068. }
  6069. }
  6070. if (!found) {
  6071. var velocitySquaredLength = this.velocity.lengthSquared();
  6072. var a = velocitySquaredLength;
  6073. this.basePoint.subtractToRef(p1, this._tempVector);
  6074. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6075. var c = this._tempVector.lengthSquared() - 1.0;
  6076. var lowestRoot = getLowestRoot(a, b, c, t);
  6077. if (lowestRoot.found) {
  6078. t = lowestRoot.root;
  6079. found = true;
  6080. this._collisionPoint.copyFrom(p1);
  6081. }
  6082. this.basePoint.subtractToRef(p2, this._tempVector);
  6083. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6084. c = this._tempVector.lengthSquared() - 1.0;
  6085. lowestRoot = getLowestRoot(a, b, c, t);
  6086. if (lowestRoot.found) {
  6087. t = lowestRoot.root;
  6088. found = true;
  6089. this._collisionPoint.copyFrom(p2);
  6090. }
  6091. this.basePoint.subtractToRef(p3, this._tempVector);
  6092. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6093. c = this._tempVector.lengthSquared() - 1.0;
  6094. lowestRoot = getLowestRoot(a, b, c, t);
  6095. if (lowestRoot.found) {
  6096. t = lowestRoot.root;
  6097. found = true;
  6098. this._collisionPoint.copyFrom(p3);
  6099. }
  6100. p2.subtractToRef(p1, this._edge);
  6101. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6102. var edgeSquaredLength = this._edge.lengthSquared();
  6103. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6104. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6105. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6106. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6107. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6108. lowestRoot = getLowestRoot(a, b, c, t);
  6109. if (lowestRoot.found) {
  6110. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6111. if (f >= 0.0 && f <= 1.0) {
  6112. t = lowestRoot.root;
  6113. found = true;
  6114. this._edge.scaleInPlace(f);
  6115. p1.addToRef(this._edge, this._collisionPoint);
  6116. }
  6117. }
  6118. p3.subtractToRef(p2, this._edge);
  6119. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6120. edgeSquaredLength = this._edge.lengthSquared();
  6121. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6122. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6123. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6124. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6125. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6126. lowestRoot = getLowestRoot(a, b, c, t);
  6127. if (lowestRoot.found) {
  6128. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6129. if (f >= 0.0 && f <= 1.0) {
  6130. t = lowestRoot.root;
  6131. found = true;
  6132. this._edge.scaleInPlace(f);
  6133. p2.addToRef(this._edge, this._collisionPoint);
  6134. }
  6135. }
  6136. p1.subtractToRef(p3, this._edge);
  6137. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6138. edgeSquaredLength = this._edge.lengthSquared();
  6139. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6140. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6141. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6142. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6143. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6144. lowestRoot = getLowestRoot(a, b, c, t);
  6145. if (lowestRoot.found) {
  6146. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6147. if (f >= 0.0 && f <= 1.0) {
  6148. t = lowestRoot.root;
  6149. found = true;
  6150. this._edge.scaleInPlace(f);
  6151. p3.addToRef(this._edge, this._collisionPoint);
  6152. }
  6153. }
  6154. }
  6155. if (found) {
  6156. var distToCollision = t * this.velocity.length();
  6157. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6158. if (!this.intersectionPoint) {
  6159. this.intersectionPoint = this._collisionPoint.clone();
  6160. }
  6161. else {
  6162. this.intersectionPoint.copyFrom(this._collisionPoint);
  6163. }
  6164. this.nearestDistance = distToCollision;
  6165. this.collisionFound = true;
  6166. this.collidedMesh = subMesh.getMesh();
  6167. }
  6168. }
  6169. };
  6170. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6171. for (var i = indexStart; i < indexEnd; i += 3) {
  6172. var p1 = pts[indices[i] - decal];
  6173. var p2 = pts[indices[i + 1] - decal];
  6174. var p3 = pts[indices[i + 2] - decal];
  6175. this._testTriangle(i, subMesh, p3, p2, p1);
  6176. }
  6177. };
  6178. Collider.prototype._getResponse = function (pos, vel) {
  6179. pos.addToRef(vel, this._destinationPoint);
  6180. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6181. this.basePoint.addToRef(vel, pos);
  6182. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6183. this._slidePlaneNormal.normalize();
  6184. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6185. pos.addInPlace(this._displacementVector);
  6186. this.intersectionPoint.addInPlace(this._displacementVector);
  6187. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6188. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6189. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6190. };
  6191. return Collider;
  6192. })();
  6193. BABYLON.Collider = Collider;
  6194. })(BABYLON || (BABYLON = {}));
  6195. //# sourceMappingURL=babylon.collider.js.map
  6196. var BABYLON;
  6197. (function (BABYLON) {
  6198. var Camera = (function (_super) {
  6199. __extends(Camera, _super);
  6200. function Camera(name, position, scene) {
  6201. _super.call(this, name, scene);
  6202. this.position = position;
  6203. // Members
  6204. this.upVector = BABYLON.Vector3.Up();
  6205. this.orthoLeft = null;
  6206. this.orthoRight = null;
  6207. this.orthoBottom = null;
  6208. this.orthoTop = null;
  6209. this.fov = 0.8;
  6210. this.minZ = 1.0;
  6211. this.maxZ = 10000.0;
  6212. this.inertia = 0.9;
  6213. this.mode = Camera.PERSPECTIVE_CAMERA;
  6214. this.isIntermediate = false;
  6215. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6216. this.subCameras = [];
  6217. this.layerMask = 0xFFFFFFFF;
  6218. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6219. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6220. this._projectionMatrix = new BABYLON.Matrix();
  6221. this._postProcesses = new Array();
  6222. this._postProcessesTakenIndices = [];
  6223. scene.cameras.push(this);
  6224. if (!scene.activeCamera) {
  6225. scene.activeCamera = this;
  6226. }
  6227. }
  6228. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6229. get: function () {
  6230. return Camera._PERSPECTIVE_CAMERA;
  6231. },
  6232. enumerable: true,
  6233. configurable: true
  6234. });
  6235. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6236. get: function () {
  6237. return Camera._ORTHOGRAPHIC_CAMERA;
  6238. },
  6239. enumerable: true,
  6240. configurable: true
  6241. });
  6242. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6243. get: function () {
  6244. return Camera._FOVMODE_VERTICAL_FIXED;
  6245. },
  6246. enumerable: true,
  6247. configurable: true
  6248. });
  6249. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6250. get: function () {
  6251. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6252. },
  6253. enumerable: true,
  6254. configurable: true
  6255. });
  6256. //Cache
  6257. Camera.prototype._initCache = function () {
  6258. _super.prototype._initCache.call(this);
  6259. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6260. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6261. this._cache.mode = undefined;
  6262. this._cache.minZ = undefined;
  6263. this._cache.maxZ = undefined;
  6264. this._cache.fov = undefined;
  6265. this._cache.aspectRatio = undefined;
  6266. this._cache.orthoLeft = undefined;
  6267. this._cache.orthoRight = undefined;
  6268. this._cache.orthoBottom = undefined;
  6269. this._cache.orthoTop = undefined;
  6270. this._cache.renderWidth = undefined;
  6271. this._cache.renderHeight = undefined;
  6272. };
  6273. Camera.prototype._updateCache = function (ignoreParentClass) {
  6274. if (!ignoreParentClass) {
  6275. _super.prototype._updateCache.call(this);
  6276. }
  6277. var engine = this.getEngine();
  6278. this._cache.position.copyFrom(this.position);
  6279. this._cache.upVector.copyFrom(this.upVector);
  6280. this._cache.mode = this.mode;
  6281. this._cache.minZ = this.minZ;
  6282. this._cache.maxZ = this.maxZ;
  6283. this._cache.fov = this.fov;
  6284. this._cache.aspectRatio = engine.getAspectRatio(this);
  6285. this._cache.orthoLeft = this.orthoLeft;
  6286. this._cache.orthoRight = this.orthoRight;
  6287. this._cache.orthoBottom = this.orthoBottom;
  6288. this._cache.orthoTop = this.orthoTop;
  6289. this._cache.renderWidth = engine.getRenderWidth();
  6290. this._cache.renderHeight = engine.getRenderHeight();
  6291. };
  6292. Camera.prototype._updateFromScene = function () {
  6293. this.updateCache();
  6294. this._update();
  6295. };
  6296. // Synchronized
  6297. Camera.prototype._isSynchronized = function () {
  6298. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6299. };
  6300. Camera.prototype._isSynchronizedViewMatrix = function () {
  6301. if (!_super.prototype._isSynchronized.call(this))
  6302. return false;
  6303. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6304. };
  6305. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6306. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6307. if (!check) {
  6308. return false;
  6309. }
  6310. var engine = this.getEngine();
  6311. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6312. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6313. }
  6314. else {
  6315. 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();
  6316. }
  6317. return check;
  6318. };
  6319. // Controls
  6320. Camera.prototype.attachControl = function (element) {
  6321. };
  6322. Camera.prototype.detachControl = function (element) {
  6323. };
  6324. Camera.prototype._update = function () {
  6325. };
  6326. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6327. if (insertAt === void 0) { insertAt = null; }
  6328. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6329. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6330. return 0;
  6331. }
  6332. if (insertAt == null || insertAt < 0) {
  6333. this._postProcesses.push(postProcess);
  6334. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6335. return this._postProcesses.length - 1;
  6336. }
  6337. var add = 0;
  6338. if (this._postProcesses[insertAt]) {
  6339. var start = this._postProcesses.length - 1;
  6340. for (var i = start; i >= insertAt + 1; --i) {
  6341. this._postProcesses[i + 1] = this._postProcesses[i];
  6342. }
  6343. add = 1;
  6344. }
  6345. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6346. if (this._postProcessesTakenIndices[i] < insertAt) {
  6347. continue;
  6348. }
  6349. start = this._postProcessesTakenIndices.length - 1;
  6350. for (var j = start; j >= i; --j) {
  6351. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6352. }
  6353. this._postProcessesTakenIndices[i] = insertAt;
  6354. break;
  6355. }
  6356. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6357. this._postProcessesTakenIndices.push(insertAt);
  6358. }
  6359. var result = insertAt + add;
  6360. this._postProcesses[result] = postProcess;
  6361. return result;
  6362. };
  6363. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6364. if (atIndices === void 0) { atIndices = null; }
  6365. var result = [];
  6366. if (!atIndices) {
  6367. var length = this._postProcesses.length;
  6368. for (var i = 0; i < length; i++) {
  6369. if (this._postProcesses[i] !== postProcess) {
  6370. continue;
  6371. }
  6372. delete this._postProcesses[i];
  6373. var index = this._postProcessesTakenIndices.indexOf(i);
  6374. this._postProcessesTakenIndices.splice(index, 1);
  6375. }
  6376. }
  6377. else {
  6378. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6379. for (i = 0; i < atIndices.length; i++) {
  6380. var foundPostProcess = this._postProcesses[atIndices[i]];
  6381. if (foundPostProcess !== postProcess) {
  6382. result.push(i);
  6383. continue;
  6384. }
  6385. delete this._postProcesses[atIndices[i]];
  6386. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6387. this._postProcessesTakenIndices.splice(index, 1);
  6388. }
  6389. }
  6390. return result;
  6391. };
  6392. Camera.prototype.getWorldMatrix = function () {
  6393. if (!this._worldMatrix) {
  6394. this._worldMatrix = BABYLON.Matrix.Identity();
  6395. }
  6396. var viewMatrix = this.getViewMatrix();
  6397. viewMatrix.invertToRef(this._worldMatrix);
  6398. return this._worldMatrix;
  6399. };
  6400. Camera.prototype._getViewMatrix = function () {
  6401. return BABYLON.Matrix.Identity();
  6402. };
  6403. Camera.prototype.getViewMatrix = function () {
  6404. this._computedViewMatrix = this._computeViewMatrix();
  6405. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6406. return this._computedViewMatrix;
  6407. }
  6408. if (!this._worldMatrix) {
  6409. this._worldMatrix = BABYLON.Matrix.Identity();
  6410. }
  6411. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6412. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6413. this._computedViewMatrix.invert();
  6414. this._currentRenderId = this.getScene().getRenderId();
  6415. return this._computedViewMatrix;
  6416. };
  6417. Camera.prototype._computeViewMatrix = function (force) {
  6418. if (!force && this._isSynchronizedViewMatrix()) {
  6419. return this._computedViewMatrix;
  6420. }
  6421. this._computedViewMatrix = this._getViewMatrix();
  6422. if (!this.parent || !this.parent.getWorldMatrix) {
  6423. this._currentRenderId = this.getScene().getRenderId();
  6424. }
  6425. return this._computedViewMatrix;
  6426. };
  6427. Camera.prototype.getProjectionMatrix = function (force) {
  6428. if (!force && this._isSynchronizedProjectionMatrix()) {
  6429. return this._projectionMatrix;
  6430. }
  6431. var engine = this.getEngine();
  6432. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6433. if (this.minZ <= 0) {
  6434. this.minZ = 0.1;
  6435. }
  6436. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  6437. return this._projectionMatrix;
  6438. }
  6439. var halfWidth = engine.getRenderWidth() / 2.0;
  6440. var halfHeight = engine.getRenderHeight() / 2.0;
  6441. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6442. return this._projectionMatrix;
  6443. };
  6444. Camera.prototype.dispose = function () {
  6445. // Remove from scene
  6446. var index = this.getScene().cameras.indexOf(this);
  6447. this.getScene().cameras.splice(index, 1);
  6448. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6449. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6450. }
  6451. };
  6452. // Statics
  6453. Camera._PERSPECTIVE_CAMERA = 0;
  6454. Camera._ORTHOGRAPHIC_CAMERA = 1;
  6455. Camera._FOVMODE_VERTICAL_FIXED = 0;
  6456. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  6457. return Camera;
  6458. })(BABYLON.Node);
  6459. BABYLON.Camera = Camera;
  6460. })(BABYLON || (BABYLON = {}));
  6461. //# sourceMappingURL=babylon.camera.js.map
  6462. var BABYLON;
  6463. (function (BABYLON) {
  6464. var TargetCamera = (function (_super) {
  6465. __extends(TargetCamera, _super);
  6466. function TargetCamera(name, position, scene) {
  6467. _super.call(this, name, position, scene);
  6468. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6469. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6470. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6471. this.speed = 2.0;
  6472. this.noRotationConstraint = false;
  6473. this.lockedTarget = null;
  6474. this._currentTarget = BABYLON.Vector3.Zero();
  6475. this._viewMatrix = BABYLON.Matrix.Zero();
  6476. this._camMatrix = BABYLON.Matrix.Zero();
  6477. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6478. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6479. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6480. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6481. this._lookAtTemp = BABYLON.Matrix.Zero();
  6482. this._tempMatrix = BABYLON.Matrix.Zero();
  6483. }
  6484. TargetCamera.prototype._getLockedTargetPosition = function () {
  6485. if (!this.lockedTarget) {
  6486. return null;
  6487. }
  6488. return this.lockedTarget.position || this.lockedTarget;
  6489. };
  6490. // Cache
  6491. TargetCamera.prototype._initCache = function () {
  6492. _super.prototype._initCache.call(this);
  6493. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6494. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6495. };
  6496. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6497. if (!ignoreParentClass) {
  6498. _super.prototype._updateCache.call(this);
  6499. }
  6500. var lockedTargetPosition = this._getLockedTargetPosition();
  6501. if (!lockedTargetPosition) {
  6502. this._cache.lockedTarget = null;
  6503. }
  6504. else {
  6505. if (!this._cache.lockedTarget) {
  6506. this._cache.lockedTarget = lockedTargetPosition.clone();
  6507. }
  6508. else {
  6509. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6510. }
  6511. }
  6512. this._cache.rotation.copyFrom(this.rotation);
  6513. };
  6514. // Synchronized
  6515. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6516. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6517. return false;
  6518. }
  6519. var lockedTargetPosition = this._getLockedTargetPosition();
  6520. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6521. };
  6522. // Methods
  6523. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6524. var engine = this.getEngine();
  6525. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6526. };
  6527. // Target
  6528. TargetCamera.prototype.setTarget = function (target) {
  6529. this.upVector.normalize();
  6530. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6531. this._camMatrix.invert();
  6532. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6533. var vDir = target.subtract(this.position);
  6534. if (vDir.x >= 0.0) {
  6535. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6536. }
  6537. else {
  6538. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6539. }
  6540. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6541. if (isNaN(this.rotation.x)) {
  6542. this.rotation.x = 0;
  6543. }
  6544. if (isNaN(this.rotation.y)) {
  6545. this.rotation.y = 0;
  6546. }
  6547. if (isNaN(this.rotation.z)) {
  6548. this.rotation.z = 0;
  6549. }
  6550. };
  6551. TargetCamera.prototype.getTarget = function () {
  6552. return this._currentTarget;
  6553. };
  6554. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6555. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6556. };
  6557. TargetCamera.prototype._updatePosition = function () {
  6558. this.position.addInPlace(this.cameraDirection);
  6559. };
  6560. TargetCamera.prototype._update = function () {
  6561. var needToMove = this._decideIfNeedsToMove();
  6562. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6563. // Move
  6564. if (needToMove) {
  6565. this._updatePosition();
  6566. }
  6567. // Rotate
  6568. if (needToRotate) {
  6569. this.rotation.x += this.cameraRotation.x;
  6570. this.rotation.y += this.cameraRotation.y;
  6571. if (!this.noRotationConstraint) {
  6572. var limit = (Math.PI / 2) * 0.95;
  6573. if (this.rotation.x > limit)
  6574. this.rotation.x = limit;
  6575. if (this.rotation.x < -limit)
  6576. this.rotation.x = -limit;
  6577. }
  6578. }
  6579. // Inertia
  6580. if (needToMove) {
  6581. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6582. this.cameraDirection.x = 0;
  6583. }
  6584. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6585. this.cameraDirection.y = 0;
  6586. }
  6587. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6588. this.cameraDirection.z = 0;
  6589. }
  6590. this.cameraDirection.scaleInPlace(this.inertia);
  6591. }
  6592. if (needToRotate) {
  6593. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6594. this.cameraRotation.x = 0;
  6595. }
  6596. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6597. this.cameraRotation.y = 0;
  6598. }
  6599. this.cameraRotation.scaleInPlace(this.inertia);
  6600. }
  6601. };
  6602. TargetCamera.prototype._getViewMatrix = function () {
  6603. if (!this.lockedTarget) {
  6604. // Compute
  6605. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6606. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6607. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6608. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6609. this._lookAtTemp.invert();
  6610. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6611. }
  6612. else {
  6613. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6614. }
  6615. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6616. // Computing target and final matrix
  6617. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6618. }
  6619. else {
  6620. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6621. }
  6622. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6623. return this._viewMatrix;
  6624. };
  6625. return TargetCamera;
  6626. })(BABYLON.Camera);
  6627. BABYLON.TargetCamera = TargetCamera;
  6628. })(BABYLON || (BABYLON = {}));
  6629. //# sourceMappingURL=babylon.targetCamera.js.map
  6630. var BABYLON;
  6631. (function (BABYLON) {
  6632. var FollowCamera = (function (_super) {
  6633. __extends(FollowCamera, _super);
  6634. function FollowCamera(name, position, scene) {
  6635. _super.call(this, name, position, scene);
  6636. this.radius = 12;
  6637. this.rotationOffset = 0;
  6638. this.heightOffset = 4;
  6639. this.cameraAcceleration = 0.05;
  6640. this.maxCameraSpeed = 20;
  6641. }
  6642. FollowCamera.prototype.getRadians = function (degrees) {
  6643. return degrees * Math.PI / 180;
  6644. };
  6645. FollowCamera.prototype.follow = function (cameraTarget) {
  6646. if (!cameraTarget)
  6647. return;
  6648. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6649. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6650. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6651. var dx = targetX - this.position.x;
  6652. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6653. var dz = (targetZ) - this.position.z;
  6654. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  6655. var vy = dy * this.cameraAcceleration;
  6656. var vz = dz * this.cameraAcceleration * 2;
  6657. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6658. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6659. }
  6660. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6661. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6662. }
  6663. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6664. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6665. }
  6666. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6667. this.setTarget(cameraTarget.position);
  6668. };
  6669. FollowCamera.prototype._update = function () {
  6670. _super.prototype._update.call(this);
  6671. this.follow(this.target);
  6672. };
  6673. return FollowCamera;
  6674. })(BABYLON.TargetCamera);
  6675. BABYLON.FollowCamera = FollowCamera;
  6676. })(BABYLON || (BABYLON = {}));
  6677. //# sourceMappingURL=babylon.followCamera.js.map
  6678. var BABYLON;
  6679. (function (BABYLON) {
  6680. var FreeCamera = (function (_super) {
  6681. __extends(FreeCamera, _super);
  6682. function FreeCamera(name, position, scene) {
  6683. _super.call(this, name, position, scene);
  6684. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6685. this.keysUp = [38];
  6686. this.keysDown = [40];
  6687. this.keysLeft = [37];
  6688. this.keysRight = [39];
  6689. this.checkCollisions = false;
  6690. this.applyGravity = false;
  6691. this.angularSensibility = 2000.0;
  6692. this._keys = [];
  6693. this._collider = new BABYLON.Collider();
  6694. this._needMoveForGravity = true;
  6695. this._oldPosition = BABYLON.Vector3.Zero();
  6696. this._diffPosition = BABYLON.Vector3.Zero();
  6697. this._newPosition = BABYLON.Vector3.Zero();
  6698. }
  6699. // Controls
  6700. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6701. var _this = this;
  6702. var previousPosition;
  6703. var engine = this.getEngine();
  6704. if (this._attachedElement) {
  6705. return;
  6706. }
  6707. this._attachedElement = element;
  6708. if (this._onMouseDown === undefined) {
  6709. this._onMouseDown = function (evt) {
  6710. previousPosition = {
  6711. x: evt.clientX,
  6712. y: evt.clientY
  6713. };
  6714. if (!noPreventDefault) {
  6715. evt.preventDefault();
  6716. }
  6717. };
  6718. this._onMouseUp = function (evt) {
  6719. previousPosition = null;
  6720. if (!noPreventDefault) {
  6721. evt.preventDefault();
  6722. }
  6723. };
  6724. this._onMouseOut = function (evt) {
  6725. previousPosition = null;
  6726. _this._keys = [];
  6727. if (!noPreventDefault) {
  6728. evt.preventDefault();
  6729. }
  6730. };
  6731. this._onMouseMove = function (evt) {
  6732. if (!previousPosition && !engine.isPointerLock) {
  6733. return;
  6734. }
  6735. var offsetX;
  6736. var offsetY;
  6737. if (!engine.isPointerLock) {
  6738. offsetX = evt.clientX - previousPosition.x;
  6739. offsetY = evt.clientY - previousPosition.y;
  6740. }
  6741. else {
  6742. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6743. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6744. }
  6745. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6746. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6747. previousPosition = {
  6748. x: evt.clientX,
  6749. y: evt.clientY
  6750. };
  6751. if (!noPreventDefault) {
  6752. evt.preventDefault();
  6753. }
  6754. };
  6755. this._onKeyDown = function (evt) {
  6756. 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) {
  6757. var index = _this._keys.indexOf(evt.keyCode);
  6758. if (index === -1) {
  6759. _this._keys.push(evt.keyCode);
  6760. }
  6761. if (!noPreventDefault) {
  6762. evt.preventDefault();
  6763. }
  6764. }
  6765. };
  6766. this._onKeyUp = function (evt) {
  6767. 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) {
  6768. var index = _this._keys.indexOf(evt.keyCode);
  6769. if (index >= 0) {
  6770. _this._keys.splice(index, 1);
  6771. }
  6772. if (!noPreventDefault) {
  6773. evt.preventDefault();
  6774. }
  6775. }
  6776. };
  6777. this._onLostFocus = function () {
  6778. _this._keys = [];
  6779. };
  6780. this._reset = function () {
  6781. _this._keys = [];
  6782. previousPosition = null;
  6783. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6784. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6785. };
  6786. }
  6787. element.addEventListener("mousedown", this._onMouseDown, false);
  6788. element.addEventListener("mouseup", this._onMouseUp, false);
  6789. element.addEventListener("mouseout", this._onMouseOut, false);
  6790. element.addEventListener("mousemove", this._onMouseMove, false);
  6791. BABYLON.Tools.RegisterTopRootEvents([
  6792. { name: "keydown", handler: this._onKeyDown },
  6793. { name: "keyup", handler: this._onKeyUp },
  6794. { name: "blur", handler: this._onLostFocus }
  6795. ]);
  6796. };
  6797. FreeCamera.prototype.detachControl = function (element) {
  6798. if (this._attachedElement != element) {
  6799. return;
  6800. }
  6801. element.removeEventListener("mousedown", this._onMouseDown);
  6802. element.removeEventListener("mouseup", this._onMouseUp);
  6803. element.removeEventListener("mouseout", this._onMouseOut);
  6804. element.removeEventListener("mousemove", this._onMouseMove);
  6805. BABYLON.Tools.UnregisterTopRootEvents([
  6806. { name: "keydown", handler: this._onKeyDown },
  6807. { name: "keyup", handler: this._onKeyUp },
  6808. { name: "blur", handler: this._onLostFocus }
  6809. ]);
  6810. this._attachedElement = null;
  6811. if (this._reset) {
  6812. this._reset();
  6813. }
  6814. };
  6815. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6816. var globalPosition;
  6817. if (this.parent) {
  6818. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6819. }
  6820. else {
  6821. globalPosition = this.position;
  6822. }
  6823. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6824. this._collider.radius = this.ellipsoid;
  6825. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6826. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6827. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6828. this.position.addInPlace(this._diffPosition);
  6829. if (this.onCollide) {
  6830. this.onCollide(this._collider.collidedMesh);
  6831. }
  6832. }
  6833. };
  6834. FreeCamera.prototype._checkInputs = function () {
  6835. if (!this._localDirection) {
  6836. this._localDirection = BABYLON.Vector3.Zero();
  6837. this._transformedDirection = BABYLON.Vector3.Zero();
  6838. }
  6839. for (var index = 0; index < this._keys.length; index++) {
  6840. var keyCode = this._keys[index];
  6841. var speed = this._computeLocalCameraSpeed();
  6842. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6843. this._localDirection.copyFromFloats(-speed, 0, 0);
  6844. }
  6845. else if (this.keysUp.indexOf(keyCode) !== -1) {
  6846. this._localDirection.copyFromFloats(0, 0, speed);
  6847. }
  6848. else if (this.keysRight.indexOf(keyCode) !== -1) {
  6849. this._localDirection.copyFromFloats(speed, 0, 0);
  6850. }
  6851. else if (this.keysDown.indexOf(keyCode) !== -1) {
  6852. this._localDirection.copyFromFloats(0, 0, -speed);
  6853. }
  6854. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6855. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6856. this.cameraDirection.addInPlace(this._transformedDirection);
  6857. }
  6858. };
  6859. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6860. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6861. };
  6862. FreeCamera.prototype._updatePosition = function () {
  6863. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6864. this._collideWithWorld(this.cameraDirection);
  6865. if (this.applyGravity) {
  6866. var oldPosition = this.position;
  6867. this._collideWithWorld(this.getScene().gravity);
  6868. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6869. }
  6870. }
  6871. else {
  6872. this.position.addInPlace(this.cameraDirection);
  6873. }
  6874. };
  6875. FreeCamera.prototype._update = function () {
  6876. this._checkInputs();
  6877. _super.prototype._update.call(this);
  6878. };
  6879. return FreeCamera;
  6880. })(BABYLON.TargetCamera);
  6881. BABYLON.FreeCamera = FreeCamera;
  6882. })(BABYLON || (BABYLON = {}));
  6883. //# sourceMappingURL=babylon.freeCamera.js.map
  6884. var BABYLON;
  6885. (function (BABYLON) {
  6886. // We're mainly based on the logic defined into the FreeCamera code
  6887. var TouchCamera = (function (_super) {
  6888. __extends(TouchCamera, _super);
  6889. function TouchCamera(name, position, scene) {
  6890. _super.call(this, name, position, scene);
  6891. this._offsetX = null;
  6892. this._offsetY = null;
  6893. this._pointerCount = 0;
  6894. this._pointerPressed = [];
  6895. this.angularSensibility = 200000.0;
  6896. this.moveSensibility = 500.0;
  6897. }
  6898. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6899. var _this = this;
  6900. var previousPosition;
  6901. if (this._attachedCanvas) {
  6902. return;
  6903. }
  6904. this._attachedCanvas = canvas;
  6905. if (this._onPointerDown === undefined) {
  6906. this._onPointerDown = function (evt) {
  6907. if (!noPreventDefault) {
  6908. evt.preventDefault();
  6909. }
  6910. _this._pointerPressed.push(evt.pointerId);
  6911. if (_this._pointerPressed.length !== 1) {
  6912. return;
  6913. }
  6914. previousPosition = {
  6915. x: evt.clientX,
  6916. y: evt.clientY
  6917. };
  6918. };
  6919. this._onPointerUp = function (evt) {
  6920. if (!noPreventDefault) {
  6921. evt.preventDefault();
  6922. }
  6923. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6924. if (index === -1) {
  6925. return;
  6926. }
  6927. _this._pointerPressed.splice(index, 1);
  6928. if (index != 0) {
  6929. return;
  6930. }
  6931. previousPosition = null;
  6932. _this._offsetX = null;
  6933. _this._offsetY = null;
  6934. };
  6935. this._onPointerMove = function (evt) {
  6936. if (!noPreventDefault) {
  6937. evt.preventDefault();
  6938. }
  6939. if (!previousPosition) {
  6940. return;
  6941. }
  6942. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6943. if (index != 0) {
  6944. return;
  6945. }
  6946. _this._offsetX = evt.clientX - previousPosition.x;
  6947. _this._offsetY = -(evt.clientY - previousPosition.y);
  6948. };
  6949. this._onLostFocus = function () {
  6950. _this._offsetX = null;
  6951. _this._offsetY = null;
  6952. };
  6953. }
  6954. canvas.addEventListener("pointerdown", this._onPointerDown);
  6955. canvas.addEventListener("pointerup", this._onPointerUp);
  6956. canvas.addEventListener("pointerout", this._onPointerUp);
  6957. canvas.addEventListener("pointermove", this._onPointerMove);
  6958. BABYLON.Tools.RegisterTopRootEvents([
  6959. { name: "blur", handler: this._onLostFocus }
  6960. ]);
  6961. };
  6962. TouchCamera.prototype.detachControl = function (canvas) {
  6963. if (this._attachedCanvas != canvas) {
  6964. return;
  6965. }
  6966. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6967. canvas.removeEventListener("pointerup", this._onPointerUp);
  6968. canvas.removeEventListener("pointerout", this._onPointerUp);
  6969. canvas.removeEventListener("pointermove", this._onPointerMove);
  6970. BABYLON.Tools.UnregisterTopRootEvents([
  6971. { name: "blur", handler: this._onLostFocus }
  6972. ]);
  6973. this._attachedCanvas = null;
  6974. };
  6975. TouchCamera.prototype._checkInputs = function () {
  6976. if (!this._offsetX) {
  6977. return;
  6978. }
  6979. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6980. if (this._pointerPressed.length > 1) {
  6981. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6982. }
  6983. else {
  6984. var speed = this._computeLocalCameraSpeed();
  6985. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6986. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6987. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6988. }
  6989. };
  6990. return TouchCamera;
  6991. })(BABYLON.FreeCamera);
  6992. BABYLON.TouchCamera = TouchCamera;
  6993. })(BABYLON || (BABYLON = {}));
  6994. //# sourceMappingURL=babylon.touchCamera.js.map
  6995. var BABYLON;
  6996. (function (BABYLON) {
  6997. // We're mainly based on the logic defined into the FreeCamera code
  6998. var DeviceOrientationCamera = (function (_super) {
  6999. __extends(DeviceOrientationCamera, _super);
  7000. function DeviceOrientationCamera(name, position, scene) {
  7001. var _this = this;
  7002. _super.call(this, name, position, scene);
  7003. this._offsetX = null;
  7004. this._offsetY = null;
  7005. this._orientationGamma = 0;
  7006. this._orientationBeta = 0;
  7007. this._initialOrientationGamma = 0;
  7008. this._initialOrientationBeta = 0;
  7009. this.angularSensibility = 10000.0;
  7010. this.moveSensibility = 50.0;
  7011. window.addEventListener("resize", function () {
  7012. _this._initialOrientationGamma = null;
  7013. }, false);
  7014. }
  7015. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7016. var _this = this;
  7017. if (this._attachedCanvas) {
  7018. return;
  7019. }
  7020. this._attachedCanvas = canvas;
  7021. if (!this._orientationChanged) {
  7022. this._orientationChanged = function (evt) {
  7023. if (!_this._initialOrientationGamma) {
  7024. _this._initialOrientationGamma = evt.gamma;
  7025. _this._initialOrientationBeta = evt.beta;
  7026. }
  7027. _this._orientationGamma = evt.gamma;
  7028. _this._orientationBeta = evt.beta;
  7029. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7030. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7031. };
  7032. }
  7033. window.addEventListener("deviceorientation", this._orientationChanged);
  7034. };
  7035. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7036. if (this._attachedCanvas != canvas) {
  7037. return;
  7038. }
  7039. window.removeEventListener("deviceorientation", this._orientationChanged);
  7040. this._attachedCanvas = null;
  7041. this._orientationGamma = 0;
  7042. this._orientationBeta = 0;
  7043. this._initialOrientationGamma = 0;
  7044. this._initialOrientationBeta = 0;
  7045. };
  7046. DeviceOrientationCamera.prototype._checkInputs = function () {
  7047. if (!this._offsetX) {
  7048. return;
  7049. }
  7050. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7051. var speed = this._computeLocalCameraSpeed();
  7052. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7053. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7054. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7055. };
  7056. return DeviceOrientationCamera;
  7057. })(BABYLON.FreeCamera);
  7058. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7059. })(BABYLON || (BABYLON = {}));
  7060. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7061. var BABYLON;
  7062. (function (BABYLON) {
  7063. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7064. var ArcRotateCamera = (function (_super) {
  7065. __extends(ArcRotateCamera, _super);
  7066. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7067. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7068. this.alpha = alpha;
  7069. this.beta = beta;
  7070. this.radius = radius;
  7071. this.target = target;
  7072. this.inertialAlphaOffset = 0;
  7073. this.inertialBetaOffset = 0;
  7074. this.inertialRadiusOffset = 0;
  7075. this.lowerAlphaLimit = null;
  7076. this.upperAlphaLimit = null;
  7077. this.lowerBetaLimit = 0.01;
  7078. this.upperBetaLimit = Math.PI;
  7079. this.lowerRadiusLimit = null;
  7080. this.upperRadiusLimit = null;
  7081. this.angularSensibility = 1000.0;
  7082. this.wheelPrecision = 3.0;
  7083. this.keysUp = [38];
  7084. this.keysDown = [40];
  7085. this.keysLeft = [37];
  7086. this.keysRight = [39];
  7087. this.zoomOnFactor = 1;
  7088. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7089. this._keys = [];
  7090. this._viewMatrix = new BABYLON.Matrix();
  7091. this.checkCollisions = false;
  7092. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7093. this._collider = new BABYLON.Collider();
  7094. this._previousPosition = BABYLON.Vector3.Zero();
  7095. this._collisionVelocity = BABYLON.Vector3.Zero();
  7096. this._newPosition = BABYLON.Vector3.Zero();
  7097. // Pinch
  7098. // value for pinch step scaling
  7099. // set to 20 by default
  7100. this.pinchPrecision = 20;
  7101. this.getViewMatrix();
  7102. }
  7103. ArcRotateCamera.prototype._getTargetPosition = function () {
  7104. return this.target.position || this.target;
  7105. };
  7106. // Cache
  7107. ArcRotateCamera.prototype._initCache = function () {
  7108. _super.prototype._initCache.call(this);
  7109. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7110. this._cache.alpha = undefined;
  7111. this._cache.beta = undefined;
  7112. this._cache.radius = undefined;
  7113. this._cache.targetScreenOffset = undefined;
  7114. };
  7115. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7116. if (!ignoreParentClass) {
  7117. _super.prototype._updateCache.call(this);
  7118. }
  7119. this._cache.target.copyFrom(this._getTargetPosition());
  7120. this._cache.alpha = this.alpha;
  7121. this._cache.beta = this.beta;
  7122. this._cache.radius = this.radius;
  7123. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7124. };
  7125. // Synchronized
  7126. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7127. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7128. return false;
  7129. 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);
  7130. };
  7131. // Methods
  7132. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7133. var _this = this;
  7134. var previousPosition;
  7135. var pointerId;
  7136. // to know if pinch started
  7137. var pinchStarted = false;
  7138. // two pinch point on X
  7139. // that will use for find if user action is pinch open or pinch close
  7140. var pinchPointX1, pinchPointX2;
  7141. if (this._attachedElement) {
  7142. return;
  7143. }
  7144. this._attachedElement = element;
  7145. var engine = this.getEngine();
  7146. if (this._onPointerDown === undefined) {
  7147. this._onPointerDown = function (evt) {
  7148. if (pointerId) {
  7149. return;
  7150. }
  7151. pointerId = evt.pointerId;
  7152. previousPosition = {
  7153. x: evt.clientX,
  7154. y: evt.clientY
  7155. };
  7156. if (!noPreventDefault) {
  7157. evt.preventDefault();
  7158. }
  7159. };
  7160. this._onPointerUp = function (evt) {
  7161. previousPosition = null;
  7162. pointerId = null;
  7163. if (!noPreventDefault) {
  7164. evt.preventDefault();
  7165. }
  7166. };
  7167. this._onPointerMove = function (evt) {
  7168. if (!previousPosition) {
  7169. return;
  7170. }
  7171. if (pointerId !== evt.pointerId) {
  7172. return;
  7173. }
  7174. // return pinch is started
  7175. if (pinchStarted) {
  7176. return;
  7177. }
  7178. var offsetX = evt.clientX - previousPosition.x;
  7179. var offsetY = evt.clientY - previousPosition.y;
  7180. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7181. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7182. previousPosition = {
  7183. x: evt.clientX,
  7184. y: evt.clientY
  7185. };
  7186. if (!noPreventDefault) {
  7187. evt.preventDefault();
  7188. }
  7189. };
  7190. this._onMouseMove = function (evt) {
  7191. if (!engine.isPointerLock) {
  7192. return;
  7193. }
  7194. // return pinch is started
  7195. if (pinchStarted) {
  7196. return;
  7197. }
  7198. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7199. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7200. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7201. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7202. if (!noPreventDefault) {
  7203. evt.preventDefault();
  7204. }
  7205. };
  7206. this._wheel = function (event) {
  7207. var delta = 0;
  7208. if (event.wheelDelta) {
  7209. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7210. }
  7211. else if (event.detail) {
  7212. delta = -event.detail / _this.wheelPrecision;
  7213. }
  7214. if (delta)
  7215. _this.inertialRadiusOffset += delta;
  7216. if (event.preventDefault) {
  7217. if (!noPreventDefault) {
  7218. event.preventDefault();
  7219. }
  7220. }
  7221. };
  7222. this._onKeyDown = function (evt) {
  7223. 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) {
  7224. var index = _this._keys.indexOf(evt.keyCode);
  7225. if (index === -1) {
  7226. _this._keys.push(evt.keyCode);
  7227. }
  7228. if (evt.preventDefault) {
  7229. if (!noPreventDefault) {
  7230. evt.preventDefault();
  7231. }
  7232. }
  7233. }
  7234. };
  7235. this._onKeyUp = function (evt) {
  7236. 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) {
  7237. var index = _this._keys.indexOf(evt.keyCode);
  7238. if (index >= 0) {
  7239. _this._keys.splice(index, 1);
  7240. }
  7241. if (evt.preventDefault) {
  7242. if (!noPreventDefault) {
  7243. evt.preventDefault();
  7244. }
  7245. }
  7246. }
  7247. };
  7248. this._onLostFocus = function () {
  7249. _this._keys = [];
  7250. pointerId = null;
  7251. };
  7252. this._onGestureStart = function (e) {
  7253. if (window.MSGesture === undefined) {
  7254. return;
  7255. }
  7256. if (!_this._MSGestureHandler) {
  7257. _this._MSGestureHandler = new MSGesture();
  7258. _this._MSGestureHandler.target = element;
  7259. }
  7260. _this._MSGestureHandler.addPointer(e.pointerId);
  7261. };
  7262. this._onGesture = function (e) {
  7263. _this.radius *= e.scale;
  7264. if (e.preventDefault) {
  7265. if (!noPreventDefault) {
  7266. e.stopPropagation();
  7267. e.preventDefault();
  7268. }
  7269. }
  7270. };
  7271. this._reset = function () {
  7272. _this._keys = [];
  7273. _this.inertialAlphaOffset = 0;
  7274. _this.inertialBetaOffset = 0;
  7275. _this.inertialRadiusOffset = 0;
  7276. previousPosition = null;
  7277. pointerId = null;
  7278. };
  7279. this._touchStart = function (event) {
  7280. if (event.touches.length === 2) {
  7281. //-- start pinch if two fingers on the screen
  7282. pinchStarted = true;
  7283. _this._pinchStart(event);
  7284. }
  7285. };
  7286. this._touchMove = function (event) {
  7287. if (pinchStarted) {
  7288. //-- make scaling
  7289. _this._pinchMove(event);
  7290. }
  7291. };
  7292. this._touchEnd = function (event) {
  7293. if (pinchStarted) {
  7294. //-- end of pinch
  7295. _this._pinchEnd(event);
  7296. }
  7297. };
  7298. this._pinchStart = function (event) {
  7299. // save origin touch point
  7300. pinchPointX1 = event.touches[0].clientX;
  7301. pinchPointX2 = event.touches[1].clientX;
  7302. // block the camera
  7303. // if not it rotate around target during pinch
  7304. pinchStarted = true;
  7305. };
  7306. this._pinchMove = function (event) {
  7307. // variable for new camera's radius
  7308. var delta = 0;
  7309. // variables to know if pinch open or pinch close
  7310. var direction = 1;
  7311. var distanceXOrigine, distanceXNow;
  7312. if (event.touches.length !== 2)
  7313. return;
  7314. // calculate absolute distances of the two fingers
  7315. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7316. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7317. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7318. if (distanceXNow < distanceXOrigine) {
  7319. direction = -1;
  7320. }
  7321. // calculate new radius
  7322. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7323. // set new radius
  7324. _this.inertialRadiusOffset -= delta;
  7325. // save origin touch point
  7326. pinchPointX1 = event.touches[0].clientX;
  7327. pinchPointX2 = event.touches[1].clientX;
  7328. };
  7329. this._pinchEnd = function (event) {
  7330. // cancel pinch and deblock camera rotation
  7331. pinchStarted = false;
  7332. };
  7333. }
  7334. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7335. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7336. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7337. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7338. element.addEventListener("mousemove", this._onMouseMove, false);
  7339. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7340. element.addEventListener("MSGestureChange", this._onGesture, false);
  7341. element.addEventListener('mousewheel', this._wheel, false);
  7342. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7343. // pinch
  7344. element.addEventListener('touchstart', this._touchStart, false);
  7345. element.addEventListener('touchmove', this._touchMove, false);
  7346. element.addEventListener('touchend', this._touchEnd, false);
  7347. BABYLON.Tools.RegisterTopRootEvents([
  7348. { name: "keydown", handler: this._onKeyDown },
  7349. { name: "keyup", handler: this._onKeyUp },
  7350. { name: "blur", handler: this._onLostFocus }
  7351. ]);
  7352. };
  7353. ArcRotateCamera.prototype.detachControl = function (element) {
  7354. if (this._attachedElement != element) {
  7355. return;
  7356. }
  7357. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7358. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7359. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7360. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7361. element.removeEventListener("mousemove", this._onMouseMove);
  7362. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7363. element.removeEventListener("MSGestureChange", this._onGesture);
  7364. element.removeEventListener('mousewheel', this._wheel);
  7365. element.removeEventListener('DOMMouseScroll', this._wheel);
  7366. // pinch
  7367. element.removeEventListener('touchstart', this._touchStart);
  7368. element.removeEventListener('touchmove', this._touchMove);
  7369. element.removeEventListener('touchend', this._touchEnd);
  7370. BABYLON.Tools.UnregisterTopRootEvents([
  7371. { name: "keydown", handler: this._onKeyDown },
  7372. { name: "keyup", handler: this._onKeyUp },
  7373. { name: "blur", handler: this._onLostFocus }
  7374. ]);
  7375. this._MSGestureHandler = null;
  7376. this._attachedElement = null;
  7377. if (this._reset) {
  7378. this._reset();
  7379. }
  7380. };
  7381. ArcRotateCamera.prototype._update = function () {
  7382. for (var index = 0; index < this._keys.length; index++) {
  7383. var keyCode = this._keys[index];
  7384. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7385. this.inertialAlphaOffset -= 0.01;
  7386. }
  7387. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7388. this.inertialBetaOffset -= 0.01;
  7389. }
  7390. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7391. this.inertialAlphaOffset += 0.01;
  7392. }
  7393. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7394. this.inertialBetaOffset += 0.01;
  7395. }
  7396. }
  7397. // Inertia
  7398. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7399. this.alpha += this.inertialAlphaOffset;
  7400. this.beta += this.inertialBetaOffset;
  7401. this.radius -= this.inertialRadiusOffset;
  7402. this.inertialAlphaOffset *= this.inertia;
  7403. this.inertialBetaOffset *= this.inertia;
  7404. this.inertialRadiusOffset *= this.inertia;
  7405. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7406. this.inertialAlphaOffset = 0;
  7407. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7408. this.inertialBetaOffset = 0;
  7409. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7410. this.inertialRadiusOffset = 0;
  7411. }
  7412. // Limits
  7413. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7414. this.alpha = this.lowerAlphaLimit;
  7415. }
  7416. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7417. this.alpha = this.upperAlphaLimit;
  7418. }
  7419. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7420. this.beta = this.lowerBetaLimit;
  7421. }
  7422. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7423. this.beta = this.upperBetaLimit;
  7424. }
  7425. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7426. this.radius = this.lowerRadiusLimit;
  7427. }
  7428. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7429. this.radius = this.upperRadiusLimit;
  7430. }
  7431. };
  7432. ArcRotateCamera.prototype.setPosition = function (position) {
  7433. var radiusv3 = position.subtract(this._getTargetPosition());
  7434. this.radius = radiusv3.length();
  7435. // Alpha
  7436. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7437. if (radiusv3.z < 0) {
  7438. this.alpha = 2 * Math.PI - this.alpha;
  7439. }
  7440. // Beta
  7441. this.beta = Math.acos(radiusv3.y / this.radius);
  7442. };
  7443. ArcRotateCamera.prototype._getViewMatrix = function () {
  7444. // Compute
  7445. var cosa = Math.cos(this.alpha);
  7446. var sina = Math.sin(this.alpha);
  7447. var cosb = Math.cos(this.beta);
  7448. var sinb = Math.sin(this.beta);
  7449. var target = this._getTargetPosition();
  7450. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7451. if (this.checkCollisions) {
  7452. this._collider.radius = this.collisionRadius;
  7453. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7454. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7455. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7456. this.position.copyFrom(this._previousPosition);
  7457. this.alpha = this._previousAlpha;
  7458. this.beta = this._previousBeta;
  7459. this.radius = this._previousRadius;
  7460. if (this.onCollide) {
  7461. this.onCollide(this._collider.collidedMesh);
  7462. }
  7463. }
  7464. }
  7465. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7466. this._previousAlpha = this.alpha;
  7467. this._previousBeta = this.beta;
  7468. this._previousRadius = this.radius;
  7469. this._previousPosition.copyFrom(this.position);
  7470. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7471. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7472. return this._viewMatrix;
  7473. };
  7474. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7475. meshes = meshes || this.getScene().meshes;
  7476. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7477. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7478. this.radius = distance * this.zoomOnFactor;
  7479. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7480. };
  7481. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7482. var meshesOrMinMaxVector;
  7483. var distance;
  7484. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7485. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7486. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7487. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7488. }
  7489. else {
  7490. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7491. distance = meshesOrMinMaxVectorAndDistance.distance;
  7492. }
  7493. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7494. this.maxZ = distance * 2;
  7495. };
  7496. return ArcRotateCamera;
  7497. })(BABYLON.Camera);
  7498. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7499. })(BABYLON || (BABYLON = {}));
  7500. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  7501. (function (BABYLON) {
  7502. /**
  7503. * Represents a scene to be rendered by the engine.
  7504. * @see http://doc.babylonjs.com/page.php?p=21911
  7505. */
  7506. var Scene = (function () {
  7507. /**
  7508. * @constructor
  7509. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  7510. */
  7511. function Scene(engine) {
  7512. // Members
  7513. this.autoClear = true;
  7514. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7515. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7516. this.forceWireframe = false;
  7517. this.forcePointsCloud = false;
  7518. this.forceShowBoundingBoxes = false;
  7519. this.animationsEnabled = true;
  7520. 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
  7521. // Fog
  7522. /**
  7523. * is fog enabled on this scene.
  7524. * @type {boolean}
  7525. */
  7526. this.fogEnabled = true;
  7527. this.fogMode = Scene.FOGMODE_NONE;
  7528. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7529. this.fogDensity = 0.1;
  7530. this.fogStart = 0;
  7531. this.fogEnd = 1000.0;
  7532. // Lights
  7533. /**
  7534. * is shadow enabled on this scene.
  7535. * @type {boolean}
  7536. */
  7537. this.shadowsEnabled = true;
  7538. /**
  7539. * is light enabled on this scene.
  7540. * @type {boolean}
  7541. */
  7542. this.lightsEnabled = true;
  7543. /**
  7544. * All of the lights added to this scene.
  7545. * @see BABYLON.Light
  7546. * @type {BABYLON.Light[]}
  7547. */
  7548. this.lights = new Array();
  7549. // Cameras
  7550. /**
  7551. * All of the cameras added to this scene.
  7552. * @see BABYLON.Camera
  7553. * @type {BABYLON.Camera[]}
  7554. */
  7555. this.cameras = new Array();
  7556. this.activeCameras = new Array();
  7557. // Meshes
  7558. /**
  7559. * All of the (abstract) meshes added to this scene.
  7560. * @see BABYLON.AbstractMesh
  7561. * @type {BABYLON.AbstractMesh[]}
  7562. */
  7563. this.meshes = new Array();
  7564. // Geometries
  7565. this._geometries = new Array();
  7566. this.materials = new Array();
  7567. this.multiMaterials = new Array();
  7568. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7569. // Textures
  7570. this.texturesEnabled = true;
  7571. this.textures = new Array();
  7572. // Particles
  7573. this.particlesEnabled = true;
  7574. this.particleSystems = new Array();
  7575. // Sprites
  7576. this.spriteManagers = new Array();
  7577. // Layers
  7578. this.layers = new Array();
  7579. // Skeletons
  7580. this.skeletonsEnabled = true;
  7581. this.skeletons = new Array();
  7582. // Lens flares
  7583. this.lensFlaresEnabled = true;
  7584. this.lensFlareSystems = new Array();
  7585. // Collisions
  7586. this.collisionsEnabled = true;
  7587. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7588. // Postprocesses
  7589. this.postProcessesEnabled = true;
  7590. // Customs render targets
  7591. this.renderTargetsEnabled = true;
  7592. this.customRenderTargets = new Array();
  7593. // Imported meshes
  7594. this.importedMeshesFiles = new Array();
  7595. this._actionManagers = new Array();
  7596. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7597. // Procedural textures
  7598. this.proceduralTexturesEnabled = true;
  7599. this._proceduralTextures = new Array();
  7600. this.soundTracks = new Array();
  7601. this._totalVertices = 0;
  7602. this._activeVertices = 0;
  7603. this._activeParticles = 0;
  7604. this._lastFrameDuration = 0;
  7605. this._evaluateActiveMeshesDuration = 0;
  7606. this._renderTargetsDuration = 0;
  7607. this._particlesDuration = 0;
  7608. this._renderDuration = 0;
  7609. this._spritesDuration = 0;
  7610. this._animationRatio = 0;
  7611. this._renderId = 0;
  7612. this._executeWhenReadyTimeoutId = -1;
  7613. this._toBeDisposed = new BABYLON.SmartArray(256);
  7614. this._onReadyCallbacks = new Array();
  7615. this._pendingData = []; //ANY
  7616. this._onBeforeRenderCallbacks = new Array();
  7617. this._onAfterRenderCallbacks = new Array();
  7618. this._activeMeshes = new BABYLON.SmartArray(256);
  7619. this._processedMaterials = new BABYLON.SmartArray(256);
  7620. this._renderTargets = new BABYLON.SmartArray(256);
  7621. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7622. this._activeSkeletons = new BABYLON.SmartArray(32);
  7623. this._activeBones = 0;
  7624. this._activeAnimatables = new Array();
  7625. this._transformMatrix = BABYLON.Matrix.Zero();
  7626. this._scaledPosition = BABYLON.Vector3.Zero();
  7627. this._scaledVelocity = BABYLON.Vector3.Zero();
  7628. this._engine = engine;
  7629. engine.scenes.push(this);
  7630. this._renderingManager = new BABYLON.RenderingManager(this);
  7631. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7632. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7633. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7634. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7635. this.attachControl();
  7636. this._debugLayer = new BABYLON.DebugLayer(this);
  7637. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7638. }
  7639. Object.defineProperty(Scene, "FOGMODE_NONE", {
  7640. get: function () {
  7641. return Scene._FOGMODE_NONE;
  7642. },
  7643. enumerable: true,
  7644. configurable: true
  7645. });
  7646. Object.defineProperty(Scene, "FOGMODE_EXP", {
  7647. get: function () {
  7648. return Scene._FOGMODE_EXP;
  7649. },
  7650. enumerable: true,
  7651. configurable: true
  7652. });
  7653. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  7654. get: function () {
  7655. return Scene._FOGMODE_EXP2;
  7656. },
  7657. enumerable: true,
  7658. configurable: true
  7659. });
  7660. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  7661. get: function () {
  7662. return Scene._FOGMODE_LINEAR;
  7663. },
  7664. enumerable: true,
  7665. configurable: true
  7666. });
  7667. Object.defineProperty(Scene.prototype, "debugLayer", {
  7668. // Properties
  7669. get: function () {
  7670. return this._debugLayer;
  7671. },
  7672. enumerable: true,
  7673. configurable: true
  7674. });
  7675. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7676. /**
  7677. * The mesh that is currently under the pointer.
  7678. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  7679. */
  7680. get: function () {
  7681. return this._meshUnderPointer;
  7682. },
  7683. enumerable: true,
  7684. configurable: true
  7685. });
  7686. Object.defineProperty(Scene.prototype, "pointerX", {
  7687. /**
  7688. * Current on-screen X position of the pointer
  7689. * @return {number} X position of the pointer
  7690. */
  7691. get: function () {
  7692. return this._pointerX;
  7693. },
  7694. enumerable: true,
  7695. configurable: true
  7696. });
  7697. Object.defineProperty(Scene.prototype, "pointerY", {
  7698. /**
  7699. * Current on-screen Y position of the pointer
  7700. * @return {number} Y position of the pointer
  7701. */
  7702. get: function () {
  7703. return this._pointerY;
  7704. },
  7705. enumerable: true,
  7706. configurable: true
  7707. });
  7708. Scene.prototype.getCachedMaterial = function () {
  7709. return this._cachedMaterial;
  7710. };
  7711. Scene.prototype.getBoundingBoxRenderer = function () {
  7712. return this._boundingBoxRenderer;
  7713. };
  7714. Scene.prototype.getOutlineRenderer = function () {
  7715. return this._outlineRenderer;
  7716. };
  7717. Scene.prototype.getEngine = function () {
  7718. return this._engine;
  7719. };
  7720. Scene.prototype.getTotalVertices = function () {
  7721. return this._totalVertices;
  7722. };
  7723. Scene.prototype.getActiveVertices = function () {
  7724. return this._activeVertices;
  7725. };
  7726. Scene.prototype.getActiveParticles = function () {
  7727. return this._activeParticles;
  7728. };
  7729. Scene.prototype.getActiveBones = function () {
  7730. return this._activeBones;
  7731. };
  7732. // Stats
  7733. Scene.prototype.getLastFrameDuration = function () {
  7734. return this._lastFrameDuration;
  7735. };
  7736. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7737. return this._evaluateActiveMeshesDuration;
  7738. };
  7739. Scene.prototype.getActiveMeshes = function () {
  7740. return this._activeMeshes;
  7741. };
  7742. Scene.prototype.getRenderTargetsDuration = function () {
  7743. return this._renderTargetsDuration;
  7744. };
  7745. Scene.prototype.getRenderDuration = function () {
  7746. return this._renderDuration;
  7747. };
  7748. Scene.prototype.getParticlesDuration = function () {
  7749. return this._particlesDuration;
  7750. };
  7751. Scene.prototype.getSpritesDuration = function () {
  7752. return this._spritesDuration;
  7753. };
  7754. Scene.prototype.getAnimationRatio = function () {
  7755. return this._animationRatio;
  7756. };
  7757. Scene.prototype.getRenderId = function () {
  7758. return this._renderId;
  7759. };
  7760. Scene.prototype.incrementRenderId = function () {
  7761. this._renderId++;
  7762. };
  7763. Scene.prototype._updatePointerPosition = function (evt) {
  7764. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7765. this._pointerX = evt.clientX - canvasRect.left;
  7766. this._pointerY = evt.clientY - canvasRect.top;
  7767. if (this.cameraToUseForPointers) {
  7768. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7769. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7770. }
  7771. };
  7772. // Pointers handling
  7773. Scene.prototype.attachControl = function () {
  7774. var _this = this;
  7775. this._onPointerMove = function (evt) {
  7776. var canvas = _this._engine.getRenderingCanvas();
  7777. _this._updatePointerPosition(evt);
  7778. 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);
  7779. if (pickResult.hit) {
  7780. _this._meshUnderPointer = pickResult.pickedMesh;
  7781. _this.setPointerOverMesh(pickResult.pickedMesh);
  7782. canvas.style.cursor = "pointer";
  7783. }
  7784. else {
  7785. _this.setPointerOverMesh(null);
  7786. canvas.style.cursor = "";
  7787. _this._meshUnderPointer = null;
  7788. }
  7789. };
  7790. this._onPointerDown = function (evt) {
  7791. var predicate = null;
  7792. if (!_this.onPointerDown) {
  7793. predicate = function (mesh) {
  7794. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7795. };
  7796. }
  7797. _this._updatePointerPosition(evt);
  7798. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7799. if (pickResult.hit) {
  7800. if (pickResult.pickedMesh.actionManager) {
  7801. switch (evt.button) {
  7802. case 0:
  7803. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7804. break;
  7805. case 1:
  7806. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7807. break;
  7808. case 2:
  7809. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7810. break;
  7811. }
  7812. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7813. }
  7814. }
  7815. if (_this.onPointerDown) {
  7816. _this.onPointerDown(evt, pickResult);
  7817. }
  7818. };
  7819. this._onKeyDown = function (evt) {
  7820. if (_this.actionManager) {
  7821. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7822. }
  7823. };
  7824. this._onKeyUp = function (evt) {
  7825. if (_this.actionManager) {
  7826. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7827. }
  7828. };
  7829. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7830. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7831. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7832. BABYLON.Tools.RegisterTopRootEvents([
  7833. { name: "keydown", handler: this._onKeyDown },
  7834. { name: "keyup", handler: this._onKeyUp }
  7835. ]);
  7836. };
  7837. Scene.prototype.detachControl = function () {
  7838. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7839. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7840. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7841. BABYLON.Tools.UnregisterTopRootEvents([
  7842. { name: "keydown", handler: this._onKeyDown },
  7843. { name: "keyup", handler: this._onKeyUp }
  7844. ]);
  7845. };
  7846. // Ready
  7847. Scene.prototype.isReady = function () {
  7848. if (this._pendingData.length > 0) {
  7849. return false;
  7850. }
  7851. for (var index = 0; index < this._geometries.length; index++) {
  7852. var geometry = this._geometries[index];
  7853. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7854. return false;
  7855. }
  7856. }
  7857. for (index = 0; index < this.meshes.length; index++) {
  7858. var mesh = this.meshes[index];
  7859. if (!mesh.isReady()) {
  7860. return false;
  7861. }
  7862. var mat = mesh.material;
  7863. if (mat) {
  7864. if (!mat.isReady(mesh)) {
  7865. return false;
  7866. }
  7867. }
  7868. }
  7869. return true;
  7870. };
  7871. Scene.prototype.resetCachedMaterial = function () {
  7872. this._cachedMaterial = null;
  7873. };
  7874. Scene.prototype.registerBeforeRender = function (func) {
  7875. this._onBeforeRenderCallbacks.push(func);
  7876. };
  7877. Scene.prototype.unregisterBeforeRender = function (func) {
  7878. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7879. if (index > -1) {
  7880. this._onBeforeRenderCallbacks.splice(index, 1);
  7881. }
  7882. };
  7883. Scene.prototype.registerAfterRender = function (func) {
  7884. this._onAfterRenderCallbacks.push(func);
  7885. };
  7886. Scene.prototype.unregisterAfterRender = function (func) {
  7887. var index = this._onAfterRenderCallbacks.indexOf(func);
  7888. if (index > -1) {
  7889. this._onAfterRenderCallbacks.splice(index, 1);
  7890. }
  7891. };
  7892. Scene.prototype._addPendingData = function (data) {
  7893. this._pendingData.push(data);
  7894. };
  7895. Scene.prototype._removePendingData = function (data) {
  7896. var index = this._pendingData.indexOf(data);
  7897. if (index !== -1) {
  7898. this._pendingData.splice(index, 1);
  7899. }
  7900. };
  7901. Scene.prototype.getWaitingItemsCount = function () {
  7902. return this._pendingData.length;
  7903. };
  7904. /**
  7905. * Registers a function to be executed when the scene is ready.
  7906. * @param {Function} func - the function to be executed.
  7907. */
  7908. Scene.prototype.executeWhenReady = function (func) {
  7909. var _this = this;
  7910. this._onReadyCallbacks.push(func);
  7911. if (this._executeWhenReadyTimeoutId !== -1) {
  7912. return;
  7913. }
  7914. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7915. _this._checkIsReady();
  7916. }, 150);
  7917. };
  7918. Scene.prototype._checkIsReady = function () {
  7919. var _this = this;
  7920. if (this.isReady()) {
  7921. this._onReadyCallbacks.forEach(function (func) {
  7922. func();
  7923. });
  7924. this._onReadyCallbacks = [];
  7925. this._executeWhenReadyTimeoutId = -1;
  7926. return;
  7927. }
  7928. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7929. _this._checkIsReady();
  7930. }, 150);
  7931. };
  7932. // Animations
  7933. /**
  7934. * Will start the animation sequence of a given target
  7935. * @param target - the target
  7936. * @param {number} from - from which frame should animation start
  7937. * @param {number} to - till which frame should animation run.
  7938. * @param {boolean} [loop] - should the animation loop
  7939. * @param {number} [speedRatio] - the speed in which to run the animation
  7940. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  7941. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  7942. * @return {BABYLON.Animatable} the animatable object created for this animation
  7943. * @see BABYLON.Animatable
  7944. * @see http://doc.babylonjs.com/page.php?p=22081
  7945. */
  7946. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7947. if (speedRatio === undefined) {
  7948. speedRatio = 1.0;
  7949. }
  7950. this.stopAnimation(target);
  7951. if (!animatable) {
  7952. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7953. }
  7954. // Local animations
  7955. if (target.animations) {
  7956. animatable.appendAnimations(target, target.animations);
  7957. }
  7958. // Children animations
  7959. if (target.getAnimatables) {
  7960. var animatables = target.getAnimatables();
  7961. for (var index = 0; index < animatables.length; index++) {
  7962. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7963. }
  7964. }
  7965. return animatable;
  7966. };
  7967. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7968. if (speedRatio === undefined) {
  7969. speedRatio = 1.0;
  7970. }
  7971. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  7972. return animatable;
  7973. };
  7974. Scene.prototype.getAnimatableByTarget = function (target) {
  7975. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7976. if (this._activeAnimatables[index].target === target) {
  7977. return this._activeAnimatables[index];
  7978. }
  7979. }
  7980. return null;
  7981. };
  7982. /**
  7983. * Will stop the animation of the given target
  7984. * @param target - the target
  7985. * @see beginAnimation
  7986. */
  7987. Scene.prototype.stopAnimation = function (target) {
  7988. var animatable = this.getAnimatableByTarget(target);
  7989. if (animatable) {
  7990. animatable.stop();
  7991. }
  7992. };
  7993. Scene.prototype._animate = function () {
  7994. if (!this.animationsEnabled) {
  7995. return;
  7996. }
  7997. if (!this._animationStartDate) {
  7998. this._animationStartDate = BABYLON.Tools.Now;
  7999. }
  8000. // Getting time
  8001. var now = BABYLON.Tools.Now;
  8002. var delay = now - this._animationStartDate;
  8003. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8004. if (!this._activeAnimatables[index]._animate(delay)) {
  8005. this._activeAnimatables.splice(index, 1);
  8006. index--;
  8007. }
  8008. }
  8009. };
  8010. // Matrix
  8011. Scene.prototype.getViewMatrix = function () {
  8012. return this._viewMatrix;
  8013. };
  8014. Scene.prototype.getProjectionMatrix = function () {
  8015. return this._projectionMatrix;
  8016. };
  8017. Scene.prototype.getTransformMatrix = function () {
  8018. return this._transformMatrix;
  8019. };
  8020. Scene.prototype.setTransformMatrix = function (view, projection) {
  8021. this._viewMatrix = view;
  8022. this._projectionMatrix = projection;
  8023. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8024. };
  8025. // Methods
  8026. /**
  8027. * sets the active camera of the scene using its ID
  8028. * @param {string} id - the camera's ID
  8029. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8030. * @see activeCamera
  8031. */
  8032. Scene.prototype.setActiveCameraByID = function (id) {
  8033. var camera = this.getCameraByID(id);
  8034. if (camera) {
  8035. this.activeCamera = camera;
  8036. return camera;
  8037. }
  8038. return null;
  8039. };
  8040. /**
  8041. * sets the active camera of the scene using its name
  8042. * @param {string} name - the camera's name
  8043. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8044. * @see activeCamera
  8045. */
  8046. Scene.prototype.setActiveCameraByName = function (name) {
  8047. var camera = this.getCameraByName(name);
  8048. if (camera) {
  8049. this.activeCamera = camera;
  8050. return camera;
  8051. }
  8052. return null;
  8053. };
  8054. /**
  8055. * get a material using its id
  8056. * @param {string} the material's ID
  8057. * @return {BABYLON.Material|null} the material or null if none found.
  8058. */
  8059. Scene.prototype.getMaterialByID = function (id) {
  8060. for (var index = 0; index < this.materials.length; index++) {
  8061. if (this.materials[index].id === id) {
  8062. return this.materials[index];
  8063. }
  8064. }
  8065. return null;
  8066. };
  8067. /**
  8068. * get a material using its name
  8069. * @param {string} the material's name
  8070. * @return {BABYLON.Material|null} the material or null if none found.
  8071. */
  8072. Scene.prototype.getMaterialByName = function (name) {
  8073. for (var index = 0; index < this.materials.length; index++) {
  8074. if (this.materials[index].name === name) {
  8075. return this.materials[index];
  8076. }
  8077. }
  8078. return null;
  8079. };
  8080. Scene.prototype.getCameraByID = function (id) {
  8081. for (var index = 0; index < this.cameras.length; index++) {
  8082. if (this.cameras[index].id === id) {
  8083. return this.cameras[index];
  8084. }
  8085. }
  8086. return null;
  8087. };
  8088. /**
  8089. * get a camera using its name
  8090. * @param {string} the camera's name
  8091. * @return {BABYLON.Camera|null} the camera or null if none found.
  8092. */
  8093. Scene.prototype.getCameraByName = function (name) {
  8094. for (var index = 0; index < this.cameras.length; index++) {
  8095. if (this.cameras[index].name === name) {
  8096. return this.cameras[index];
  8097. }
  8098. }
  8099. return null;
  8100. };
  8101. /**
  8102. * get a light node using its name
  8103. * @param {string} the light's name
  8104. * @return {BABYLON.Light|null} the light or null if none found.
  8105. */
  8106. Scene.prototype.getLightByName = function (name) {
  8107. for (var index = 0; index < this.lights.length; index++) {
  8108. if (this.lights[index].name === name) {
  8109. return this.lights[index];
  8110. }
  8111. }
  8112. return null;
  8113. };
  8114. /**
  8115. * get a light node using its ID
  8116. * @param {string} the light's id
  8117. * @return {BABYLON.Light|null} the light or null if none found.
  8118. */
  8119. Scene.prototype.getLightByID = function (id) {
  8120. for (var index = 0; index < this.lights.length; index++) {
  8121. if (this.lights[index].id === id) {
  8122. return this.lights[index];
  8123. }
  8124. }
  8125. return null;
  8126. };
  8127. /**
  8128. * get a geometry using its ID
  8129. * @param {string} the geometry's id
  8130. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8131. */
  8132. Scene.prototype.getGeometryByID = function (id) {
  8133. for (var index = 0; index < this._geometries.length; index++) {
  8134. if (this._geometries[index].id === id) {
  8135. return this._geometries[index];
  8136. }
  8137. }
  8138. return null;
  8139. };
  8140. /**
  8141. * add a new geometry to this scene.
  8142. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8143. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8144. * @return {boolean} was the geometry added or not
  8145. */
  8146. Scene.prototype.pushGeometry = function (geometry, force) {
  8147. if (!force && this.getGeometryByID(geometry.id)) {
  8148. return false;
  8149. }
  8150. this._geometries.push(geometry);
  8151. return true;
  8152. };
  8153. Scene.prototype.getGeometries = function () {
  8154. return this._geometries;
  8155. };
  8156. /**
  8157. * Get a the first added mesh found of a given ID
  8158. * @param {string} id - the id to search for
  8159. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8160. */
  8161. Scene.prototype.getMeshByID = function (id) {
  8162. for (var index = 0; index < this.meshes.length; index++) {
  8163. if (this.meshes[index].id === id) {
  8164. return this.meshes[index];
  8165. }
  8166. }
  8167. return null;
  8168. };
  8169. /**
  8170. * Get a the last added mesh found of a given ID
  8171. * @param {string} id - the id to search for
  8172. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8173. */
  8174. Scene.prototype.getLastMeshByID = function (id) {
  8175. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8176. if (this.meshes[index].id === id) {
  8177. return this.meshes[index];
  8178. }
  8179. }
  8180. return null;
  8181. };
  8182. /**
  8183. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8184. * @param {string} id - the id to search for
  8185. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8186. */
  8187. Scene.prototype.getLastEntryByID = function (id) {
  8188. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8189. if (this.meshes[index].id === id) {
  8190. return this.meshes[index];
  8191. }
  8192. }
  8193. for (index = this.cameras.length - 1; index >= 0; index--) {
  8194. if (this.cameras[index].id === id) {
  8195. return this.cameras[index];
  8196. }
  8197. }
  8198. for (index = this.lights.length - 1; index >= 0; index--) {
  8199. if (this.lights[index].id === id) {
  8200. return this.lights[index];
  8201. }
  8202. }
  8203. return null;
  8204. };
  8205. Scene.prototype.getNodeByName = function (name) {
  8206. var mesh = this.getMeshByName(name);
  8207. if (mesh) {
  8208. return mesh;
  8209. }
  8210. var light = this.getLightByName(name);
  8211. if (light) {
  8212. return light;
  8213. }
  8214. return this.getCameraByName(name);
  8215. };
  8216. Scene.prototype.getMeshByName = function (name) {
  8217. for (var index = 0; index < this.meshes.length; index++) {
  8218. if (this.meshes[index].name === name) {
  8219. return this.meshes[index];
  8220. }
  8221. }
  8222. return null;
  8223. };
  8224. Scene.prototype.getSoundByName = function (name) {
  8225. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8226. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8227. return this.mainSoundTrack.soundCollection[index];
  8228. }
  8229. }
  8230. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8231. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8232. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8233. return this.soundTracks[sdIndex].soundCollection[index];
  8234. }
  8235. }
  8236. }
  8237. return null;
  8238. };
  8239. Scene.prototype.getLastSkeletonByID = function (id) {
  8240. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8241. if (this.skeletons[index].id === id) {
  8242. return this.skeletons[index];
  8243. }
  8244. }
  8245. return null;
  8246. };
  8247. Scene.prototype.getSkeletonById = function (id) {
  8248. for (var index = 0; index < this.skeletons.length; index++) {
  8249. if (this.skeletons[index].id === id) {
  8250. return this.skeletons[index];
  8251. }
  8252. }
  8253. return null;
  8254. };
  8255. Scene.prototype.getSkeletonByName = function (name) {
  8256. for (var index = 0; index < this.skeletons.length; index++) {
  8257. if (this.skeletons[index].name === name) {
  8258. return this.skeletons[index];
  8259. }
  8260. }
  8261. return null;
  8262. };
  8263. Scene.prototype.isActiveMesh = function (mesh) {
  8264. return (this._activeMeshes.indexOf(mesh) !== -1);
  8265. };
  8266. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8267. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8268. var material = subMesh.getMaterial();
  8269. if (mesh.showSubMeshesBoundingBox) {
  8270. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8271. }
  8272. if (material) {
  8273. // Render targets
  8274. if (material.getRenderTargetTextures) {
  8275. if (this._processedMaterials.indexOf(material) === -1) {
  8276. this._processedMaterials.push(material);
  8277. this._renderTargets.concat(material.getRenderTargetTextures());
  8278. }
  8279. }
  8280. // Dispatch
  8281. this._activeVertices += subMesh.indexCount;
  8282. this._renderingManager.dispatch(subMesh);
  8283. }
  8284. }
  8285. };
  8286. Scene.prototype._evaluateActiveMeshes = function () {
  8287. this._activeMeshes.reset();
  8288. this._renderingManager.reset();
  8289. this._processedMaterials.reset();
  8290. this._activeParticleSystems.reset();
  8291. this._activeSkeletons.reset();
  8292. this._boundingBoxRenderer.reset();
  8293. if (!this._frustumPlanes) {
  8294. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8295. }
  8296. else {
  8297. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8298. }
  8299. // Meshes
  8300. var meshes;
  8301. var len;
  8302. if (this._selectionOctree) {
  8303. var selection = this._selectionOctree.select(this._frustumPlanes);
  8304. meshes = selection.data;
  8305. len = selection.length;
  8306. }
  8307. else {
  8308. len = this.meshes.length;
  8309. meshes = this.meshes;
  8310. }
  8311. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8312. var mesh = meshes[meshIndex];
  8313. if (mesh.isBlocked) {
  8314. continue;
  8315. }
  8316. this._totalVertices += mesh.getTotalVertices();
  8317. if (!mesh.isReady()) {
  8318. continue;
  8319. }
  8320. mesh.computeWorldMatrix();
  8321. // Intersections
  8322. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8323. this._meshesForIntersections.pushNoDuplicate(mesh);
  8324. }
  8325. // Switch to current LOD
  8326. var meshLOD = mesh.getLOD(this.activeCamera);
  8327. if (!meshLOD) {
  8328. continue;
  8329. }
  8330. mesh._preActivate();
  8331. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8332. this._activeMeshes.push(mesh);
  8333. mesh._activate(this._renderId);
  8334. this._activeMesh(meshLOD);
  8335. }
  8336. }
  8337. // Particle systems
  8338. var beforeParticlesDate = BABYLON.Tools.Now;
  8339. if (this.particlesEnabled) {
  8340. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8341. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8342. var particleSystem = this.particleSystems[particleIndex];
  8343. if (!particleSystem.isStarted()) {
  8344. continue;
  8345. }
  8346. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8347. this._activeParticleSystems.push(particleSystem);
  8348. particleSystem.animate();
  8349. }
  8350. }
  8351. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8352. }
  8353. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8354. };
  8355. Scene.prototype._activeMesh = function (mesh) {
  8356. if (mesh.skeleton && this.skeletonsEnabled) {
  8357. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8358. }
  8359. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8360. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8361. }
  8362. if (mesh && mesh.subMeshes) {
  8363. // Submeshes Octrees
  8364. var len;
  8365. var subMeshes;
  8366. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8367. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8368. len = intersections.length;
  8369. subMeshes = intersections.data;
  8370. }
  8371. else {
  8372. subMeshes = mesh.subMeshes;
  8373. len = subMeshes.length;
  8374. }
  8375. for (var subIndex = 0; subIndex < len; subIndex++) {
  8376. var subMesh = subMeshes[subIndex];
  8377. this._evaluateSubMesh(subMesh, mesh);
  8378. }
  8379. }
  8380. };
  8381. Scene.prototype.updateTransformMatrix = function (force) {
  8382. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8383. };
  8384. Scene.prototype._renderForCamera = function (camera) {
  8385. var engine = this._engine;
  8386. this.activeCamera = camera;
  8387. if (!this.activeCamera)
  8388. throw new Error("Active camera not set");
  8389. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8390. // Viewport
  8391. engine.setViewport(this.activeCamera.viewport);
  8392. // Camera
  8393. this._renderId++;
  8394. this.updateTransformMatrix();
  8395. if (this.beforeCameraRender) {
  8396. this.beforeCameraRender(this.activeCamera);
  8397. }
  8398. // Meshes
  8399. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8400. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8401. this._evaluateActiveMeshes();
  8402. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8403. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8404. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8405. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8406. skeleton.prepare();
  8407. this._activeBones += skeleton.bones.length;
  8408. }
  8409. // Render targets
  8410. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8411. if (this.renderTargetsEnabled) {
  8412. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8413. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  8414. var renderTarget = this._renderTargets.data[renderIndex];
  8415. if (renderTarget._shouldRender()) {
  8416. this._renderId++;
  8417. renderTarget.render();
  8418. }
  8419. }
  8420. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8421. this._renderId++;
  8422. }
  8423. if (this._renderTargets.length > 0) {
  8424. engine.restoreDefaultFramebuffer();
  8425. }
  8426. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8427. // Prepare Frame
  8428. this.postProcessManager._prepareFrame();
  8429. var beforeRenderDate = BABYLON.Tools.Now;
  8430. // Backgrounds
  8431. if (this.layers.length) {
  8432. engine.setDepthBuffer(false);
  8433. var layerIndex;
  8434. var layer;
  8435. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8436. layer = this.layers[layerIndex];
  8437. if (layer.isBackground) {
  8438. layer.render();
  8439. }
  8440. }
  8441. engine.setDepthBuffer(true);
  8442. }
  8443. // Render
  8444. BABYLON.Tools.StartPerformanceCounter("Main render");
  8445. this._renderingManager.render(null, null, true, true);
  8446. BABYLON.Tools.EndPerformanceCounter("Main render");
  8447. // Bounding boxes
  8448. this._boundingBoxRenderer.render();
  8449. // Lens flares
  8450. if (this.lensFlaresEnabled) {
  8451. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8452. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8453. this.lensFlareSystems[lensFlareSystemIndex].render();
  8454. }
  8455. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8456. }
  8457. // Foregrounds
  8458. if (this.layers.length) {
  8459. engine.setDepthBuffer(false);
  8460. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8461. layer = this.layers[layerIndex];
  8462. if (!layer.isBackground) {
  8463. layer.render();
  8464. }
  8465. }
  8466. engine.setDepthBuffer(true);
  8467. }
  8468. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  8469. // Finalize frame
  8470. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8471. // Update camera
  8472. this.activeCamera._updateFromScene();
  8473. // Reset some special arrays
  8474. this._renderTargets.reset();
  8475. if (this.afterCameraRender) {
  8476. this.afterCameraRender(this.activeCamera);
  8477. }
  8478. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8479. };
  8480. Scene.prototype._processSubCameras = function (camera) {
  8481. if (camera.subCameras.length === 0) {
  8482. this._renderForCamera(camera);
  8483. return;
  8484. }
  8485. for (var index = 0; index < camera.subCameras.length; index++) {
  8486. this._renderForCamera(camera.subCameras[index]);
  8487. }
  8488. this.activeCamera = camera;
  8489. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8490. // Update camera
  8491. this.activeCamera._updateFromScene();
  8492. };
  8493. Scene.prototype._checkIntersections = function () {
  8494. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8495. var sourceMesh = this._meshesForIntersections.data[index];
  8496. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8497. var action = sourceMesh.actionManager.actions[actionIndex];
  8498. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8499. var parameters = action.getTriggerParameter();
  8500. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  8501. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  8502. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8503. if (areIntersecting && currentIntersectionInProgress === -1) {
  8504. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8505. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8506. sourceMesh._intersectionsInProgress.push(otherMesh);
  8507. }
  8508. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8509. sourceMesh._intersectionsInProgress.push(otherMesh);
  8510. }
  8511. }
  8512. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8513. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8514. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8515. if (indexOfOther > -1) {
  8516. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8517. }
  8518. }
  8519. }
  8520. }
  8521. }
  8522. };
  8523. Scene.prototype.render = function () {
  8524. var startDate = BABYLON.Tools.Now;
  8525. this._particlesDuration = 0;
  8526. this._spritesDuration = 0;
  8527. this._activeParticles = 0;
  8528. this._renderDuration = 0;
  8529. this._renderTargetsDuration = 0;
  8530. this._evaluateActiveMeshesDuration = 0;
  8531. this._totalVertices = 0;
  8532. this._activeVertices = 0;
  8533. this._activeBones = 0;
  8534. this.getEngine().resetDrawCalls();
  8535. this._meshesForIntersections.reset();
  8536. this.resetCachedMaterial();
  8537. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8538. // Actions
  8539. if (this.actionManager) {
  8540. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8541. }
  8542. // Before render
  8543. if (this.beforeRender) {
  8544. this.beforeRender();
  8545. }
  8546. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8547. this._onBeforeRenderCallbacks[callbackIndex]();
  8548. }
  8549. // Animations
  8550. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8551. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8552. this._animate();
  8553. // Physics
  8554. if (this._physicsEngine) {
  8555. BABYLON.Tools.StartPerformanceCounter("Physics");
  8556. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8557. BABYLON.Tools.EndPerformanceCounter("Physics");
  8558. }
  8559. // Customs render targets
  8560. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8561. var engine = this.getEngine();
  8562. var currentActiveCamera = this.activeCamera;
  8563. if (this.renderTargetsEnabled) {
  8564. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8565. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8566. var renderTarget = this.customRenderTargets[customIndex];
  8567. if (renderTarget._shouldRender()) {
  8568. this._renderId++;
  8569. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8570. if (!this.activeCamera)
  8571. throw new Error("Active camera not set");
  8572. // Viewport
  8573. engine.setViewport(this.activeCamera.viewport);
  8574. // Camera
  8575. this.updateTransformMatrix();
  8576. renderTarget.render();
  8577. }
  8578. }
  8579. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8580. this._renderId++;
  8581. }
  8582. if (this.customRenderTargets.length > 0) {
  8583. engine.restoreDefaultFramebuffer();
  8584. }
  8585. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8586. this.activeCamera = currentActiveCamera;
  8587. // Procedural textures
  8588. if (this.proceduralTexturesEnabled) {
  8589. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8590. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8591. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8592. if (proceduralTexture._shouldRender()) {
  8593. proceduralTexture.render();
  8594. }
  8595. }
  8596. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8597. }
  8598. // Clear
  8599. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8600. // Shadows
  8601. if (this.shadowsEnabled) {
  8602. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8603. var light = this.lights[lightIndex];
  8604. var shadowGenerator = light.getShadowGenerator();
  8605. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8606. this._renderTargets.push(shadowGenerator.getShadowMap());
  8607. }
  8608. }
  8609. }
  8610. // Depth renderer
  8611. if (this._depthRenderer) {
  8612. this._renderTargets.push(this._depthRenderer.getDepthMap());
  8613. }
  8614. // RenderPipeline
  8615. this.postProcessRenderPipelineManager.update();
  8616. // Multi-cameras?
  8617. if (this.activeCameras.length > 0) {
  8618. var currentRenderId = this._renderId;
  8619. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8620. this._renderId = currentRenderId;
  8621. this._processSubCameras(this.activeCameras[cameraIndex]);
  8622. }
  8623. }
  8624. else {
  8625. if (!this.activeCamera) {
  8626. throw new Error("No camera defined");
  8627. }
  8628. this._processSubCameras(this.activeCamera);
  8629. }
  8630. // Intersection checks
  8631. this._checkIntersections();
  8632. // Update the audio listener attached to the camera
  8633. this._updateAudioParameters();
  8634. // After render
  8635. if (this.afterRender) {
  8636. this.afterRender();
  8637. }
  8638. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8639. this._onAfterRenderCallbacks[callbackIndex]();
  8640. }
  8641. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8642. this._toBeDisposed.data[index].dispose();
  8643. this._toBeDisposed[index] = null;
  8644. }
  8645. this._toBeDisposed.reset();
  8646. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8647. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8648. };
  8649. Scene.prototype._updateAudioParameters = function () {
  8650. var listeningCamera;
  8651. var audioEngine = BABYLON.Engine.audioEngine;
  8652. if (this.activeCameras.length > 0) {
  8653. listeningCamera = this.activeCameras[0];
  8654. }
  8655. else {
  8656. listeningCamera = this.activeCamera;
  8657. }
  8658. if (listeningCamera && audioEngine.canUseWebAudio) {
  8659. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8660. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8661. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8662. cameraDirection.normalize();
  8663. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8664. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8665. var sound = this.mainSoundTrack.soundCollection[i];
  8666. if (sound.useCustomAttenuation) {
  8667. sound.updateDistanceFromListener();
  8668. }
  8669. }
  8670. for (i = 0; i < this.soundTracks.length; i++) {
  8671. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8672. sound = this.soundTracks[i].soundCollection[j];
  8673. if (sound.useCustomAttenuation) {
  8674. sound.updateDistanceFromListener();
  8675. }
  8676. }
  8677. }
  8678. }
  8679. };
  8680. Scene.prototype.enableDepthRenderer = function () {
  8681. if (this._depthRenderer) {
  8682. return this._depthRenderer;
  8683. }
  8684. this._depthRenderer = new BABYLON.DepthRenderer(this);
  8685. return this._depthRenderer;
  8686. };
  8687. Scene.prototype.disableDepthRenderer = function () {
  8688. if (!this._depthRenderer) {
  8689. return;
  8690. }
  8691. this._depthRenderer.dispose();
  8692. this._depthRenderer = null;
  8693. };
  8694. Scene.prototype.dispose = function () {
  8695. this.beforeRender = null;
  8696. this.afterRender = null;
  8697. this.skeletons = [];
  8698. this._boundingBoxRenderer.dispose();
  8699. if (this._depthRenderer) {
  8700. this._depthRenderer.dispose();
  8701. }
  8702. // Debug layer
  8703. this.debugLayer.hide();
  8704. // Events
  8705. if (this.onDispose) {
  8706. this.onDispose();
  8707. }
  8708. this._onBeforeRenderCallbacks = [];
  8709. this._onAfterRenderCallbacks = [];
  8710. this.detachControl();
  8711. // Release sounds & sounds tracks
  8712. this.mainSoundTrack.dispose();
  8713. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  8714. this.soundTracks[scIndex].dispose();
  8715. }
  8716. // Detach cameras
  8717. var canvas = this._engine.getRenderingCanvas();
  8718. var index;
  8719. for (index = 0; index < this.cameras.length; index++) {
  8720. this.cameras[index].detachControl(canvas);
  8721. }
  8722. while (this.lights.length) {
  8723. this.lights[0].dispose();
  8724. }
  8725. while (this.meshes.length) {
  8726. this.meshes[0].dispose(true);
  8727. }
  8728. while (this.cameras.length) {
  8729. this.cameras[0].dispose();
  8730. }
  8731. while (this.materials.length) {
  8732. this.materials[0].dispose();
  8733. }
  8734. while (this.particleSystems.length) {
  8735. this.particleSystems[0].dispose();
  8736. }
  8737. while (this.spriteManagers.length) {
  8738. this.spriteManagers[0].dispose();
  8739. }
  8740. while (this.layers.length) {
  8741. this.layers[0].dispose();
  8742. }
  8743. while (this.textures.length) {
  8744. this.textures[0].dispose();
  8745. }
  8746. // Post-processes
  8747. this.postProcessManager.dispose();
  8748. // Physics
  8749. if (this._physicsEngine) {
  8750. this.disablePhysicsEngine();
  8751. }
  8752. // Remove from engine
  8753. index = this._engine.scenes.indexOf(this);
  8754. if (index > -1) {
  8755. this._engine.scenes.splice(index, 1);
  8756. }
  8757. this._engine.wipeCaches();
  8758. };
  8759. // Collisions
  8760. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8761. if (excludedMesh === void 0) { excludedMesh = null; }
  8762. position.divideToRef(collider.radius, this._scaledPosition);
  8763. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8764. collider.retry = 0;
  8765. collider.initialVelocity = this._scaledVelocity;
  8766. collider.initialPosition = this._scaledPosition;
  8767. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8768. finalPosition.multiplyInPlace(collider.radius);
  8769. };
  8770. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8771. if (excludedMesh === void 0) { excludedMesh = null; }
  8772. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8773. if (collider.retry >= maximumRetry) {
  8774. finalPosition.copyFrom(position);
  8775. return;
  8776. }
  8777. collider._initialize(position, velocity, closeDistance);
  8778. for (var index = 0; index < this.meshes.length; index++) {
  8779. var mesh = this.meshes[index];
  8780. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8781. mesh._checkCollision(collider);
  8782. }
  8783. }
  8784. if (!collider.collisionFound) {
  8785. position.addToRef(velocity, finalPosition);
  8786. return;
  8787. }
  8788. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  8789. collider._getResponse(position, velocity);
  8790. }
  8791. if (velocity.length() <= closeDistance) {
  8792. finalPosition.copyFrom(position);
  8793. return;
  8794. }
  8795. collider.retry++;
  8796. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8797. };
  8798. // Octrees
  8799. Scene.prototype.getWorldExtends = function () {
  8800. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8801. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8802. for (var index = 0; index < this.meshes.length; index++) {
  8803. var mesh = this.meshes[index];
  8804. mesh.computeWorldMatrix(true);
  8805. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8806. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8807. BABYLON.Tools.CheckExtends(minBox, min, max);
  8808. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8809. }
  8810. return {
  8811. min: min,
  8812. max: max
  8813. };
  8814. };
  8815. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8816. if (maxCapacity === void 0) { maxCapacity = 64; }
  8817. if (maxDepth === void 0) { maxDepth = 2; }
  8818. if (!this._selectionOctree) {
  8819. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8820. }
  8821. var worldExtends = this.getWorldExtends();
  8822. // Update octree
  8823. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  8824. return this._selectionOctree;
  8825. };
  8826. // Picking
  8827. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8828. var engine = this._engine;
  8829. if (!camera) {
  8830. if (!this.activeCamera)
  8831. throw new Error("Active camera not set");
  8832. camera = this.activeCamera;
  8833. }
  8834. var cameraViewport = camera.viewport;
  8835. var viewport = cameraViewport.toGlobal(engine);
  8836. // Moving coordinates to local viewport world
  8837. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8838. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8839. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8840. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8841. };
  8842. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8843. var pickingInfo = null;
  8844. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8845. var mesh = this.meshes[meshIndex];
  8846. if (predicate) {
  8847. if (!predicate(mesh)) {
  8848. continue;
  8849. }
  8850. }
  8851. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8852. continue;
  8853. }
  8854. var world = mesh.getWorldMatrix();
  8855. var ray = rayFunction(world);
  8856. var result = mesh.intersects(ray, fastCheck);
  8857. if (!result || !result.hit)
  8858. continue;
  8859. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8860. continue;
  8861. pickingInfo = result;
  8862. if (fastCheck) {
  8863. break;
  8864. }
  8865. }
  8866. return pickingInfo || new BABYLON.PickingInfo();
  8867. };
  8868. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8869. var _this = this;
  8870. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8871. /// <param name="x">X position on screen</param>
  8872. /// <param name="y">Y position on screen</param>
  8873. /// <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>
  8874. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8875. /// <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>
  8876. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  8877. };
  8878. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8879. var _this = this;
  8880. return this._internalPick(function (world) {
  8881. if (!_this._pickWithRayInverseMatrix) {
  8882. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8883. }
  8884. world.invertToRef(_this._pickWithRayInverseMatrix);
  8885. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8886. }, predicate, fastCheck);
  8887. };
  8888. Scene.prototype.setPointerOverMesh = function (mesh) {
  8889. if (this._pointerOverMesh === mesh) {
  8890. return;
  8891. }
  8892. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8893. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8894. }
  8895. this._pointerOverMesh = mesh;
  8896. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8897. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8898. }
  8899. };
  8900. Scene.prototype.getPointerOverMesh = function () {
  8901. return this._pointerOverMesh;
  8902. };
  8903. // Physics
  8904. Scene.prototype.getPhysicsEngine = function () {
  8905. return this._physicsEngine;
  8906. };
  8907. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8908. if (this._physicsEngine) {
  8909. return true;
  8910. }
  8911. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8912. if (!this._physicsEngine.isSupported()) {
  8913. this._physicsEngine = null;
  8914. return false;
  8915. }
  8916. this._physicsEngine._initialize(gravity);
  8917. return true;
  8918. };
  8919. Scene.prototype.disablePhysicsEngine = function () {
  8920. if (!this._physicsEngine) {
  8921. return;
  8922. }
  8923. this._physicsEngine.dispose();
  8924. this._physicsEngine = undefined;
  8925. };
  8926. Scene.prototype.isPhysicsEnabled = function () {
  8927. return this._physicsEngine !== undefined;
  8928. };
  8929. Scene.prototype.setGravity = function (gravity) {
  8930. if (!this._physicsEngine) {
  8931. return;
  8932. }
  8933. this._physicsEngine._setGravity(gravity);
  8934. };
  8935. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8936. if (parts.parts) {
  8937. options = parts;
  8938. parts = parts.parts;
  8939. }
  8940. if (!this._physicsEngine) {
  8941. return null;
  8942. }
  8943. for (var index = 0; index < parts.length; index++) {
  8944. var mesh = parts[index].mesh;
  8945. mesh._physicImpostor = parts[index].impostor;
  8946. mesh._physicsMass = options.mass / parts.length;
  8947. mesh._physicsFriction = options.friction;
  8948. mesh._physicRestitution = options.restitution;
  8949. }
  8950. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8951. };
  8952. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8953. for (var index = 0; index < compound.parts.length; index++) {
  8954. var mesh = compound.parts[index].mesh;
  8955. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8956. this._physicsEngine._unregisterMesh(mesh);
  8957. }
  8958. };
  8959. // Misc.
  8960. Scene.prototype.createDefaultCameraOrLight = function () {
  8961. // Light
  8962. if (this.lights.length === 0) {
  8963. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  8964. }
  8965. // Camera
  8966. if (!this.activeCamera) {
  8967. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  8968. // Compute position
  8969. var worldExtends = this.getWorldExtends();
  8970. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  8971. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  8972. camera.setTarget(worldCenter);
  8973. this.activeCamera = camera;
  8974. }
  8975. };
  8976. // Tags
  8977. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  8978. if (tagsQuery === undefined) {
  8979. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  8980. return list;
  8981. }
  8982. var listByTags = [];
  8983. forEach = forEach || (function (item) {
  8984. return;
  8985. });
  8986. for (var i in list) {
  8987. var item = list[i];
  8988. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  8989. listByTags.push(item);
  8990. forEach(item);
  8991. }
  8992. }
  8993. return listByTags;
  8994. };
  8995. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  8996. return this._getByTags(this.meshes, tagsQuery, forEach);
  8997. };
  8998. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  8999. return this._getByTags(this.cameras, tagsQuery, forEach);
  9000. };
  9001. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9002. return this._getByTags(this.lights, tagsQuery, forEach);
  9003. };
  9004. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9005. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9006. };
  9007. // Statics
  9008. Scene._FOGMODE_NONE = 0;
  9009. Scene._FOGMODE_EXP = 1;
  9010. Scene._FOGMODE_EXP2 = 2;
  9011. Scene._FOGMODE_LINEAR = 3;
  9012. Scene.MinDeltaTime = 1.0;
  9013. Scene.MaxDeltaTime = 1000.0;
  9014. return Scene;
  9015. })();
  9016. BABYLON.Scene = Scene;
  9017. })(BABYLON || (BABYLON = {}));
  9018. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9019. (function (BABYLON) {
  9020. var VertexBuffer = (function () {
  9021. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9022. if (engine instanceof BABYLON.Mesh) {
  9023. this._engine = engine.getScene().getEngine();
  9024. }
  9025. else {
  9026. this._engine = engine;
  9027. }
  9028. this._updatable = updatable;
  9029. this._data = data;
  9030. if (!postponeInternalCreation) {
  9031. this.create();
  9032. }
  9033. this._kind = kind;
  9034. if (stride) {
  9035. this._strideSize = stride;
  9036. return;
  9037. }
  9038. switch (kind) {
  9039. case VertexBuffer.PositionKind:
  9040. this._strideSize = 3;
  9041. break;
  9042. case VertexBuffer.NormalKind:
  9043. this._strideSize = 3;
  9044. break;
  9045. case VertexBuffer.UVKind:
  9046. this._strideSize = 2;
  9047. break;
  9048. case VertexBuffer.UV2Kind:
  9049. this._strideSize = 2;
  9050. break;
  9051. case VertexBuffer.ColorKind:
  9052. this._strideSize = 4;
  9053. break;
  9054. case VertexBuffer.MatricesIndicesKind:
  9055. this._strideSize = 4;
  9056. break;
  9057. case VertexBuffer.MatricesWeightsKind:
  9058. this._strideSize = 4;
  9059. break;
  9060. }
  9061. }
  9062. // Properties
  9063. VertexBuffer.prototype.isUpdatable = function () {
  9064. return this._updatable;
  9065. };
  9066. VertexBuffer.prototype.getData = function () {
  9067. return this._data;
  9068. };
  9069. VertexBuffer.prototype.getBuffer = function () {
  9070. return this._buffer;
  9071. };
  9072. VertexBuffer.prototype.getStrideSize = function () {
  9073. return this._strideSize;
  9074. };
  9075. // Methods
  9076. VertexBuffer.prototype.create = function (data) {
  9077. if (!data && this._buffer) {
  9078. return; // nothing to do
  9079. }
  9080. data = data || this._data;
  9081. if (!this._buffer) {
  9082. if (this._updatable) {
  9083. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9084. }
  9085. else {
  9086. this._buffer = this._engine.createVertexBuffer(data);
  9087. }
  9088. }
  9089. if (this._updatable) {
  9090. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9091. this._data = data;
  9092. }
  9093. };
  9094. VertexBuffer.prototype.update = function (data) {
  9095. this.create(data);
  9096. };
  9097. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9098. if (!this._buffer) {
  9099. return;
  9100. }
  9101. if (this._updatable) {
  9102. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9103. this._data = null;
  9104. }
  9105. };
  9106. VertexBuffer.prototype.dispose = function () {
  9107. if (!this._buffer) {
  9108. return;
  9109. }
  9110. if (this._engine._releaseBuffer(this._buffer)) {
  9111. this._buffer = null;
  9112. }
  9113. };
  9114. Object.defineProperty(VertexBuffer, "PositionKind", {
  9115. get: function () {
  9116. return VertexBuffer._PositionKind;
  9117. },
  9118. enumerable: true,
  9119. configurable: true
  9120. });
  9121. Object.defineProperty(VertexBuffer, "NormalKind", {
  9122. get: function () {
  9123. return VertexBuffer._NormalKind;
  9124. },
  9125. enumerable: true,
  9126. configurable: true
  9127. });
  9128. Object.defineProperty(VertexBuffer, "UVKind", {
  9129. get: function () {
  9130. return VertexBuffer._UVKind;
  9131. },
  9132. enumerable: true,
  9133. configurable: true
  9134. });
  9135. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9136. get: function () {
  9137. return VertexBuffer._UV2Kind;
  9138. },
  9139. enumerable: true,
  9140. configurable: true
  9141. });
  9142. Object.defineProperty(VertexBuffer, "ColorKind", {
  9143. get: function () {
  9144. return VertexBuffer._ColorKind;
  9145. },
  9146. enumerable: true,
  9147. configurable: true
  9148. });
  9149. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9150. get: function () {
  9151. return VertexBuffer._MatricesIndicesKind;
  9152. },
  9153. enumerable: true,
  9154. configurable: true
  9155. });
  9156. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9157. get: function () {
  9158. return VertexBuffer._MatricesWeightsKind;
  9159. },
  9160. enumerable: true,
  9161. configurable: true
  9162. });
  9163. // Enums
  9164. VertexBuffer._PositionKind = "position";
  9165. VertexBuffer._NormalKind = "normal";
  9166. VertexBuffer._UVKind = "uv";
  9167. VertexBuffer._UV2Kind = "uv2";
  9168. VertexBuffer._ColorKind = "color";
  9169. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9170. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9171. return VertexBuffer;
  9172. })();
  9173. BABYLON.VertexBuffer = VertexBuffer;
  9174. })(BABYLON || (BABYLON = {}));
  9175. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9176. var BABYLON;
  9177. (function (BABYLON) {
  9178. var AbstractMesh = (function (_super) {
  9179. __extends(AbstractMesh, _super);
  9180. function AbstractMesh(name, scene) {
  9181. _super.call(this, name, scene);
  9182. // Properties
  9183. this.definedFacingForward = true; // orientation for POV movement & rotation
  9184. this.position = new BABYLON.Vector3(0, 0, 0);
  9185. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9186. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9187. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9188. this.visibility = 1.0;
  9189. this.alphaIndex = Number.MAX_VALUE;
  9190. this.infiniteDistance = false;
  9191. this.isVisible = true;
  9192. this.isPickable = true;
  9193. this.showBoundingBox = false;
  9194. this.showSubMeshesBoundingBox = false;
  9195. this.onDispose = null;
  9196. this.checkCollisions = false;
  9197. this.isBlocker = false;
  9198. this.renderingGroupId = 0;
  9199. this.receiveShadows = false;
  9200. this.renderOutline = false;
  9201. this.outlineColor = BABYLON.Color3.Red();
  9202. this.outlineWidth = 0.02;
  9203. this.renderOverlay = false;
  9204. this.overlayColor = BABYLON.Color3.Red();
  9205. this.overlayAlpha = 0.5;
  9206. this.hasVertexAlpha = false;
  9207. this.useVertexColors = true;
  9208. this.applyFog = true;
  9209. this.useOctreeForRenderingSelection = true;
  9210. this.useOctreeForPicking = true;
  9211. this.useOctreeForCollisions = true;
  9212. this.layerMask = 0xFFFFFFFF;
  9213. // Physics
  9214. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9215. // Collisions
  9216. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9217. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9218. this._collider = new BABYLON.Collider();
  9219. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9220. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9221. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9222. // Cache
  9223. this._localScaling = BABYLON.Matrix.Zero();
  9224. this._localRotation = BABYLON.Matrix.Zero();
  9225. this._localTranslation = BABYLON.Matrix.Zero();
  9226. this._localBillboard = BABYLON.Matrix.Zero();
  9227. this._localPivotScaling = BABYLON.Matrix.Zero();
  9228. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9229. this._localWorld = BABYLON.Matrix.Zero();
  9230. this._worldMatrix = BABYLON.Matrix.Zero();
  9231. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9232. this._absolutePosition = BABYLON.Vector3.Zero();
  9233. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9234. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9235. this._isDirty = false;
  9236. this._pivotMatrix = BABYLON.Matrix.Identity();
  9237. this._isDisposed = false;
  9238. this._renderId = 0;
  9239. this._intersectionsInProgress = new Array();
  9240. this._onAfterWorldMatrixUpdate = new Array();
  9241. scene.meshes.push(this);
  9242. }
  9243. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9244. get: function () {
  9245. return AbstractMesh._BILLBOARDMODE_NONE;
  9246. },
  9247. enumerable: true,
  9248. configurable: true
  9249. });
  9250. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9251. get: function () {
  9252. return AbstractMesh._BILLBOARDMODE_X;
  9253. },
  9254. enumerable: true,
  9255. configurable: true
  9256. });
  9257. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9258. get: function () {
  9259. return AbstractMesh._BILLBOARDMODE_Y;
  9260. },
  9261. enumerable: true,
  9262. configurable: true
  9263. });
  9264. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9265. get: function () {
  9266. return AbstractMesh._BILLBOARDMODE_Z;
  9267. },
  9268. enumerable: true,
  9269. configurable: true
  9270. });
  9271. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9272. get: function () {
  9273. return AbstractMesh._BILLBOARDMODE_ALL;
  9274. },
  9275. enumerable: true,
  9276. configurable: true
  9277. });
  9278. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9279. // Methods
  9280. get: function () {
  9281. return false;
  9282. },
  9283. enumerable: true,
  9284. configurable: true
  9285. });
  9286. AbstractMesh.prototype.getLOD = function (camera) {
  9287. return this;
  9288. };
  9289. AbstractMesh.prototype.getTotalVertices = function () {
  9290. return 0;
  9291. };
  9292. AbstractMesh.prototype.getIndices = function () {
  9293. return null;
  9294. };
  9295. AbstractMesh.prototype.getVerticesData = function (kind) {
  9296. return null;
  9297. };
  9298. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9299. return false;
  9300. };
  9301. AbstractMesh.prototype.getBoundingInfo = function () {
  9302. if (this._masterMesh) {
  9303. return this._masterMesh.getBoundingInfo();
  9304. }
  9305. if (!this._boundingInfo) {
  9306. this._updateBoundingInfo();
  9307. }
  9308. return this._boundingInfo;
  9309. };
  9310. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9311. get: function () {
  9312. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9313. },
  9314. enumerable: true,
  9315. configurable: true
  9316. });
  9317. AbstractMesh.prototype._preActivate = function () {
  9318. };
  9319. AbstractMesh.prototype._activate = function (renderId) {
  9320. this._renderId = renderId;
  9321. };
  9322. AbstractMesh.prototype.getWorldMatrix = function () {
  9323. if (this._masterMesh) {
  9324. return this._masterMesh.getWorldMatrix();
  9325. }
  9326. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9327. this.computeWorldMatrix();
  9328. }
  9329. return this._worldMatrix;
  9330. };
  9331. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9332. get: function () {
  9333. return this._worldMatrix;
  9334. },
  9335. enumerable: true,
  9336. configurable: true
  9337. });
  9338. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9339. get: function () {
  9340. return this._absolutePosition;
  9341. },
  9342. enumerable: true,
  9343. configurable: true
  9344. });
  9345. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9346. if (!this.rotationQuaternion) {
  9347. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9348. this.rotation = BABYLON.Vector3.Zero();
  9349. }
  9350. if (!space || space == 0 /* LOCAL */) {
  9351. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9352. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9353. }
  9354. else {
  9355. if (this.parent) {
  9356. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9357. invertParentWorldMatrix.invert();
  9358. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9359. }
  9360. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9361. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9362. }
  9363. };
  9364. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9365. var displacementVector = axis.scale(distance);
  9366. if (!space || space == 0 /* LOCAL */) {
  9367. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9368. this.setPositionWithLocalVector(tempV3);
  9369. }
  9370. else {
  9371. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9372. }
  9373. };
  9374. AbstractMesh.prototype.getAbsolutePosition = function () {
  9375. this.computeWorldMatrix();
  9376. return this._absolutePosition;
  9377. };
  9378. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9379. if (!absolutePosition) {
  9380. return;
  9381. }
  9382. var absolutePositionX;
  9383. var absolutePositionY;
  9384. var absolutePositionZ;
  9385. if (absolutePosition.x === undefined) {
  9386. if (arguments.length < 3) {
  9387. return;
  9388. }
  9389. absolutePositionX = arguments[0];
  9390. absolutePositionY = arguments[1];
  9391. absolutePositionZ = arguments[2];
  9392. }
  9393. else {
  9394. absolutePositionX = absolutePosition.x;
  9395. absolutePositionY = absolutePosition.y;
  9396. absolutePositionZ = absolutePosition.z;
  9397. }
  9398. if (this.parent) {
  9399. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9400. invertParentWorldMatrix.invert();
  9401. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9402. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9403. }
  9404. else {
  9405. this.position.x = absolutePositionX;
  9406. this.position.y = absolutePositionY;
  9407. this.position.z = absolutePositionZ;
  9408. }
  9409. };
  9410. // ================================== Point of View Movement =================================
  9411. /**
  9412. * Perform relative position change from the point of view of behind the front of the mesh.
  9413. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9414. * Supports definition of mesh facing forward or backward.
  9415. * @param {number} amountRight
  9416. * @param {number} amountUp
  9417. * @param {number} amountForward
  9418. */
  9419. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9420. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9421. };
  9422. /**
  9423. * Calculate relative position change from the point of view of behind the front of the mesh.
  9424. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9425. * Supports definition of mesh facing forward or backward.
  9426. * @param {number} amountRight
  9427. * @param {number} amountUp
  9428. * @param {number} amountForward
  9429. */
  9430. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9431. var rotMatrix = new BABYLON.Matrix();
  9432. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9433. rotQuaternion.toRotationMatrix(rotMatrix);
  9434. var translationDelta = BABYLON.Vector3.Zero();
  9435. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9436. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9437. return translationDelta;
  9438. };
  9439. // ================================== Point of View Rotation =================================
  9440. /**
  9441. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9442. * Supports definition of mesh facing forward or backward.
  9443. * @param {number} flipBack
  9444. * @param {number} twirlClockwise
  9445. * @param {number} tiltRight
  9446. */
  9447. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9448. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9449. };
  9450. /**
  9451. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9452. * Supports definition of mesh facing forward or backward.
  9453. * @param {number} flipBack
  9454. * @param {number} twirlClockwise
  9455. * @param {number} tiltRight
  9456. */
  9457. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9458. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9459. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9460. };
  9461. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9462. this._pivotMatrix = matrix;
  9463. this._cache.pivotMatrixUpdated = true;
  9464. };
  9465. AbstractMesh.prototype.getPivotMatrix = function () {
  9466. return this._pivotMatrix;
  9467. };
  9468. AbstractMesh.prototype._isSynchronized = function () {
  9469. if (this._isDirty) {
  9470. return false;
  9471. }
  9472. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9473. return false;
  9474. if (this._cache.pivotMatrixUpdated) {
  9475. return false;
  9476. }
  9477. if (this.infiniteDistance) {
  9478. return false;
  9479. }
  9480. if (!this._cache.position.equals(this.position))
  9481. return false;
  9482. if (this.rotationQuaternion) {
  9483. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9484. return false;
  9485. }
  9486. else {
  9487. if (!this._cache.rotation.equals(this.rotation))
  9488. return false;
  9489. }
  9490. if (!this._cache.scaling.equals(this.scaling))
  9491. return false;
  9492. return true;
  9493. };
  9494. AbstractMesh.prototype._initCache = function () {
  9495. _super.prototype._initCache.call(this);
  9496. this._cache.localMatrixUpdated = false;
  9497. this._cache.position = BABYLON.Vector3.Zero();
  9498. this._cache.scaling = BABYLON.Vector3.Zero();
  9499. this._cache.rotation = BABYLON.Vector3.Zero();
  9500. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9501. };
  9502. AbstractMesh.prototype.markAsDirty = function (property) {
  9503. if (property === "rotation") {
  9504. this.rotationQuaternion = null;
  9505. }
  9506. this._currentRenderId = Number.MAX_VALUE;
  9507. this._isDirty = true;
  9508. };
  9509. AbstractMesh.prototype._updateBoundingInfo = function () {
  9510. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9511. this._boundingInfo._update(this.worldMatrixFromCache);
  9512. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9513. };
  9514. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9515. if (!this.subMeshes) {
  9516. return;
  9517. }
  9518. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9519. var subMesh = this.subMeshes[subIndex];
  9520. subMesh.updateBoundingInfo(matrix);
  9521. }
  9522. };
  9523. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9524. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  9525. return this._worldMatrix;
  9526. }
  9527. this._cache.position.copyFrom(this.position);
  9528. this._cache.scaling.copyFrom(this.scaling);
  9529. this._cache.pivotMatrixUpdated = false;
  9530. this._currentRenderId = this.getScene().getRenderId();
  9531. this._isDirty = false;
  9532. // Scaling
  9533. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  9534. // Rotation
  9535. if (this.rotationQuaternion) {
  9536. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  9537. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9538. }
  9539. else {
  9540. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  9541. this._cache.rotation.copyFrom(this.rotation);
  9542. }
  9543. // Translation
  9544. if (this.infiniteDistance && !this.parent) {
  9545. var camera = this.getScene().activeCamera;
  9546. var cameraWorldMatrix = camera.getWorldMatrix();
  9547. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9548. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  9549. }
  9550. else {
  9551. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  9552. }
  9553. // Composing transformations
  9554. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  9555. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  9556. // Billboarding
  9557. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9558. var localPosition = this.position.clone();
  9559. var zero = this.getScene().activeCamera.position.clone();
  9560. if (this.parent && this.parent.position) {
  9561. localPosition.addInPlace(this.parent.position);
  9562. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  9563. }
  9564. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  9565. zero = this.getScene().activeCamera.position;
  9566. }
  9567. else {
  9568. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  9569. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  9570. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  9571. zero.y = localPosition.y + 0.001;
  9572. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  9573. zero.z = localPosition.z + 0.001;
  9574. }
  9575. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  9576. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  9577. this._localBillboard.invert();
  9578. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  9579. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  9580. }
  9581. // Local world
  9582. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  9583. // Parent
  9584. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  9585. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9586. }
  9587. else {
  9588. this._worldMatrix.copyFrom(this._localWorld);
  9589. }
  9590. // Bounding info
  9591. this._updateBoundingInfo();
  9592. // Absolute position
  9593. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9594. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  9595. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  9596. }
  9597. return this._worldMatrix;
  9598. };
  9599. /**
  9600. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9601. * @param func: callback function to add
  9602. */
  9603. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9604. this._onAfterWorldMatrixUpdate.push(func);
  9605. };
  9606. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9607. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  9608. if (index > -1) {
  9609. this._onAfterWorldMatrixUpdate.splice(index, 1);
  9610. }
  9611. };
  9612. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9613. this.computeWorldMatrix();
  9614. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9615. };
  9616. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9617. this.computeWorldMatrix();
  9618. var invLocalWorldMatrix = this._localWorld.clone();
  9619. invLocalWorldMatrix.invert();
  9620. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9621. };
  9622. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9623. this.computeWorldMatrix();
  9624. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9625. };
  9626. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9627. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9628. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  9629. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9630. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9631. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9632. /// <returns>Mesh oriented towards targetMesh</returns>
  9633. yawCor = yawCor || 0; // default to zero if undefined
  9634. pitchCor = pitchCor || 0;
  9635. rollCor = rollCor || 0;
  9636. var dv = targetPoint.subtract(this.position);
  9637. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9638. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9639. var pitch = Math.atan2(dv.y, len);
  9640. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9641. };
  9642. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9643. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  9644. return false;
  9645. }
  9646. return true;
  9647. };
  9648. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9649. if (!camera) {
  9650. camera = this.getScene().activeCamera;
  9651. }
  9652. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9653. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9654. return false;
  9655. }
  9656. return true;
  9657. };
  9658. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9659. if (!this._boundingInfo || !mesh._boundingInfo) {
  9660. return false;
  9661. }
  9662. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9663. };
  9664. AbstractMesh.prototype.intersectsPoint = function (point) {
  9665. if (!this._boundingInfo) {
  9666. return false;
  9667. }
  9668. return this._boundingInfo.intersectsPoint(point);
  9669. };
  9670. // Physics
  9671. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9672. var physicsEngine = this.getScene().getPhysicsEngine();
  9673. if (!physicsEngine) {
  9674. return;
  9675. }
  9676. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  9677. if (impostor.impostor) {
  9678. // Old API
  9679. options = impostor;
  9680. impostor = impostor.impostor;
  9681. }
  9682. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  9683. physicsEngine._unregisterMesh(this);
  9684. return;
  9685. }
  9686. if (!options) {
  9687. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  9688. }
  9689. else {
  9690. options.mass = options.mass || 0;
  9691. options.friction = options.friction || 0.2;
  9692. options.restitution = options.restitution || 0.2;
  9693. }
  9694. this._physicImpostor = impostor;
  9695. this._physicsMass = options.mass;
  9696. this._physicsFriction = options.friction;
  9697. this._physicRestitution = options.restitution;
  9698. return physicsEngine._registerMesh(this, impostor, options);
  9699. };
  9700. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9701. if (!this._physicImpostor) {
  9702. return BABYLON.PhysicsEngine.NoImpostor;
  9703. }
  9704. return this._physicImpostor;
  9705. };
  9706. AbstractMesh.prototype.getPhysicsMass = function () {
  9707. if (!this._physicsMass) {
  9708. return 0;
  9709. }
  9710. return this._physicsMass;
  9711. };
  9712. AbstractMesh.prototype.getPhysicsFriction = function () {
  9713. if (!this._physicsFriction) {
  9714. return 0;
  9715. }
  9716. return this._physicsFriction;
  9717. };
  9718. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9719. if (!this._physicRestitution) {
  9720. return 0;
  9721. }
  9722. return this._physicRestitution;
  9723. };
  9724. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9725. if (!camera) {
  9726. camera = this.getScene().activeCamera;
  9727. }
  9728. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9729. };
  9730. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9731. if (!camera) {
  9732. camera = this.getScene().activeCamera;
  9733. }
  9734. return this.absolutePosition.subtract(camera.position).length();
  9735. };
  9736. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9737. if (!this._physicImpostor) {
  9738. return;
  9739. }
  9740. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  9741. };
  9742. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9743. if (!this._physicImpostor) {
  9744. return;
  9745. }
  9746. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  9747. };
  9748. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9749. if (!this._physicImpostor) {
  9750. return;
  9751. }
  9752. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  9753. };
  9754. // Collisions
  9755. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9756. var globalPosition = this.getAbsolutePosition();
  9757. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9758. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9759. this._collider.radius = this.ellipsoid;
  9760. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  9761. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  9762. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9763. this.position.addInPlace(this._diffPositionForCollisions);
  9764. }
  9765. };
  9766. // Submeshes octree
  9767. /**
  9768. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9769. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9770. */
  9771. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9772. if (maxCapacity === void 0) { maxCapacity = 64; }
  9773. if (maxDepth === void 0) { maxDepth = 2; }
  9774. if (!this._submeshesOctree) {
  9775. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9776. }
  9777. this.computeWorldMatrix(true);
  9778. // Update octree
  9779. var bbox = this.getBoundingInfo().boundingBox;
  9780. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9781. return this._submeshesOctree;
  9782. };
  9783. // Collisions
  9784. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9785. this._generatePointsArray();
  9786. // Transformation
  9787. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9788. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9789. subMesh._lastColliderWorldVertices = [];
  9790. subMesh._trianglePlanes = [];
  9791. var start = subMesh.verticesStart;
  9792. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9793. for (var i = start; i < end; i++) {
  9794. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9795. }
  9796. }
  9797. // Collide
  9798. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  9799. };
  9800. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9801. var subMeshes;
  9802. var len;
  9803. // Octrees
  9804. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9805. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9806. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9807. len = intersections.length;
  9808. subMeshes = intersections.data;
  9809. }
  9810. else {
  9811. subMeshes = this.subMeshes;
  9812. len = subMeshes.length;
  9813. }
  9814. for (var index = 0; index < len; index++) {
  9815. var subMesh = subMeshes[index];
  9816. // Bounding test
  9817. if (len > 1 && !subMesh._checkCollision(collider))
  9818. continue;
  9819. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9820. }
  9821. };
  9822. AbstractMesh.prototype._checkCollision = function (collider) {
  9823. // Bounding box test
  9824. if (!this._boundingInfo._checkCollision(collider))
  9825. return;
  9826. // Transformation matrix
  9827. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9828. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9829. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9830. };
  9831. // Picking
  9832. AbstractMesh.prototype._generatePointsArray = function () {
  9833. return false;
  9834. };
  9835. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9836. var pickingInfo = new BABYLON.PickingInfo();
  9837. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9838. return pickingInfo;
  9839. }
  9840. if (!this._generatePointsArray()) {
  9841. return pickingInfo;
  9842. }
  9843. var intersectInfo = null;
  9844. // Octrees
  9845. var subMeshes;
  9846. var len;
  9847. if (this._submeshesOctree && this.useOctreeForPicking) {
  9848. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9849. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9850. len = intersections.length;
  9851. subMeshes = intersections.data;
  9852. }
  9853. else {
  9854. subMeshes = this.subMeshes;
  9855. len = subMeshes.length;
  9856. }
  9857. for (var index = 0; index < len; index++) {
  9858. var subMesh = subMeshes[index];
  9859. // Bounding test
  9860. if (len > 1 && !subMesh.canIntersects(ray))
  9861. continue;
  9862. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9863. if (currentIntersectInfo) {
  9864. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9865. intersectInfo = currentIntersectInfo;
  9866. if (fastCheck) {
  9867. break;
  9868. }
  9869. }
  9870. }
  9871. }
  9872. if (intersectInfo) {
  9873. // Get picked point
  9874. var world = this.getWorldMatrix();
  9875. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9876. var direction = ray.direction.clone();
  9877. direction = direction.scale(intersectInfo.distance);
  9878. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9879. var pickedPoint = worldOrigin.add(worldDirection);
  9880. // Return result
  9881. pickingInfo.hit = true;
  9882. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9883. pickingInfo.pickedPoint = pickedPoint;
  9884. pickingInfo.pickedMesh = this;
  9885. pickingInfo.bu = intersectInfo.bu;
  9886. pickingInfo.bv = intersectInfo.bv;
  9887. pickingInfo.faceId = intersectInfo.faceId;
  9888. return pickingInfo;
  9889. }
  9890. return pickingInfo;
  9891. };
  9892. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9893. return null;
  9894. };
  9895. AbstractMesh.prototype.releaseSubMeshes = function () {
  9896. if (this.subMeshes) {
  9897. while (this.subMeshes.length) {
  9898. this.subMeshes[0].dispose();
  9899. }
  9900. }
  9901. else {
  9902. this.subMeshes = new Array();
  9903. }
  9904. };
  9905. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9906. // Physics
  9907. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  9908. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  9909. }
  9910. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9911. var other = this._intersectionsInProgress[index];
  9912. var pos = other._intersectionsInProgress.indexOf(this);
  9913. other._intersectionsInProgress.splice(pos, 1);
  9914. }
  9915. this._intersectionsInProgress = [];
  9916. // SubMeshes
  9917. this.releaseSubMeshes();
  9918. // Remove from scene
  9919. var index = this.getScene().meshes.indexOf(this);
  9920. if (index != -1) {
  9921. // Remove from the scene if mesh found
  9922. this.getScene().meshes.splice(index, 1);
  9923. }
  9924. if (!doNotRecurse) {
  9925. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9926. if (this.getScene().particleSystems[index].emitter == this) {
  9927. this.getScene().particleSystems[index].dispose();
  9928. index--;
  9929. }
  9930. }
  9931. // Children
  9932. var objects = this.getScene().meshes.slice(0);
  9933. for (index = 0; index < objects.length; index++) {
  9934. if (objects[index].parent == this) {
  9935. objects[index].dispose();
  9936. }
  9937. }
  9938. }
  9939. else {
  9940. for (index = 0; index < this.getScene().meshes.length; index++) {
  9941. var obj = this.getScene().meshes[index];
  9942. if (obj.parent === this) {
  9943. obj.parent = null;
  9944. obj.computeWorldMatrix(true);
  9945. }
  9946. }
  9947. }
  9948. this._onAfterWorldMatrixUpdate = [];
  9949. this._isDisposed = true;
  9950. // Callback
  9951. if (this.onDispose) {
  9952. this.onDispose();
  9953. }
  9954. };
  9955. // Statics
  9956. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9957. AbstractMesh._BILLBOARDMODE_X = 1;
  9958. AbstractMesh._BILLBOARDMODE_Y = 2;
  9959. AbstractMesh._BILLBOARDMODE_Z = 4;
  9960. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9961. return AbstractMesh;
  9962. })(BABYLON.Node);
  9963. BABYLON.AbstractMesh = AbstractMesh;
  9964. })(BABYLON || (BABYLON = {}));
  9965. //# sourceMappingURL=babylon.abstractMesh.js.map
  9966. var BABYLON;
  9967. (function (BABYLON) {
  9968. var _InstancesBatch = (function () {
  9969. function _InstancesBatch() {
  9970. this.mustReturn = false;
  9971. this.visibleInstances = new Array();
  9972. this.renderSelf = new Array();
  9973. }
  9974. return _InstancesBatch;
  9975. })();
  9976. BABYLON._InstancesBatch = _InstancesBatch;
  9977. var Mesh = (function (_super) {
  9978. __extends(Mesh, _super);
  9979. /**
  9980. * @constructor
  9981. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  9982. * @param {Scene} scene - The scene to add this mesh to.
  9983. * @param {Node} parent - The parent of this mesh, if it has one
  9984. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  9985. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  9986. * When false, achieved by calling a clone(), also passing False.
  9987. * This will make creation of children, recursive.
  9988. */
  9989. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  9990. if (parent === void 0) { parent = null; }
  9991. _super.call(this, name, scene);
  9992. // Members
  9993. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9994. this.instances = new Array();
  9995. this._LODLevels = new Array();
  9996. this._onBeforeRenderCallbacks = new Array();
  9997. this._onAfterRenderCallbacks = new Array();
  9998. this._visibleInstances = {};
  9999. this._renderIdForInstances = new Array();
  10000. this._batchCache = new _InstancesBatch();
  10001. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10002. if (source) {
  10003. // Geometry
  10004. if (source._geometry) {
  10005. source._geometry.applyToMesh(this);
  10006. }
  10007. // Deep copy
  10008. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10009. // Material
  10010. this.material = source.material;
  10011. if (!doNotCloneChildren) {
  10012. for (var index = 0; index < scene.meshes.length; index++) {
  10013. var mesh = scene.meshes[index];
  10014. if (mesh.parent === source) {
  10015. // doNotCloneChildren is always going to be False
  10016. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10017. }
  10018. }
  10019. }
  10020. for (index = 0; index < scene.particleSystems.length; index++) {
  10021. var system = scene.particleSystems[index];
  10022. if (system.emitter === source) {
  10023. system.clone(system.name, this);
  10024. }
  10025. }
  10026. this.computeWorldMatrix(true);
  10027. }
  10028. // Parent
  10029. if (parent !== null) {
  10030. this.parent = parent;
  10031. }
  10032. }
  10033. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10034. // Methods
  10035. get: function () {
  10036. return this._LODLevels.length > 0;
  10037. },
  10038. enumerable: true,
  10039. configurable: true
  10040. });
  10041. Mesh.prototype._sortLODLevels = function () {
  10042. this._LODLevels.sort(function (a, b) {
  10043. if (a.distance < b.distance) {
  10044. return 1;
  10045. }
  10046. if (a.distance > b.distance) {
  10047. return -1;
  10048. }
  10049. return 0;
  10050. });
  10051. };
  10052. /**
  10053. * Add a mesh as LOD level triggered at the given distance.
  10054. * @param {number} distance - the distance from the center of the object to show this level
  10055. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10056. * @return {BABYLON.Mesh} this mesh (for chaining)
  10057. */
  10058. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10059. if (mesh && mesh._masterMesh) {
  10060. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10061. return this;
  10062. }
  10063. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10064. this._LODLevels.push(level);
  10065. if (mesh) {
  10066. mesh._masterMesh = this;
  10067. }
  10068. this._sortLODLevels();
  10069. return this;
  10070. };
  10071. /**
  10072. * Remove a mesh from the LOD array
  10073. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10074. * @return {BABYLON.Mesh} this mesh (for chaining)
  10075. */
  10076. Mesh.prototype.removeLODLevel = function (mesh) {
  10077. for (var index = 0; index < this._LODLevels.length; index++) {
  10078. if (this._LODLevels[index].mesh === mesh) {
  10079. this._LODLevels.splice(index, 1);
  10080. if (mesh) {
  10081. mesh._masterMesh = null;
  10082. }
  10083. }
  10084. }
  10085. this._sortLODLevels();
  10086. return this;
  10087. };
  10088. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  10089. if (!this._LODLevels || this._LODLevels.length === 0) {
  10090. return this;
  10091. }
  10092. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  10093. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  10094. return this;
  10095. }
  10096. for (var index = 0; index < this._LODLevels.length; index++) {
  10097. var level = this._LODLevels[index];
  10098. if (level.distance < distanceToCamera) {
  10099. if (level.mesh) {
  10100. level.mesh._preActivate();
  10101. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10102. }
  10103. return level.mesh;
  10104. }
  10105. }
  10106. return this;
  10107. };
  10108. Object.defineProperty(Mesh.prototype, "geometry", {
  10109. get: function () {
  10110. return this._geometry;
  10111. },
  10112. enumerable: true,
  10113. configurable: true
  10114. });
  10115. Mesh.prototype.getTotalVertices = function () {
  10116. if (!this._geometry) {
  10117. return 0;
  10118. }
  10119. return this._geometry.getTotalVertices();
  10120. };
  10121. Mesh.prototype.getVerticesData = function (kind) {
  10122. if (!this._geometry) {
  10123. return null;
  10124. }
  10125. return this._geometry.getVerticesData(kind);
  10126. };
  10127. Mesh.prototype.getVertexBuffer = function (kind) {
  10128. if (!this._geometry) {
  10129. return undefined;
  10130. }
  10131. return this._geometry.getVertexBuffer(kind);
  10132. };
  10133. Mesh.prototype.isVerticesDataPresent = function (kind) {
  10134. if (!this._geometry) {
  10135. if (this._delayInfo) {
  10136. return this._delayInfo.indexOf(kind) !== -1;
  10137. }
  10138. return false;
  10139. }
  10140. return this._geometry.isVerticesDataPresent(kind);
  10141. };
  10142. Mesh.prototype.getVerticesDataKinds = function () {
  10143. if (!this._geometry) {
  10144. var result = [];
  10145. if (this._delayInfo) {
  10146. for (var kind in this._delayInfo) {
  10147. result.push(kind);
  10148. }
  10149. }
  10150. return result;
  10151. }
  10152. return this._geometry.getVerticesDataKinds();
  10153. };
  10154. Mesh.prototype.getTotalIndices = function () {
  10155. if (!this._geometry) {
  10156. return 0;
  10157. }
  10158. return this._geometry.getTotalIndices();
  10159. };
  10160. Mesh.prototype.getIndices = function () {
  10161. if (!this._geometry) {
  10162. return [];
  10163. }
  10164. return this._geometry.getIndices();
  10165. };
  10166. Object.defineProperty(Mesh.prototype, "isBlocked", {
  10167. get: function () {
  10168. return this._masterMesh !== null && this._masterMesh !== undefined;
  10169. },
  10170. enumerable: true,
  10171. configurable: true
  10172. });
  10173. Mesh.prototype.isReady = function () {
  10174. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10175. return false;
  10176. }
  10177. return _super.prototype.isReady.call(this);
  10178. };
  10179. Mesh.prototype.isDisposed = function () {
  10180. return this._isDisposed;
  10181. };
  10182. // Methods
  10183. Mesh.prototype._preActivate = function () {
  10184. var sceneRenderId = this.getScene().getRenderId();
  10185. if (this._preActivateId == sceneRenderId) {
  10186. return;
  10187. }
  10188. this._preActivateId = sceneRenderId;
  10189. this._visibleInstances = null;
  10190. };
  10191. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  10192. if (!this._visibleInstances) {
  10193. this._visibleInstances = {};
  10194. this._visibleInstances.defaultRenderId = renderId;
  10195. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10196. }
  10197. if (!this._visibleInstances[renderId]) {
  10198. this._visibleInstances[renderId] = new Array();
  10199. }
  10200. this._visibleInstances[renderId].push(instance);
  10201. };
  10202. Mesh.prototype.refreshBoundingInfo = function () {
  10203. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10204. if (data) {
  10205. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10206. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10207. }
  10208. if (this.subMeshes) {
  10209. for (var index = 0; index < this.subMeshes.length; index++) {
  10210. this.subMeshes[index].refreshBoundingInfo();
  10211. }
  10212. }
  10213. this._updateBoundingInfo();
  10214. };
  10215. Mesh.prototype._createGlobalSubMesh = function () {
  10216. var totalVertices = this.getTotalVertices();
  10217. if (!totalVertices || !this.getIndices()) {
  10218. return null;
  10219. }
  10220. this.releaseSubMeshes();
  10221. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10222. };
  10223. Mesh.prototype.subdivide = function (count) {
  10224. if (count < 1) {
  10225. return;
  10226. }
  10227. var totalIndices = this.getTotalIndices();
  10228. var subdivisionSize = (totalIndices / count) | 0;
  10229. var offset = 0;
  10230. while (subdivisionSize % 3 != 0) {
  10231. subdivisionSize++;
  10232. }
  10233. this.releaseSubMeshes();
  10234. for (var index = 0; index < count; index++) {
  10235. if (offset >= totalIndices) {
  10236. break;
  10237. }
  10238. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10239. offset += subdivisionSize;
  10240. }
  10241. this.synchronizeInstances();
  10242. };
  10243. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10244. if (kind instanceof Array) {
  10245. var temp = data;
  10246. data = kind;
  10247. kind = temp;
  10248. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10249. }
  10250. if (!this._geometry) {
  10251. var vertexData = new BABYLON.VertexData();
  10252. vertexData.set(data, kind);
  10253. var scene = this.getScene();
  10254. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10255. }
  10256. else {
  10257. this._geometry.setVerticesData(kind, data, updatable, stride);
  10258. }
  10259. };
  10260. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10261. if (!this._geometry) {
  10262. return;
  10263. }
  10264. if (!makeItUnique) {
  10265. this._geometry.updateVerticesData(kind, data, updateExtends);
  10266. }
  10267. else {
  10268. this.makeGeometryUnique();
  10269. this.updateVerticesData(kind, data, updateExtends, false);
  10270. }
  10271. };
  10272. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  10273. if (!this._geometry) {
  10274. return;
  10275. }
  10276. if (!makeItUnique) {
  10277. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  10278. }
  10279. else {
  10280. this.makeGeometryUnique();
  10281. this.updateVerticesDataDirectly(kind, data, offset, false);
  10282. }
  10283. };
  10284. Mesh.prototype.makeGeometryUnique = function () {
  10285. if (!this._geometry) {
  10286. return;
  10287. }
  10288. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  10289. geometry.applyToMesh(this);
  10290. };
  10291. Mesh.prototype.setIndices = function (indices, totalVertices) {
  10292. if (!this._geometry) {
  10293. var vertexData = new BABYLON.VertexData();
  10294. vertexData.indices = indices;
  10295. var scene = this.getScene();
  10296. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  10297. }
  10298. else {
  10299. this._geometry.setIndices(indices, totalVertices);
  10300. }
  10301. };
  10302. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  10303. var engine = this.getScene().getEngine();
  10304. // Wireframe
  10305. var indexToBind;
  10306. switch (fillMode) {
  10307. case BABYLON.Material.PointFillMode:
  10308. indexToBind = null;
  10309. break;
  10310. case BABYLON.Material.WireFrameFillMode:
  10311. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  10312. break;
  10313. default:
  10314. case BABYLON.Material.TriangleFillMode:
  10315. indexToBind = this._geometry.getIndexBuffer();
  10316. break;
  10317. }
  10318. // VBOs
  10319. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  10320. };
  10321. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  10322. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10323. return;
  10324. }
  10325. var engine = this.getScene().getEngine();
  10326. switch (fillMode) {
  10327. case BABYLON.Material.PointFillMode:
  10328. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  10329. break;
  10330. case BABYLON.Material.WireFrameFillMode:
  10331. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  10332. break;
  10333. default:
  10334. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  10335. }
  10336. };
  10337. Mesh.prototype.registerBeforeRender = function (func) {
  10338. this._onBeforeRenderCallbacks.push(func);
  10339. };
  10340. Mesh.prototype.unregisterBeforeRender = function (func) {
  10341. var index = this._onBeforeRenderCallbacks.indexOf(func);
  10342. if (index > -1) {
  10343. this._onBeforeRenderCallbacks.splice(index, 1);
  10344. }
  10345. };
  10346. Mesh.prototype.registerAfterRender = function (func) {
  10347. this._onAfterRenderCallbacks.push(func);
  10348. };
  10349. Mesh.prototype.unregisterAfterRender = function (func) {
  10350. var index = this._onAfterRenderCallbacks.indexOf(func);
  10351. if (index > -1) {
  10352. this._onAfterRenderCallbacks.splice(index, 1);
  10353. }
  10354. };
  10355. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  10356. var scene = this.getScene();
  10357. this._batchCache.mustReturn = false;
  10358. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  10359. this._batchCache.visibleInstances[subMeshId] = null;
  10360. if (this._visibleInstances) {
  10361. var currentRenderId = scene.getRenderId();
  10362. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  10363. var selfRenderId = this._renderId;
  10364. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  10365. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  10366. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  10367. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  10368. }
  10369. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  10370. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  10371. this._batchCache.mustReturn = true;
  10372. return this._batchCache;
  10373. }
  10374. if (currentRenderId !== selfRenderId) {
  10375. this._batchCache.renderSelf[subMeshId] = false;
  10376. }
  10377. }
  10378. this._renderIdForInstances[subMeshId] = currentRenderId;
  10379. }
  10380. return this._batchCache;
  10381. };
  10382. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  10383. var visibleInstances = batch.visibleInstances[subMesh._id];
  10384. var matricesCount = visibleInstances.length + 1;
  10385. var bufferSize = matricesCount * 16 * 4;
  10386. while (this._instancesBufferSize < bufferSize) {
  10387. this._instancesBufferSize *= 2;
  10388. }
  10389. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  10390. if (this._worldMatricesInstancesBuffer) {
  10391. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10392. }
  10393. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  10394. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  10395. }
  10396. var offset = 0;
  10397. var instancesCount = 0;
  10398. var world = this.getWorldMatrix();
  10399. if (batch.renderSelf[subMesh._id]) {
  10400. world.copyToArray(this._worldMatricesInstancesArray, offset);
  10401. offset += 16;
  10402. instancesCount++;
  10403. }
  10404. if (visibleInstances) {
  10405. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  10406. var instance = visibleInstances[instanceIndex];
  10407. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  10408. offset += 16;
  10409. instancesCount++;
  10410. }
  10411. }
  10412. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  10413. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  10414. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  10415. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  10416. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  10417. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  10418. this._draw(subMesh, fillMode, instancesCount);
  10419. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  10420. };
  10421. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  10422. var scene = this.getScene();
  10423. var engine = scene.getEngine();
  10424. if (hardwareInstancedRendering) {
  10425. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  10426. }
  10427. else {
  10428. if (batch.renderSelf[subMesh._id]) {
  10429. // Draw
  10430. if (onBeforeDraw) {
  10431. onBeforeDraw(false, this.getWorldMatrix());
  10432. }
  10433. this._draw(subMesh, fillMode);
  10434. }
  10435. if (batch.visibleInstances[subMesh._id]) {
  10436. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  10437. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  10438. // World
  10439. var world = instance.getWorldMatrix();
  10440. if (onBeforeDraw) {
  10441. onBeforeDraw(true, world);
  10442. }
  10443. // Draw
  10444. this._draw(subMesh, fillMode);
  10445. }
  10446. }
  10447. }
  10448. };
  10449. Mesh.prototype.render = function (subMesh) {
  10450. var scene = this.getScene();
  10451. // Managing instances
  10452. var batch = this._getInstancesRenderList(subMesh._id);
  10453. if (batch.mustReturn) {
  10454. return;
  10455. }
  10456. // Checking geometry state
  10457. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10458. return;
  10459. }
  10460. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  10461. this._onBeforeRenderCallbacks[callbackIndex]();
  10462. }
  10463. var engine = scene.getEngine();
  10464. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10465. // Material
  10466. var effectiveMaterial = subMesh.getMaterial();
  10467. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  10468. return;
  10469. }
  10470. // Outline - step 1
  10471. var savedDepthWrite = engine.getDepthWrite();
  10472. if (this.renderOutline) {
  10473. engine.setDepthWrite(false);
  10474. scene.getOutlineRenderer().render(subMesh, batch);
  10475. engine.setDepthWrite(savedDepthWrite);
  10476. }
  10477. effectiveMaterial._preBind();
  10478. var effect = effectiveMaterial.getEffect();
  10479. // Bind
  10480. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  10481. this._bind(subMesh, effect, fillMode);
  10482. var world = this.getWorldMatrix();
  10483. effectiveMaterial.bind(world, this);
  10484. // Draw
  10485. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  10486. if (isInstance) {
  10487. effectiveMaterial.bindOnlyWorldMatrix(world);
  10488. }
  10489. });
  10490. // Unbind
  10491. effectiveMaterial.unbind();
  10492. // Outline - step 2
  10493. if (this.renderOutline && savedDepthWrite) {
  10494. engine.setDepthWrite(true);
  10495. engine.setColorWrite(false);
  10496. scene.getOutlineRenderer().render(subMesh, batch);
  10497. engine.setColorWrite(true);
  10498. }
  10499. // Overlay
  10500. if (this.renderOverlay) {
  10501. var currentMode = engine.getAlphaMode();
  10502. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10503. scene.getOutlineRenderer().render(subMesh, batch, true);
  10504. engine.setAlphaMode(currentMode);
  10505. }
  10506. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  10507. this._onAfterRenderCallbacks[callbackIndex]();
  10508. }
  10509. };
  10510. Mesh.prototype.getEmittedParticleSystems = function () {
  10511. var results = new Array();
  10512. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10513. var particleSystem = this.getScene().particleSystems[index];
  10514. if (particleSystem.emitter === this) {
  10515. results.push(particleSystem);
  10516. }
  10517. }
  10518. return results;
  10519. };
  10520. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  10521. var results = new Array();
  10522. var descendants = this.getDescendants();
  10523. descendants.push(this);
  10524. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10525. var particleSystem = this.getScene().particleSystems[index];
  10526. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  10527. results.push(particleSystem);
  10528. }
  10529. }
  10530. return results;
  10531. };
  10532. Mesh.prototype.getChildren = function () {
  10533. var results = [];
  10534. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10535. var mesh = this.getScene().meshes[index];
  10536. if (mesh.parent === this) {
  10537. results.push(mesh);
  10538. }
  10539. }
  10540. return results;
  10541. };
  10542. Mesh.prototype._checkDelayState = function () {
  10543. var _this = this;
  10544. var that = this;
  10545. var scene = this.getScene();
  10546. if (this._geometry) {
  10547. this._geometry.load(scene);
  10548. }
  10549. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10550. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  10551. scene._addPendingData(that);
  10552. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  10553. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  10554. if (data instanceof ArrayBuffer) {
  10555. _this._delayLoadingFunction(data, _this);
  10556. }
  10557. else {
  10558. _this._delayLoadingFunction(JSON.parse(data), _this);
  10559. }
  10560. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10561. scene._removePendingData(_this);
  10562. }, function () {
  10563. }, scene.database, getBinaryData);
  10564. }
  10565. };
  10566. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  10567. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10568. return false;
  10569. }
  10570. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  10571. return false;
  10572. }
  10573. this._checkDelayState();
  10574. return true;
  10575. };
  10576. Mesh.prototype.setMaterialByID = function (id) {
  10577. var materials = this.getScene().materials;
  10578. for (var index = 0; index < materials.length; index++) {
  10579. if (materials[index].id === id) {
  10580. this.material = materials[index];
  10581. return;
  10582. }
  10583. }
  10584. // Multi
  10585. var multiMaterials = this.getScene().multiMaterials;
  10586. for (index = 0; index < multiMaterials.length; index++) {
  10587. if (multiMaterials[index].id === id) {
  10588. this.material = multiMaterials[index];
  10589. return;
  10590. }
  10591. }
  10592. };
  10593. Mesh.prototype.getAnimatables = function () {
  10594. var results = [];
  10595. if (this.material) {
  10596. results.push(this.material);
  10597. }
  10598. if (this.skeleton) {
  10599. results.push(this.skeleton);
  10600. }
  10601. return results;
  10602. };
  10603. // Geometry
  10604. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  10605. // Position
  10606. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  10607. return;
  10608. }
  10609. this._resetPointsArrayCache();
  10610. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10611. var temp = [];
  10612. for (var index = 0; index < data.length; index += 3) {
  10613. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10614. }
  10615. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  10616. // Normals
  10617. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  10618. return;
  10619. }
  10620. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10621. for (index = 0; index < data.length; index += 3) {
  10622. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10623. }
  10624. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  10625. };
  10626. // Cache
  10627. Mesh.prototype._resetPointsArrayCache = function () {
  10628. this._positions = null;
  10629. };
  10630. Mesh.prototype._generatePointsArray = function () {
  10631. if (this._positions)
  10632. return true;
  10633. this._positions = [];
  10634. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10635. if (!data) {
  10636. return false;
  10637. }
  10638. for (var index = 0; index < data.length; index += 3) {
  10639. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  10640. }
  10641. return true;
  10642. };
  10643. // Clone
  10644. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10645. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  10646. };
  10647. // Dispose
  10648. Mesh.prototype.dispose = function (doNotRecurse) {
  10649. if (this._geometry) {
  10650. this._geometry.releaseForMesh(this, true);
  10651. }
  10652. // Instances
  10653. if (this._worldMatricesInstancesBuffer) {
  10654. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10655. this._worldMatricesInstancesBuffer = null;
  10656. }
  10657. while (this.instances.length) {
  10658. this.instances[0].dispose();
  10659. }
  10660. _super.prototype.dispose.call(this, doNotRecurse);
  10661. };
  10662. // Geometric tools
  10663. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  10664. var _this = this;
  10665. var scene = this.getScene();
  10666. var onload = function (img) {
  10667. // Getting height map data
  10668. var canvas = document.createElement("canvas");
  10669. var context = canvas.getContext("2d");
  10670. var heightMapWidth = img.width;
  10671. var heightMapHeight = img.height;
  10672. canvas.width = heightMapWidth;
  10673. canvas.height = heightMapHeight;
  10674. context.drawImage(img, 0, 0);
  10675. // Create VertexData from map data
  10676. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10677. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  10678. //execute success callback, if set
  10679. if (onSuccess) {
  10680. onSuccess(_this);
  10681. }
  10682. };
  10683. BABYLON.Tools.LoadImage(url, onload, function () {
  10684. }, scene.database);
  10685. };
  10686. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  10687. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10688. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  10689. return;
  10690. }
  10691. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10692. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10693. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  10694. var position = BABYLON.Vector3.Zero();
  10695. var normal = BABYLON.Vector3.Zero();
  10696. var uv = BABYLON.Vector2.Zero();
  10697. for (var index = 0; index < positions.length; index += 3) {
  10698. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  10699. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  10700. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  10701. // Compute height
  10702. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  10703. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  10704. var pos = (u + v * heightMapWidth) * 4;
  10705. var r = buffer[pos] / 255.0;
  10706. var g = buffer[pos + 1] / 255.0;
  10707. var b = buffer[pos + 2] / 255.0;
  10708. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  10709. normal.normalize();
  10710. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  10711. position = position.add(normal);
  10712. position.toArray(positions, index);
  10713. }
  10714. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  10715. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  10716. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  10717. };
  10718. Mesh.prototype.convertToFlatShadedMesh = function () {
  10719. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  10720. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  10721. var kinds = this.getVerticesDataKinds();
  10722. var vbs = [];
  10723. var data = [];
  10724. var newdata = [];
  10725. var updatableNormals = false;
  10726. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10727. var kind = kinds[kindIndex];
  10728. var vertexBuffer = this.getVertexBuffer(kind);
  10729. if (kind === BABYLON.VertexBuffer.NormalKind) {
  10730. updatableNormals = vertexBuffer.isUpdatable();
  10731. kinds.splice(kindIndex, 1);
  10732. kindIndex--;
  10733. continue;
  10734. }
  10735. vbs[kind] = vertexBuffer;
  10736. data[kind] = vbs[kind].getData();
  10737. newdata[kind] = [];
  10738. }
  10739. // Save previous submeshes
  10740. var previousSubmeshes = this.subMeshes.slice(0);
  10741. var indices = this.getIndices();
  10742. var totalIndices = this.getTotalIndices();
  10743. for (var index = 0; index < totalIndices; index++) {
  10744. var vertexIndex = indices[index];
  10745. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10746. kind = kinds[kindIndex];
  10747. var stride = vbs[kind].getStrideSize();
  10748. for (var offset = 0; offset < stride; offset++) {
  10749. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  10750. }
  10751. }
  10752. }
  10753. // Updating faces & normal
  10754. var normals = [];
  10755. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  10756. for (index = 0; index < totalIndices; index += 3) {
  10757. indices[index] = index;
  10758. indices[index + 1] = index + 1;
  10759. indices[index + 2] = index + 2;
  10760. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  10761. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  10762. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  10763. var p1p2 = p1.subtract(p2);
  10764. var p3p2 = p3.subtract(p2);
  10765. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  10766. for (var localIndex = 0; localIndex < 3; localIndex++) {
  10767. normals.push(normal.x);
  10768. normals.push(normal.y);
  10769. normals.push(normal.z);
  10770. }
  10771. }
  10772. this.setIndices(indices);
  10773. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  10774. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10775. kind = kinds[kindIndex];
  10776. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  10777. }
  10778. // Updating submeshes
  10779. this.releaseSubMeshes();
  10780. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  10781. var previousOne = previousSubmeshes[submeshIndex];
  10782. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  10783. }
  10784. this.synchronizeInstances();
  10785. };
  10786. // Instances
  10787. Mesh.prototype.createInstance = function (name) {
  10788. return new BABYLON.InstancedMesh(name, this);
  10789. };
  10790. Mesh.prototype.synchronizeInstances = function () {
  10791. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  10792. var instance = this.instances[instanceIndex];
  10793. instance._syncSubMeshes();
  10794. }
  10795. };
  10796. /**
  10797. * Simplify the mesh according to the given array of settings.
  10798. * Function will return immediately and will simplify async.
  10799. * @param settings a collection of simplification settings.
  10800. * @param parallelProcessing should all levels calculate parallel or one after the other.
  10801. * @param type the type of simplification to run.
  10802. * successCallback optional success callback to be called after the simplification finished processing all settings.
  10803. */
  10804. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  10805. var _this = this;
  10806. if (parallelProcessing === void 0) { parallelProcessing = true; }
  10807. if (type === void 0) { type = 0 /* QUADRATIC */; }
  10808. var getSimplifier = function () {
  10809. switch (type) {
  10810. case 0 /* QUADRATIC */:
  10811. default:
  10812. return new BABYLON.QuadraticErrorSimplification(_this);
  10813. }
  10814. };
  10815. if (parallelProcessing) {
  10816. //parallel simplifier
  10817. settings.forEach(function (setting) {
  10818. var simplifier = getSimplifier();
  10819. simplifier.simplify(setting, function (newMesh) {
  10820. _this.addLODLevel(setting.distance, newMesh);
  10821. //check if it is the last
  10822. if (setting.quality === settings[settings.length - 1].quality && successCallback) {
  10823. //all done, run the success callback.
  10824. successCallback();
  10825. }
  10826. });
  10827. });
  10828. }
  10829. else {
  10830. //single simplifier.
  10831. var simplifier = getSimplifier();
  10832. var runDecimation = function (setting, callback) {
  10833. simplifier.simplify(setting, function (newMesh) {
  10834. _this.addLODLevel(setting.distance, newMesh);
  10835. //run the next quality level
  10836. callback();
  10837. });
  10838. };
  10839. BABYLON.AsyncLoop.Run(settings.length, function (loop) {
  10840. runDecimation(settings[loop.index], function () {
  10841. loop.executeNext();
  10842. });
  10843. }, function () {
  10844. //execution ended, run the success callback.
  10845. if (successCallback) {
  10846. successCallback();
  10847. }
  10848. });
  10849. }
  10850. };
  10851. // Statics
  10852. Mesh.CreateBox = function (name, size, scene, updatable) {
  10853. var box = new Mesh(name, scene);
  10854. var vertexData = BABYLON.VertexData.CreateBox(size);
  10855. vertexData.applyToMesh(box, updatable);
  10856. return box;
  10857. };
  10858. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  10859. var sphere = new Mesh(name, scene);
  10860. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  10861. vertexData.applyToMesh(sphere, updatable);
  10862. return sphere;
  10863. };
  10864. // Cylinder and cone (Code inspired by SharpDX.org)
  10865. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  10866. // subdivisions is a new parameter, we need to support old signature
  10867. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  10868. if (scene !== undefined) {
  10869. updatable = scene;
  10870. }
  10871. scene = subdivisions;
  10872. subdivisions = 1;
  10873. }
  10874. var cylinder = new Mesh(name, scene);
  10875. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  10876. vertexData.applyToMesh(cylinder, updatable);
  10877. return cylinder;
  10878. };
  10879. // Torus (Code from SharpDX.org)
  10880. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  10881. var torus = new Mesh(name, scene);
  10882. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  10883. vertexData.applyToMesh(torus, updatable);
  10884. return torus;
  10885. };
  10886. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  10887. var torusKnot = new Mesh(name, scene);
  10888. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  10889. vertexData.applyToMesh(torusKnot, updatable);
  10890. return torusKnot;
  10891. };
  10892. // Lines
  10893. Mesh.CreateLines = function (name, points, scene, updatable) {
  10894. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  10895. var vertexData = BABYLON.VertexData.CreateLines(points);
  10896. vertexData.applyToMesh(lines, updatable);
  10897. return lines;
  10898. };
  10899. // Plane & ground
  10900. Mesh.CreatePlane = function (name, size, scene, updatable) {
  10901. var plane = new Mesh(name, scene);
  10902. var vertexData = BABYLON.VertexData.CreatePlane(size);
  10903. vertexData.applyToMesh(plane, updatable);
  10904. return plane;
  10905. };
  10906. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  10907. var ground = new BABYLON.GroundMesh(name, scene);
  10908. ground._setReady(false);
  10909. ground._subdivisions = subdivisions;
  10910. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  10911. vertexData.applyToMesh(ground, updatable);
  10912. ground._setReady(true);
  10913. return ground;
  10914. };
  10915. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  10916. var tiledGround = new Mesh(name, scene);
  10917. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  10918. vertexData.applyToMesh(tiledGround, updatable);
  10919. return tiledGround;
  10920. };
  10921. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  10922. var ground = new BABYLON.GroundMesh(name, scene);
  10923. ground._subdivisions = subdivisions;
  10924. ground._setReady(false);
  10925. var onload = function (img) {
  10926. // Getting height map data
  10927. var canvas = document.createElement("canvas");
  10928. var context = canvas.getContext("2d");
  10929. var heightMapWidth = img.width;
  10930. var heightMapHeight = img.height;
  10931. canvas.width = heightMapWidth;
  10932. canvas.height = heightMapHeight;
  10933. context.drawImage(img, 0, 0);
  10934. // Create VertexData from map data
  10935. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10936. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  10937. vertexData.applyToMesh(ground, updatable);
  10938. ground._setReady(true);
  10939. //execute ready callback, if set
  10940. if (onReady) {
  10941. onReady(ground);
  10942. }
  10943. };
  10944. BABYLON.Tools.LoadImage(url, onload, function () {
  10945. }, scene.database);
  10946. return ground;
  10947. };
  10948. // Tools
  10949. Mesh.MinMax = function (meshes) {
  10950. var minVector = null;
  10951. var maxVector = null;
  10952. for (var i in meshes) {
  10953. var mesh = meshes[i];
  10954. var boundingBox = mesh.getBoundingInfo().boundingBox;
  10955. if (!minVector) {
  10956. minVector = boundingBox.minimumWorld;
  10957. maxVector = boundingBox.maximumWorld;
  10958. continue;
  10959. }
  10960. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  10961. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  10962. }
  10963. return {
  10964. min: minVector,
  10965. max: maxVector
  10966. };
  10967. };
  10968. Mesh.Center = function (meshesOrMinMaxVector) {
  10969. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  10970. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  10971. };
  10972. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  10973. if (disposeSource === void 0) { disposeSource = true; }
  10974. var source = meshes[0];
  10975. var material = source.material;
  10976. var scene = source.getScene();
  10977. if (!allow32BitsIndices) {
  10978. var totalVertices = 0;
  10979. for (var index = 0; index < meshes.length; index++) {
  10980. totalVertices += meshes[index].getTotalVertices();
  10981. if (totalVertices > 65536) {
  10982. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  10983. return null;
  10984. }
  10985. }
  10986. }
  10987. // Merge
  10988. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  10989. vertexData.transform(source.getWorldMatrix());
  10990. for (index = 1; index < meshes.length; index++) {
  10991. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  10992. otherVertexData.transform(meshes[index].getWorldMatrix());
  10993. vertexData.merge(otherVertexData);
  10994. }
  10995. var newMesh = new Mesh(source.name + "_merged", scene);
  10996. vertexData.applyToMesh(newMesh);
  10997. // Setting properties
  10998. newMesh.material = material;
  10999. newMesh.checkCollisions = source.checkCollisions;
  11000. // Cleaning
  11001. if (disposeSource) {
  11002. for (index = 0; index < meshes.length; index++) {
  11003. meshes[index].dispose();
  11004. }
  11005. }
  11006. return newMesh;
  11007. };
  11008. return Mesh;
  11009. })(BABYLON.AbstractMesh);
  11010. BABYLON.Mesh = Mesh;
  11011. })(BABYLON || (BABYLON = {}));
  11012. //# sourceMappingURL=babylon.mesh.js.map
  11013. var BABYLON;
  11014. (function (BABYLON) {
  11015. var GroundMesh = (function (_super) {
  11016. __extends(GroundMesh, _super);
  11017. function GroundMesh(name, scene) {
  11018. _super.call(this, name, scene);
  11019. this.generateOctree = false;
  11020. this._worldInverse = new BABYLON.Matrix();
  11021. }
  11022. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  11023. get: function () {
  11024. return this._subdivisions;
  11025. },
  11026. enumerable: true,
  11027. configurable: true
  11028. });
  11029. GroundMesh.prototype.optimize = function (chunksCount) {
  11030. this.subdivide(this._subdivisions);
  11031. this.createOrUpdateSubmeshesOctree(32);
  11032. };
  11033. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  11034. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  11035. this.getWorldMatrix().invertToRef(this._worldInverse);
  11036. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  11037. var pickInfo = this.intersects(ray);
  11038. if (pickInfo.hit) {
  11039. return pickInfo.pickedPoint.y;
  11040. }
  11041. return 0;
  11042. };
  11043. return GroundMesh;
  11044. })(BABYLON.Mesh);
  11045. BABYLON.GroundMesh = GroundMesh;
  11046. })(BABYLON || (BABYLON = {}));
  11047. //# sourceMappingURL=babylon.groundMesh.js.map
  11048. var BABYLON;
  11049. (function (BABYLON) {
  11050. /**
  11051. * Creates an instance based on a source mesh.
  11052. */
  11053. var InstancedMesh = (function (_super) {
  11054. __extends(InstancedMesh, _super);
  11055. function InstancedMesh(name, source) {
  11056. _super.call(this, name, source.getScene());
  11057. source.instances.push(this);
  11058. this._sourceMesh = source;
  11059. this.position.copyFrom(source.position);
  11060. this.rotation.copyFrom(source.rotation);
  11061. this.scaling.copyFrom(source.scaling);
  11062. if (source.rotationQuaternion) {
  11063. this.rotationQuaternion = source.rotationQuaternion.clone();
  11064. }
  11065. this.infiniteDistance = source.infiniteDistance;
  11066. this.setPivotMatrix(source.getPivotMatrix());
  11067. this.refreshBoundingInfo();
  11068. this._syncSubMeshes();
  11069. }
  11070. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  11071. // Methods
  11072. get: function () {
  11073. return this._sourceMesh.receiveShadows;
  11074. },
  11075. enumerable: true,
  11076. configurable: true
  11077. });
  11078. Object.defineProperty(InstancedMesh.prototype, "material", {
  11079. get: function () {
  11080. return this._sourceMesh.material;
  11081. },
  11082. enumerable: true,
  11083. configurable: true
  11084. });
  11085. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  11086. get: function () {
  11087. return this._sourceMesh.visibility;
  11088. },
  11089. enumerable: true,
  11090. configurable: true
  11091. });
  11092. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  11093. get: function () {
  11094. return this._sourceMesh.skeleton;
  11095. },
  11096. enumerable: true,
  11097. configurable: true
  11098. });
  11099. InstancedMesh.prototype.getTotalVertices = function () {
  11100. return this._sourceMesh.getTotalVertices();
  11101. };
  11102. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  11103. get: function () {
  11104. return this._sourceMesh;
  11105. },
  11106. enumerable: true,
  11107. configurable: true
  11108. });
  11109. InstancedMesh.prototype.getVerticesData = function (kind) {
  11110. return this._sourceMesh.getVerticesData(kind);
  11111. };
  11112. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  11113. return this._sourceMesh.isVerticesDataPresent(kind);
  11114. };
  11115. InstancedMesh.prototype.getIndices = function () {
  11116. return this._sourceMesh.getIndices();
  11117. };
  11118. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  11119. get: function () {
  11120. return this._sourceMesh._positions;
  11121. },
  11122. enumerable: true,
  11123. configurable: true
  11124. });
  11125. InstancedMesh.prototype.refreshBoundingInfo = function () {
  11126. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11127. if (data) {
  11128. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  11129. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11130. }
  11131. this._updateBoundingInfo();
  11132. };
  11133. InstancedMesh.prototype._preActivate = function () {
  11134. if (this._currentLOD) {
  11135. this._currentLOD._preActivate();
  11136. }
  11137. };
  11138. InstancedMesh.prototype._activate = function (renderId) {
  11139. if (this._currentLOD) {
  11140. this._currentLOD._registerInstanceForRenderId(this, renderId);
  11141. }
  11142. };
  11143. InstancedMesh.prototype.getLOD = function (camera) {
  11144. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  11145. if (this._currentLOD === this.sourceMesh) {
  11146. return this;
  11147. }
  11148. return this._currentLOD;
  11149. };
  11150. InstancedMesh.prototype._syncSubMeshes = function () {
  11151. this.releaseSubMeshes();
  11152. if (this._sourceMesh.subMeshes) {
  11153. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  11154. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  11155. }
  11156. }
  11157. };
  11158. InstancedMesh.prototype._generatePointsArray = function () {
  11159. return this._sourceMesh._generatePointsArray();
  11160. };
  11161. // Clone
  11162. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11163. var result = this._sourceMesh.createInstance(name);
  11164. // Deep copy
  11165. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  11166. // Bounding info
  11167. this.refreshBoundingInfo();
  11168. // Parent
  11169. if (newParent) {
  11170. result.parent = newParent;
  11171. }
  11172. if (!doNotCloneChildren) {
  11173. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11174. var mesh = this.getScene().meshes[index];
  11175. if (mesh.parent === this) {
  11176. mesh.clone(mesh.name, result);
  11177. }
  11178. }
  11179. }
  11180. result.computeWorldMatrix(true);
  11181. return result;
  11182. };
  11183. // Dispoe
  11184. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  11185. // Remove from mesh
  11186. var index = this._sourceMesh.instances.indexOf(this);
  11187. this._sourceMesh.instances.splice(index, 1);
  11188. _super.prototype.dispose.call(this, doNotRecurse);
  11189. };
  11190. return InstancedMesh;
  11191. })(BABYLON.AbstractMesh);
  11192. BABYLON.InstancedMesh = InstancedMesh;
  11193. })(BABYLON || (BABYLON = {}));
  11194. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  11195. (function (BABYLON) {
  11196. var SubMesh = (function () {
  11197. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  11198. if (createBoundingBox === void 0) { createBoundingBox = true; }
  11199. this.materialIndex = materialIndex;
  11200. this.verticesStart = verticesStart;
  11201. this.verticesCount = verticesCount;
  11202. this.indexStart = indexStart;
  11203. this.indexCount = indexCount;
  11204. this._renderId = 0;
  11205. this._mesh = mesh;
  11206. this._renderingMesh = renderingMesh || mesh;
  11207. mesh.subMeshes.push(this);
  11208. this._id = mesh.subMeshes.length - 1;
  11209. if (createBoundingBox) {
  11210. this.refreshBoundingInfo();
  11211. }
  11212. }
  11213. SubMesh.prototype.getBoundingInfo = function () {
  11214. return this._boundingInfo;
  11215. };
  11216. SubMesh.prototype.getMesh = function () {
  11217. return this._mesh;
  11218. };
  11219. SubMesh.prototype.getRenderingMesh = function () {
  11220. return this._renderingMesh;
  11221. };
  11222. SubMesh.prototype.getMaterial = function () {
  11223. var rootMaterial = this._renderingMesh.material;
  11224. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  11225. var multiMaterial = rootMaterial;
  11226. return multiMaterial.getSubMaterial(this.materialIndex);
  11227. }
  11228. if (!rootMaterial) {
  11229. return this._mesh.getScene().defaultMaterial;
  11230. }
  11231. return rootMaterial;
  11232. };
  11233. // Methods
  11234. SubMesh.prototype.refreshBoundingInfo = function () {
  11235. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11236. if (!data) {
  11237. this._boundingInfo = this._mesh._boundingInfo;
  11238. return;
  11239. }
  11240. var indices = this._renderingMesh.getIndices();
  11241. var extend;
  11242. if (this.indexStart === 0 && this.indexCount === indices.length) {
  11243. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  11244. }
  11245. else {
  11246. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  11247. }
  11248. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11249. };
  11250. SubMesh.prototype._checkCollision = function (collider) {
  11251. return this._boundingInfo._checkCollision(collider);
  11252. };
  11253. SubMesh.prototype.updateBoundingInfo = function (world) {
  11254. if (!this._boundingInfo) {
  11255. this.refreshBoundingInfo();
  11256. }
  11257. this._boundingInfo._update(world);
  11258. };
  11259. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  11260. return this._boundingInfo.isInFrustum(frustumPlanes);
  11261. };
  11262. SubMesh.prototype.render = function () {
  11263. this._renderingMesh.render(this);
  11264. };
  11265. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  11266. if (!this._linesIndexBuffer) {
  11267. var linesIndices = [];
  11268. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11269. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  11270. }
  11271. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  11272. this.linesIndexCount = linesIndices.length;
  11273. }
  11274. return this._linesIndexBuffer;
  11275. };
  11276. SubMesh.prototype.canIntersects = function (ray) {
  11277. return ray.intersectsBox(this._boundingInfo.boundingBox);
  11278. };
  11279. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  11280. var intersectInfo = null;
  11281. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11282. var p0 = positions[indices[index]];
  11283. var p1 = positions[indices[index + 1]];
  11284. var p2 = positions[indices[index + 2]];
  11285. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  11286. if (currentIntersectInfo) {
  11287. if (currentIntersectInfo.distance < 0) {
  11288. continue;
  11289. }
  11290. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11291. intersectInfo = currentIntersectInfo;
  11292. intersectInfo.faceId = index / 3;
  11293. if (fastCheck) {
  11294. break;
  11295. }
  11296. }
  11297. }
  11298. }
  11299. return intersectInfo;
  11300. };
  11301. // Clone
  11302. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  11303. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  11304. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  11305. return result;
  11306. };
  11307. // Dispose
  11308. SubMesh.prototype.dispose = function () {
  11309. if (this._linesIndexBuffer) {
  11310. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  11311. this._linesIndexBuffer = null;
  11312. }
  11313. // Remove from mesh
  11314. var index = this._mesh.subMeshes.indexOf(this);
  11315. this._mesh.subMeshes.splice(index, 1);
  11316. };
  11317. // Statics
  11318. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  11319. var minVertexIndex = Number.MAX_VALUE;
  11320. var maxVertexIndex = -Number.MAX_VALUE;
  11321. renderingMesh = renderingMesh || mesh;
  11322. var indices = renderingMesh.getIndices();
  11323. for (var index = startIndex; index < startIndex + indexCount; index++) {
  11324. var vertexIndex = indices[index];
  11325. if (vertexIndex < minVertexIndex)
  11326. minVertexIndex = vertexIndex;
  11327. if (vertexIndex > maxVertexIndex)
  11328. maxVertexIndex = vertexIndex;
  11329. }
  11330. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  11331. };
  11332. return SubMesh;
  11333. })();
  11334. BABYLON.SubMesh = SubMesh;
  11335. })(BABYLON || (BABYLON = {}));
  11336. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  11337. (function (BABYLON) {
  11338. var BaseTexture = (function () {
  11339. function BaseTexture(scene) {
  11340. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  11341. this.hasAlpha = false;
  11342. this.getAlphaFromRGB = false;
  11343. this.level = 1;
  11344. this.isCube = false;
  11345. this.isRenderTarget = false;
  11346. this.animations = new Array();
  11347. this.coordinatesIndex = 0;
  11348. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  11349. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11350. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11351. this.anisotropicFilteringLevel = 4;
  11352. this._scene = scene;
  11353. this._scene.textures.push(this);
  11354. }
  11355. BaseTexture.prototype.getScene = function () {
  11356. return this._scene;
  11357. };
  11358. BaseTexture.prototype.getTextureMatrix = function () {
  11359. return null;
  11360. };
  11361. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  11362. return null;
  11363. };
  11364. BaseTexture.prototype.getInternalTexture = function () {
  11365. return this._texture;
  11366. };
  11367. BaseTexture.prototype.isReady = function () {
  11368. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11369. return true;
  11370. }
  11371. if (this._texture) {
  11372. return this._texture.isReady;
  11373. }
  11374. return false;
  11375. };
  11376. BaseTexture.prototype.getSize = function () {
  11377. if (this._texture._width) {
  11378. return { width: this._texture._width, height: this._texture._height };
  11379. }
  11380. if (this._texture._size) {
  11381. return { width: this._texture._size, height: this._texture._size };
  11382. }
  11383. return { width: 0, height: 0 };
  11384. };
  11385. BaseTexture.prototype.getBaseSize = function () {
  11386. if (!this.isReady())
  11387. return { width: 0, height: 0 };
  11388. if (this._texture._size) {
  11389. return { width: this._texture._size, height: this._texture._size };
  11390. }
  11391. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  11392. };
  11393. BaseTexture.prototype.scale = function (ratio) {
  11394. };
  11395. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  11396. get: function () {
  11397. return false;
  11398. },
  11399. enumerable: true,
  11400. configurable: true
  11401. });
  11402. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  11403. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11404. for (var index = 0; index < texturesCache.length; index++) {
  11405. var texturesCacheEntry = texturesCache[index];
  11406. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11407. texturesCache.splice(index, 1);
  11408. return;
  11409. }
  11410. }
  11411. };
  11412. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  11413. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11414. for (var index = 0; index < texturesCache.length; index++) {
  11415. var texturesCacheEntry = texturesCache[index];
  11416. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11417. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  11418. texturesCacheEntry.references++;
  11419. return texturesCacheEntry;
  11420. }
  11421. }
  11422. }
  11423. return null;
  11424. };
  11425. BaseTexture.prototype.delayLoad = function () {
  11426. };
  11427. BaseTexture.prototype.releaseInternalTexture = function () {
  11428. if (!this._texture) {
  11429. return;
  11430. }
  11431. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11432. this._texture.references--;
  11433. // Final reference ?
  11434. if (this._texture.references === 0) {
  11435. var index = texturesCache.indexOf(this._texture);
  11436. texturesCache.splice(index, 1);
  11437. this._scene.getEngine()._releaseTexture(this._texture);
  11438. delete this._texture;
  11439. }
  11440. };
  11441. BaseTexture.prototype.clone = function () {
  11442. return null;
  11443. };
  11444. BaseTexture.prototype.dispose = function () {
  11445. // Remove from scene
  11446. var index = this._scene.textures.indexOf(this);
  11447. if (index >= 0) {
  11448. this._scene.textures.splice(index, 1);
  11449. }
  11450. if (this._texture === undefined) {
  11451. return;
  11452. }
  11453. this.releaseInternalTexture();
  11454. // Callback
  11455. if (this.onDispose) {
  11456. this.onDispose();
  11457. }
  11458. };
  11459. return BaseTexture;
  11460. })();
  11461. BABYLON.BaseTexture = BaseTexture;
  11462. })(BABYLON || (BABYLON = {}));
  11463. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  11464. (function (BABYLON) {
  11465. var RenderingGroup = (function () {
  11466. function RenderingGroup(index, scene) {
  11467. this.index = index;
  11468. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11469. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11470. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11471. this._scene = scene;
  11472. }
  11473. RenderingGroup.prototype.render = function (customRenderFunction) {
  11474. if (customRenderFunction) {
  11475. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11476. return true;
  11477. }
  11478. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11479. return false;
  11480. }
  11481. var engine = this._scene.getEngine();
  11482. // Opaque
  11483. var subIndex;
  11484. var submesh;
  11485. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11486. submesh = this._opaqueSubMeshes.data[subIndex];
  11487. submesh.render();
  11488. }
  11489. // Alpha test
  11490. engine.setAlphaTesting(true);
  11491. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11492. submesh = this._alphaTestSubMeshes.data[subIndex];
  11493. submesh.render();
  11494. }
  11495. engine.setAlphaTesting(false);
  11496. // Transparent
  11497. if (this._transparentSubMeshes.length) {
  11498. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11499. submesh = this._transparentSubMeshes.data[subIndex];
  11500. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11501. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11502. }
  11503. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11504. sortedArray.sort(function (a, b) {
  11505. // Alpha index first
  11506. if (a._alphaIndex > b._alphaIndex) {
  11507. return 1;
  11508. }
  11509. if (a._alphaIndex < b._alphaIndex) {
  11510. return -1;
  11511. }
  11512. // Then distance to camera
  11513. if (a._distanceToCamera < b._distanceToCamera) {
  11514. return 1;
  11515. }
  11516. if (a._distanceToCamera > b._distanceToCamera) {
  11517. return -1;
  11518. }
  11519. return 0;
  11520. });
  11521. // Rendering
  11522. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11523. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11524. submesh = sortedArray[subIndex];
  11525. submesh.render();
  11526. }
  11527. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11528. }
  11529. return true;
  11530. };
  11531. RenderingGroup.prototype.prepare = function () {
  11532. this._opaqueSubMeshes.reset();
  11533. this._transparentSubMeshes.reset();
  11534. this._alphaTestSubMeshes.reset();
  11535. };
  11536. RenderingGroup.prototype.dispatch = function (subMesh) {
  11537. var material = subMesh.getMaterial();
  11538. var mesh = subMesh.getMesh();
  11539. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11540. this._transparentSubMeshes.push(subMesh);
  11541. }
  11542. else if (material.needAlphaTesting()) {
  11543. this._alphaTestSubMeshes.push(subMesh);
  11544. }
  11545. else {
  11546. this._opaqueSubMeshes.push(subMesh); // Opaque
  11547. }
  11548. };
  11549. return RenderingGroup;
  11550. })();
  11551. BABYLON.RenderingGroup = RenderingGroup;
  11552. })(BABYLON || (BABYLON = {}));
  11553. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  11554. (function (BABYLON) {
  11555. var RenderingManager = (function () {
  11556. function RenderingManager(scene) {
  11557. this._renderingGroups = new Array();
  11558. this._scene = scene;
  11559. }
  11560. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11561. if (this._scene._activeParticleSystems.length === 0) {
  11562. return;
  11563. }
  11564. // Particles
  11565. var beforeParticlesDate = BABYLON.Tools.Now;
  11566. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11567. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11568. if (particleSystem.renderingGroupId !== index) {
  11569. continue;
  11570. }
  11571. this._clearDepthBuffer();
  11572. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11573. this._scene._activeParticles += particleSystem.render();
  11574. }
  11575. }
  11576. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11577. };
  11578. RenderingManager.prototype._renderSprites = function (index) {
  11579. if (this._scene.spriteManagers.length === 0) {
  11580. return;
  11581. }
  11582. // Sprites
  11583. var beforeSpritessDate = BABYLON.Tools.Now;
  11584. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11585. var spriteManager = this._scene.spriteManagers[id];
  11586. if (spriteManager.renderingGroupId === index) {
  11587. this._clearDepthBuffer();
  11588. spriteManager.render();
  11589. }
  11590. }
  11591. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11592. };
  11593. RenderingManager.prototype._clearDepthBuffer = function () {
  11594. if (this._depthBufferAlreadyCleaned) {
  11595. return;
  11596. }
  11597. this._scene.getEngine().clear(0, false, true);
  11598. this._depthBufferAlreadyCleaned = true;
  11599. };
  11600. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11601. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11602. this._depthBufferAlreadyCleaned = false;
  11603. var renderingGroup = this._renderingGroups[index];
  11604. if (renderingGroup) {
  11605. this._clearDepthBuffer();
  11606. if (!renderingGroup.render(customRenderFunction)) {
  11607. this._renderingGroups.splice(index, 1);
  11608. }
  11609. }
  11610. if (renderSprites) {
  11611. this._renderSprites(index);
  11612. }
  11613. if (renderParticles) {
  11614. this._renderParticles(index, activeMeshes);
  11615. }
  11616. }
  11617. };
  11618. RenderingManager.prototype.reset = function () {
  11619. for (var index in this._renderingGroups) {
  11620. var renderingGroup = this._renderingGroups[index];
  11621. renderingGroup.prepare();
  11622. }
  11623. };
  11624. RenderingManager.prototype.dispatch = function (subMesh) {
  11625. var mesh = subMesh.getMesh();
  11626. var renderingGroupId = mesh.renderingGroupId || 0;
  11627. if (!this._renderingGroups[renderingGroupId]) {
  11628. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11629. }
  11630. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11631. };
  11632. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11633. return RenderingManager;
  11634. })();
  11635. BABYLON.RenderingManager = RenderingManager;
  11636. })(BABYLON || (BABYLON = {}));
  11637. //# sourceMappingURL=babylon.renderingManager.js.map
  11638. var BABYLON;
  11639. (function (BABYLON) {
  11640. var Texture = (function (_super) {
  11641. __extends(Texture, _super);
  11642. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  11643. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11644. if (onLoad === void 0) { onLoad = null; }
  11645. if (onError === void 0) { onError = null; }
  11646. if (buffer === void 0) { buffer = null; }
  11647. if (deleteBuffer === void 0) { deleteBuffer = false; }
  11648. _super.call(this, scene);
  11649. this.uOffset = 0;
  11650. this.vOffset = 0;
  11651. this.uScale = 1.0;
  11652. this.vScale = 1.0;
  11653. this.uAng = 0;
  11654. this.vAng = 0;
  11655. this.wAng = 0;
  11656. this.name = url;
  11657. this.url = url;
  11658. this._noMipmap = noMipmap;
  11659. this._invertY = invertY;
  11660. this._samplingMode = samplingMode;
  11661. this._buffer = buffer;
  11662. this._deleteBuffer = deleteBuffer;
  11663. if (!url) {
  11664. return;
  11665. }
  11666. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  11667. if (!this._texture) {
  11668. if (!scene.useDelayedTextureLoading) {
  11669. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  11670. if (deleteBuffer) {
  11671. delete this._buffer;
  11672. }
  11673. }
  11674. else {
  11675. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11676. }
  11677. }
  11678. }
  11679. Texture.prototype.delayLoad = function () {
  11680. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11681. return;
  11682. }
  11683. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11684. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  11685. if (!this._texture) {
  11686. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  11687. if (this._deleteBuffer) {
  11688. delete this._buffer;
  11689. }
  11690. }
  11691. };
  11692. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  11693. x -= this.uOffset + 0.5;
  11694. y -= this.vOffset + 0.5;
  11695. z -= 0.5;
  11696. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  11697. t.x *= this.uScale;
  11698. t.y *= this.vScale;
  11699. t.x += 0.5;
  11700. t.y += 0.5;
  11701. t.z += 0.5;
  11702. };
  11703. Texture.prototype.getTextureMatrix = function () {
  11704. 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) {
  11705. return this._cachedTextureMatrix;
  11706. }
  11707. this._cachedUOffset = this.uOffset;
  11708. this._cachedVOffset = this.vOffset;
  11709. this._cachedUScale = this.uScale;
  11710. this._cachedVScale = this.vScale;
  11711. this._cachedUAng = this.uAng;
  11712. this._cachedVAng = this.vAng;
  11713. this._cachedWAng = this.wAng;
  11714. if (!this._cachedTextureMatrix) {
  11715. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11716. this._rowGenerationMatrix = new BABYLON.Matrix();
  11717. this._t0 = BABYLON.Vector3.Zero();
  11718. this._t1 = BABYLON.Vector3.Zero();
  11719. this._t2 = BABYLON.Vector3.Zero();
  11720. }
  11721. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  11722. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  11723. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  11724. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  11725. this._t1.subtractInPlace(this._t0);
  11726. this._t2.subtractInPlace(this._t0);
  11727. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11728. this._cachedTextureMatrix.m[0] = this._t1.x;
  11729. this._cachedTextureMatrix.m[1] = this._t1.y;
  11730. this._cachedTextureMatrix.m[2] = this._t1.z;
  11731. this._cachedTextureMatrix.m[4] = this._t2.x;
  11732. this._cachedTextureMatrix.m[5] = this._t2.y;
  11733. this._cachedTextureMatrix.m[6] = this._t2.z;
  11734. this._cachedTextureMatrix.m[8] = this._t0.x;
  11735. this._cachedTextureMatrix.m[9] = this._t0.y;
  11736. this._cachedTextureMatrix.m[10] = this._t0.z;
  11737. return this._cachedTextureMatrix;
  11738. };
  11739. Texture.prototype.getReflectionTextureMatrix = function () {
  11740. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  11741. return this._cachedTextureMatrix;
  11742. }
  11743. if (!this._cachedTextureMatrix) {
  11744. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11745. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  11746. }
  11747. this._cachedCoordinatesMode = this.coordinatesMode;
  11748. switch (this.coordinatesMode) {
  11749. case BABYLON.Texture.SPHERICAL_MODE:
  11750. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11751. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  11752. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  11753. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  11754. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  11755. break;
  11756. case BABYLON.Texture.PLANAR_MODE:
  11757. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11758. this._cachedTextureMatrix[0] = this.uScale;
  11759. this._cachedTextureMatrix[5] = this.vScale;
  11760. this._cachedTextureMatrix[12] = this.uOffset;
  11761. this._cachedTextureMatrix[13] = this.vOffset;
  11762. break;
  11763. case BABYLON.Texture.PROJECTION_MODE:
  11764. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  11765. this._projectionModeMatrix.m[0] = 0.5;
  11766. this._projectionModeMatrix.m[5] = -0.5;
  11767. this._projectionModeMatrix.m[10] = 0.0;
  11768. this._projectionModeMatrix.m[12] = 0.5;
  11769. this._projectionModeMatrix.m[13] = 0.5;
  11770. this._projectionModeMatrix.m[14] = 1.0;
  11771. this._projectionModeMatrix.m[15] = 1.0;
  11772. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  11773. break;
  11774. default:
  11775. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11776. break;
  11777. }
  11778. return this._cachedTextureMatrix;
  11779. };
  11780. Texture.prototype.clone = function () {
  11781. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  11782. // Base texture
  11783. newTexture.hasAlpha = this.hasAlpha;
  11784. newTexture.level = this.level;
  11785. newTexture.wrapU = this.wrapU;
  11786. newTexture.wrapV = this.wrapV;
  11787. newTexture.coordinatesIndex = this.coordinatesIndex;
  11788. newTexture.coordinatesMode = this.coordinatesMode;
  11789. // Texture
  11790. newTexture.uOffset = this.uOffset;
  11791. newTexture.vOffset = this.vOffset;
  11792. newTexture.uScale = this.uScale;
  11793. newTexture.vScale = this.vScale;
  11794. newTexture.uAng = this.uAng;
  11795. newTexture.vAng = this.vAng;
  11796. newTexture.wAng = this.wAng;
  11797. return newTexture;
  11798. };
  11799. // Statics
  11800. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  11801. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11802. if (onLoad === void 0) { onLoad = null; }
  11803. if (onError === void 0) { onError = null; }
  11804. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  11805. };
  11806. // Constants
  11807. Texture.NEAREST_SAMPLINGMODE = 1;
  11808. Texture.BILINEAR_SAMPLINGMODE = 2;
  11809. Texture.TRILINEAR_SAMPLINGMODE = 3;
  11810. Texture.EXPLICIT_MODE = 0;
  11811. Texture.SPHERICAL_MODE = 1;
  11812. Texture.PLANAR_MODE = 2;
  11813. Texture.CUBIC_MODE = 3;
  11814. Texture.PROJECTION_MODE = 4;
  11815. Texture.SKYBOX_MODE = 5;
  11816. Texture.CLAMP_ADDRESSMODE = 0;
  11817. Texture.WRAP_ADDRESSMODE = 1;
  11818. Texture.MIRROR_ADDRESSMODE = 2;
  11819. return Texture;
  11820. })(BABYLON.BaseTexture);
  11821. BABYLON.Texture = Texture;
  11822. })(BABYLON || (BABYLON = {}));
  11823. //# sourceMappingURL=babylon.texture.js.map
  11824. var BABYLON;
  11825. (function (BABYLON) {
  11826. var CubeTexture = (function (_super) {
  11827. __extends(CubeTexture, _super);
  11828. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  11829. _super.call(this, scene);
  11830. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  11831. this.name = rootUrl;
  11832. this.url = rootUrl;
  11833. this._noMipmap = noMipmap;
  11834. this.hasAlpha = false;
  11835. this._texture = this._getFromCache(rootUrl, noMipmap);
  11836. if (!extensions) {
  11837. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  11838. }
  11839. this._extensions = extensions;
  11840. if (!this._texture) {
  11841. if (!scene.useDelayedTextureLoading) {
  11842. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  11843. }
  11844. else {
  11845. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11846. }
  11847. }
  11848. this.isCube = true;
  11849. this._textureMatrix = BABYLON.Matrix.Identity();
  11850. }
  11851. CubeTexture.prototype.clone = function () {
  11852. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  11853. // Base texture
  11854. newTexture.level = this.level;
  11855. newTexture.wrapU = this.wrapU;
  11856. newTexture.wrapV = this.wrapV;
  11857. newTexture.coordinatesIndex = this.coordinatesIndex;
  11858. newTexture.coordinatesMode = this.coordinatesMode;
  11859. return newTexture;
  11860. };
  11861. // Methods
  11862. CubeTexture.prototype.delayLoad = function () {
  11863. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11864. return;
  11865. }
  11866. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11867. this._texture = this._getFromCache(this.url, this._noMipmap);
  11868. if (!this._texture) {
  11869. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  11870. }
  11871. };
  11872. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  11873. return this._textureMatrix;
  11874. };
  11875. return CubeTexture;
  11876. })(BABYLON.BaseTexture);
  11877. BABYLON.CubeTexture = CubeTexture;
  11878. })(BABYLON || (BABYLON = {}));
  11879. //# sourceMappingURL=babylon.cubeTexture.js.map
  11880. var BABYLON;
  11881. (function (BABYLON) {
  11882. var RenderTargetTexture = (function (_super) {
  11883. __extends(RenderTargetTexture, _super);
  11884. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  11885. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  11886. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  11887. _super.call(this, null, scene, !generateMipMaps);
  11888. this.renderList = new Array();
  11889. this.renderParticles = true;
  11890. this.renderSprites = false;
  11891. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  11892. this._currentRefreshId = -1;
  11893. this._refreshRate = 1;
  11894. this.name = name;
  11895. this.isRenderTarget = true;
  11896. this._size = size;
  11897. this._generateMipMaps = generateMipMaps;
  11898. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  11899. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  11900. // Rendering groups
  11901. this._renderingManager = new BABYLON.RenderingManager(scene);
  11902. }
  11903. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  11904. this._currentRefreshId = -1;
  11905. };
  11906. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  11907. get: function () {
  11908. return this._refreshRate;
  11909. },
  11910. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11911. set: function (value) {
  11912. this._refreshRate = value;
  11913. this.resetRefreshCounter();
  11914. },
  11915. enumerable: true,
  11916. configurable: true
  11917. });
  11918. RenderTargetTexture.prototype._shouldRender = function () {
  11919. if (this._currentRefreshId === -1) {
  11920. this._currentRefreshId = 1;
  11921. return true;
  11922. }
  11923. if (this.refreshRate === this._currentRefreshId) {
  11924. this._currentRefreshId = 1;
  11925. return true;
  11926. }
  11927. this._currentRefreshId++;
  11928. return false;
  11929. };
  11930. RenderTargetTexture.prototype.isReady = function () {
  11931. if (!this.getScene().renderTargetsEnabled) {
  11932. return false;
  11933. }
  11934. return _super.prototype.isReady.call(this);
  11935. };
  11936. RenderTargetTexture.prototype.getRenderSize = function () {
  11937. return this._size;
  11938. };
  11939. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  11940. get: function () {
  11941. return true;
  11942. },
  11943. enumerable: true,
  11944. configurable: true
  11945. });
  11946. RenderTargetTexture.prototype.scale = function (ratio) {
  11947. var newSize = this._size * ratio;
  11948. this.resize(newSize, this._generateMipMaps);
  11949. };
  11950. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  11951. this.releaseInternalTexture();
  11952. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11953. };
  11954. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  11955. var scene = this.getScene();
  11956. var engine = scene.getEngine();
  11957. if (this._waitingRenderList) {
  11958. this.renderList = [];
  11959. for (var index = 0; index < this._waitingRenderList.length; index++) {
  11960. var id = this._waitingRenderList[index];
  11961. this.renderList.push(scene.getMeshByID(id));
  11962. }
  11963. delete this._waitingRenderList;
  11964. }
  11965. if (this.renderList && this.renderList.length === 0) {
  11966. return;
  11967. }
  11968. // Bind
  11969. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  11970. engine.bindFramebuffer(this._texture);
  11971. }
  11972. this._renderingManager.reset();
  11973. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  11974. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  11975. var mesh = currentRenderList[meshIndex];
  11976. if (mesh) {
  11977. if (!mesh.isReady()) {
  11978. // Reset _currentRefreshId
  11979. this.resetRefreshCounter();
  11980. continue;
  11981. }
  11982. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  11983. mesh._activate(scene.getRenderId());
  11984. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  11985. var subMesh = mesh.subMeshes[subIndex];
  11986. scene._activeVertices += subMesh.indexCount;
  11987. this._renderingManager.dispatch(subMesh);
  11988. }
  11989. }
  11990. }
  11991. }
  11992. if (this.onBeforeRender) {
  11993. this.onBeforeRender();
  11994. }
  11995. // Clear
  11996. engine.clear(scene.clearColor, true, true);
  11997. if (!this._doNotChangeAspectRatio) {
  11998. scene.updateTransformMatrix(true);
  11999. }
  12000. // Render
  12001. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  12002. if (useCameraPostProcess) {
  12003. scene.postProcessManager._finalizeFrame(false, this._texture);
  12004. }
  12005. if (!this._doNotChangeAspectRatio) {
  12006. scene.updateTransformMatrix(true);
  12007. }
  12008. if (this.onAfterRender) {
  12009. this.onAfterRender();
  12010. }
  12011. // Unbind
  12012. engine.unBindFramebuffer(this._texture);
  12013. };
  12014. RenderTargetTexture.prototype.clone = function () {
  12015. var textureSize = this.getSize();
  12016. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12017. // Base texture
  12018. newTexture.hasAlpha = this.hasAlpha;
  12019. newTexture.level = this.level;
  12020. // RenderTarget Texture
  12021. newTexture.coordinatesMode = this.coordinatesMode;
  12022. newTexture.renderList = this.renderList.slice(0);
  12023. return newTexture;
  12024. };
  12025. return RenderTargetTexture;
  12026. })(BABYLON.Texture);
  12027. BABYLON.RenderTargetTexture = RenderTargetTexture;
  12028. })(BABYLON || (BABYLON = {}));
  12029. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  12030. var BABYLON;
  12031. (function (BABYLON) {
  12032. var ProceduralTexture = (function (_super) {
  12033. __extends(ProceduralTexture, _super);
  12034. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  12035. if (generateMipMaps === void 0) { generateMipMaps = true; }
  12036. _super.call(this, null, scene, !generateMipMaps);
  12037. this._currentRefreshId = -1;
  12038. this._refreshRate = 1;
  12039. this._vertexDeclaration = [2];
  12040. this._vertexStrideSize = 2 * 4;
  12041. this._uniforms = new Array();
  12042. this._samplers = new Array();
  12043. this._textures = new Array();
  12044. this._floats = new Array();
  12045. this._floatsArrays = {};
  12046. this._colors3 = new Array();
  12047. this._colors4 = new Array();
  12048. this._vectors2 = new Array();
  12049. this._vectors3 = new Array();
  12050. this._matrices = new Array();
  12051. this._fallbackTextureUsed = false;
  12052. scene._proceduralTextures.push(this);
  12053. this.name = name;
  12054. this.isRenderTarget = true;
  12055. this._size = size;
  12056. this._generateMipMaps = generateMipMaps;
  12057. this.setFragment(fragment);
  12058. this._fallbackTexture = fallbackTexture;
  12059. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  12060. // VBO
  12061. var vertices = [];
  12062. vertices.push(1, 1);
  12063. vertices.push(-1, 1);
  12064. vertices.push(-1, -1);
  12065. vertices.push(1, -1);
  12066. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12067. // Indices
  12068. var indices = [];
  12069. indices.push(0);
  12070. indices.push(1);
  12071. indices.push(2);
  12072. indices.push(0);
  12073. indices.push(2);
  12074. indices.push(3);
  12075. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12076. }
  12077. ProceduralTexture.prototype.reset = function () {
  12078. if (this._effect === undefined) {
  12079. return;
  12080. }
  12081. var engine = this.getScene().getEngine();
  12082. engine._releaseEffect(this._effect);
  12083. };
  12084. ProceduralTexture.prototype.isReady = function () {
  12085. var _this = this;
  12086. var engine = this.getScene().getEngine();
  12087. var shaders;
  12088. if (!this._fragment) {
  12089. return false;
  12090. }
  12091. if (this._fallbackTextureUsed) {
  12092. return true;
  12093. }
  12094. if (this._fragment.fragmentElement !== undefined) {
  12095. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  12096. }
  12097. else {
  12098. shaders = { vertex: "procedural", fragment: this._fragment };
  12099. }
  12100. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  12101. _this.releaseInternalTexture();
  12102. if (_this._fallbackTexture) {
  12103. _this._texture = _this._fallbackTexture._texture;
  12104. _this._texture.references++;
  12105. }
  12106. _this._fallbackTextureUsed = true;
  12107. });
  12108. return this._effect.isReady();
  12109. };
  12110. ProceduralTexture.prototype.resetRefreshCounter = function () {
  12111. this._currentRefreshId = -1;
  12112. };
  12113. ProceduralTexture.prototype.setFragment = function (fragment) {
  12114. this._fragment = fragment;
  12115. };
  12116. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  12117. get: function () {
  12118. return this._refreshRate;
  12119. },
  12120. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12121. set: function (value) {
  12122. this._refreshRate = value;
  12123. this.resetRefreshCounter();
  12124. },
  12125. enumerable: true,
  12126. configurable: true
  12127. });
  12128. ProceduralTexture.prototype._shouldRender = function () {
  12129. if (!this.isReady() || !this._texture) {
  12130. return false;
  12131. }
  12132. if (this._fallbackTextureUsed) {
  12133. return false;
  12134. }
  12135. if (this._currentRefreshId === -1) {
  12136. this._currentRefreshId = 1;
  12137. return true;
  12138. }
  12139. if (this.refreshRate === this._currentRefreshId) {
  12140. this._currentRefreshId = 1;
  12141. return true;
  12142. }
  12143. this._currentRefreshId++;
  12144. return false;
  12145. };
  12146. ProceduralTexture.prototype.getRenderSize = function () {
  12147. return this._size;
  12148. };
  12149. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  12150. if (this._fallbackTextureUsed) {
  12151. return;
  12152. }
  12153. this.releaseInternalTexture();
  12154. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12155. };
  12156. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  12157. if (this._uniforms.indexOf(uniformName) === -1) {
  12158. this._uniforms.push(uniformName);
  12159. }
  12160. };
  12161. ProceduralTexture.prototype.setTexture = function (name, texture) {
  12162. if (this._samplers.indexOf(name) === -1) {
  12163. this._samplers.push(name);
  12164. }
  12165. this._textures[name] = texture;
  12166. return this;
  12167. };
  12168. ProceduralTexture.prototype.setFloat = function (name, value) {
  12169. this._checkUniform(name);
  12170. this._floats[name] = value;
  12171. return this;
  12172. };
  12173. ProceduralTexture.prototype.setFloats = function (name, value) {
  12174. this._checkUniform(name);
  12175. this._floatsArrays[name] = value;
  12176. return this;
  12177. };
  12178. ProceduralTexture.prototype.setColor3 = function (name, value) {
  12179. this._checkUniform(name);
  12180. this._colors3[name] = value;
  12181. return this;
  12182. };
  12183. ProceduralTexture.prototype.setColor4 = function (name, value) {
  12184. this._checkUniform(name);
  12185. this._colors4[name] = value;
  12186. return this;
  12187. };
  12188. ProceduralTexture.prototype.setVector2 = function (name, value) {
  12189. this._checkUniform(name);
  12190. this._vectors2[name] = value;
  12191. return this;
  12192. };
  12193. ProceduralTexture.prototype.setVector3 = function (name, value) {
  12194. this._checkUniform(name);
  12195. this._vectors3[name] = value;
  12196. return this;
  12197. };
  12198. ProceduralTexture.prototype.setMatrix = function (name, value) {
  12199. this._checkUniform(name);
  12200. this._matrices[name] = value;
  12201. return this;
  12202. };
  12203. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12204. var scene = this.getScene();
  12205. var engine = scene.getEngine();
  12206. engine.bindFramebuffer(this._texture);
  12207. // Clear
  12208. engine.clear(scene.clearColor, true, true);
  12209. // Render
  12210. engine.enableEffect(this._effect);
  12211. engine.setState(false);
  12212. for (var name in this._textures) {
  12213. this._effect.setTexture(name, this._textures[name]);
  12214. }
  12215. for (name in this._floats) {
  12216. this._effect.setFloat(name, this._floats[name]);
  12217. }
  12218. for (name in this._floatsArrays) {
  12219. this._effect.setArray(name, this._floatsArrays[name]);
  12220. }
  12221. for (name in this._colors3) {
  12222. this._effect.setColor3(name, this._colors3[name]);
  12223. }
  12224. for (name in this._colors4) {
  12225. var color = this._colors4[name];
  12226. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  12227. }
  12228. for (name in this._vectors2) {
  12229. this._effect.setVector2(name, this._vectors2[name]);
  12230. }
  12231. for (name in this._vectors3) {
  12232. this._effect.setVector3(name, this._vectors3[name]);
  12233. }
  12234. for (name in this._matrices) {
  12235. this._effect.setMatrix(name, this._matrices[name]);
  12236. }
  12237. // VBOs
  12238. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12239. // Draw order
  12240. engine.draw(true, 0, 6);
  12241. // Unbind
  12242. engine.unBindFramebuffer(this._texture);
  12243. };
  12244. ProceduralTexture.prototype.clone = function () {
  12245. var textureSize = this.getSize();
  12246. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  12247. // Base texture
  12248. newTexture.hasAlpha = this.hasAlpha;
  12249. newTexture.level = this.level;
  12250. // RenderTarget Texture
  12251. newTexture.coordinatesMode = this.coordinatesMode;
  12252. return newTexture;
  12253. };
  12254. ProceduralTexture.prototype.dispose = function () {
  12255. var index = this.getScene()._proceduralTextures.indexOf(this);
  12256. if (index >= 0) {
  12257. this.getScene()._proceduralTextures.splice(index, 1);
  12258. }
  12259. _super.prototype.dispose.call(this);
  12260. };
  12261. return ProceduralTexture;
  12262. })(BABYLON.Texture);
  12263. BABYLON.ProceduralTexture = ProceduralTexture;
  12264. })(BABYLON || (BABYLON = {}));
  12265. //# sourceMappingURL=babylon.proceduralTexture.js.map
  12266. var BABYLON;
  12267. (function (BABYLON) {
  12268. var WoodProceduralTexture = (function (_super) {
  12269. __extends(WoodProceduralTexture, _super);
  12270. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12271. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  12272. this._ampScale = 100.0;
  12273. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  12274. this.updateShaderUniforms();
  12275. this.refreshRate = 0;
  12276. }
  12277. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  12278. this.setFloat("ampScale", this._ampScale);
  12279. this.setColor3("woodColor", this._woodColor);
  12280. };
  12281. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  12282. get: function () {
  12283. return this._ampScale;
  12284. },
  12285. set: function (value) {
  12286. this._ampScale = value;
  12287. this.updateShaderUniforms();
  12288. },
  12289. enumerable: true,
  12290. configurable: true
  12291. });
  12292. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  12293. get: function () {
  12294. return this._woodColor;
  12295. },
  12296. set: function (value) {
  12297. this._woodColor = value;
  12298. this.updateShaderUniforms();
  12299. },
  12300. enumerable: true,
  12301. configurable: true
  12302. });
  12303. return WoodProceduralTexture;
  12304. })(BABYLON.ProceduralTexture);
  12305. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  12306. var FireProceduralTexture = (function (_super) {
  12307. __extends(FireProceduralTexture, _super);
  12308. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12309. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  12310. this._time = 0.0;
  12311. this._speed = new BABYLON.Vector2(0.5, 0.3);
  12312. this._shift = 1.6;
  12313. this._autoGenerateTime = true;
  12314. this._alphaThreshold = 0.5;
  12315. this._fireColors = FireProceduralTexture.RedFireColors;
  12316. this.updateShaderUniforms();
  12317. this.refreshRate = 1;
  12318. }
  12319. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  12320. this.setFloat("time", this._time);
  12321. this.setVector2("speed", this._speed);
  12322. this.setFloat("shift", this._shift);
  12323. this.setColor3("c1", this._fireColors[0]);
  12324. this.setColor3("c2", this._fireColors[1]);
  12325. this.setColor3("c3", this._fireColors[2]);
  12326. this.setColor3("c4", this._fireColors[3]);
  12327. this.setColor3("c5", this._fireColors[4]);
  12328. this.setColor3("c6", this._fireColors[5]);
  12329. this.setFloat("alphaThreshold", this._alphaThreshold);
  12330. };
  12331. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12332. if (this._autoGenerateTime) {
  12333. this._time += this.getScene().getAnimationRatio() * 0.03;
  12334. this.updateShaderUniforms();
  12335. }
  12336. _super.prototype.render.call(this, useCameraPostProcess);
  12337. };
  12338. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  12339. get: function () {
  12340. return [
  12341. new BABYLON.Color3(0.5, 0.0, 1.0),
  12342. new BABYLON.Color3(0.9, 0.0, 1.0),
  12343. new BABYLON.Color3(0.2, 0.0, 1.0),
  12344. new BABYLON.Color3(1.0, 0.9, 1.0),
  12345. new BABYLON.Color3(0.1, 0.1, 1.0),
  12346. new BABYLON.Color3(0.9, 0.9, 1.0)
  12347. ];
  12348. },
  12349. enumerable: true,
  12350. configurable: true
  12351. });
  12352. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  12353. get: function () {
  12354. return [
  12355. new BABYLON.Color3(0.5, 1.0, 0.0),
  12356. new BABYLON.Color3(0.5, 1.0, 0.0),
  12357. new BABYLON.Color3(0.3, 0.4, 0.0),
  12358. new BABYLON.Color3(0.5, 1.0, 0.0),
  12359. new BABYLON.Color3(0.2, 0.0, 0.0),
  12360. new BABYLON.Color3(0.5, 1.0, 0.0)
  12361. ];
  12362. },
  12363. enumerable: true,
  12364. configurable: true
  12365. });
  12366. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  12367. get: function () {
  12368. return [
  12369. new BABYLON.Color3(0.5, 0.0, 0.1),
  12370. new BABYLON.Color3(0.9, 0.0, 0.0),
  12371. new BABYLON.Color3(0.2, 0.0, 0.0),
  12372. new BABYLON.Color3(1.0, 0.9, 0.0),
  12373. new BABYLON.Color3(0.1, 0.1, 0.1),
  12374. new BABYLON.Color3(0.9, 0.9, 0.9)
  12375. ];
  12376. },
  12377. enumerable: true,
  12378. configurable: true
  12379. });
  12380. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  12381. get: function () {
  12382. return [
  12383. new BABYLON.Color3(0.1, 0.0, 0.5),
  12384. new BABYLON.Color3(0.0, 0.0, 0.5),
  12385. new BABYLON.Color3(0.1, 0.0, 0.2),
  12386. new BABYLON.Color3(0.0, 0.0, 1.0),
  12387. new BABYLON.Color3(0.1, 0.2, 0.3),
  12388. new BABYLON.Color3(0.0, 0.2, 0.9)
  12389. ];
  12390. },
  12391. enumerable: true,
  12392. configurable: true
  12393. });
  12394. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  12395. get: function () {
  12396. return this._fireColors;
  12397. },
  12398. set: function (value) {
  12399. this._fireColors = value;
  12400. this.updateShaderUniforms();
  12401. },
  12402. enumerable: true,
  12403. configurable: true
  12404. });
  12405. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  12406. get: function () {
  12407. return this._time;
  12408. },
  12409. set: function (value) {
  12410. this._time = value;
  12411. this.updateShaderUniforms();
  12412. },
  12413. enumerable: true,
  12414. configurable: true
  12415. });
  12416. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  12417. get: function () {
  12418. return this._speed;
  12419. },
  12420. set: function (value) {
  12421. this._speed = value;
  12422. this.updateShaderUniforms();
  12423. },
  12424. enumerable: true,
  12425. configurable: true
  12426. });
  12427. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  12428. get: function () {
  12429. return this._shift;
  12430. },
  12431. set: function (value) {
  12432. this._shift = value;
  12433. this.updateShaderUniforms();
  12434. },
  12435. enumerable: true,
  12436. configurable: true
  12437. });
  12438. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  12439. get: function () {
  12440. return this._alphaThreshold;
  12441. },
  12442. set: function (value) {
  12443. this._alphaThreshold = value;
  12444. this.updateShaderUniforms();
  12445. },
  12446. enumerable: true,
  12447. configurable: true
  12448. });
  12449. return FireProceduralTexture;
  12450. })(BABYLON.ProceduralTexture);
  12451. BABYLON.FireProceduralTexture = FireProceduralTexture;
  12452. var CloudProceduralTexture = (function (_super) {
  12453. __extends(CloudProceduralTexture, _super);
  12454. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12455. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  12456. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  12457. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  12458. this.updateShaderUniforms();
  12459. this.refreshRate = 0;
  12460. }
  12461. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  12462. this.setColor3("skyColor", this._skyColor);
  12463. this.setColor3("cloudColor", this._cloudColor);
  12464. };
  12465. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  12466. get: function () {
  12467. return this._skyColor;
  12468. },
  12469. set: function (value) {
  12470. this._skyColor = value;
  12471. this.updateShaderUniforms();
  12472. },
  12473. enumerable: true,
  12474. configurable: true
  12475. });
  12476. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  12477. get: function () {
  12478. return this._cloudColor;
  12479. },
  12480. set: function (value) {
  12481. this._cloudColor = value;
  12482. this.updateShaderUniforms();
  12483. },
  12484. enumerable: true,
  12485. configurable: true
  12486. });
  12487. return CloudProceduralTexture;
  12488. })(BABYLON.ProceduralTexture);
  12489. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  12490. var GrassProceduralTexture = (function (_super) {
  12491. __extends(GrassProceduralTexture, _super);
  12492. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12493. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  12494. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  12495. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  12496. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  12497. this._groundColor = new BABYLON.Color3(1, 1, 1);
  12498. this._grassColors = [
  12499. new BABYLON.Color3(0.29, 0.38, 0.02),
  12500. new BABYLON.Color3(0.36, 0.49, 0.09),
  12501. new BABYLON.Color3(0.51, 0.6, 0.28)
  12502. ];
  12503. this.updateShaderUniforms();
  12504. this.refreshRate = 0;
  12505. }
  12506. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  12507. this.setColor3("herb1Color", this._grassColors[0]);
  12508. this.setColor3("herb2Color", this._grassColors[1]);
  12509. this.setColor3("herb3Color", this._grassColors[2]);
  12510. this.setColor3("groundColor", this._groundColor);
  12511. };
  12512. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  12513. get: function () {
  12514. return this._grassColors;
  12515. },
  12516. set: function (value) {
  12517. this._grassColors = value;
  12518. this.updateShaderUniforms();
  12519. },
  12520. enumerable: true,
  12521. configurable: true
  12522. });
  12523. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  12524. get: function () {
  12525. return this._groundColor;
  12526. },
  12527. set: function (value) {
  12528. this.groundColor = value;
  12529. this.updateShaderUniforms();
  12530. },
  12531. enumerable: true,
  12532. configurable: true
  12533. });
  12534. return GrassProceduralTexture;
  12535. })(BABYLON.ProceduralTexture);
  12536. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  12537. var RoadProceduralTexture = (function (_super) {
  12538. __extends(RoadProceduralTexture, _super);
  12539. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12540. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  12541. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  12542. this.updateShaderUniforms();
  12543. this.refreshRate = 0;
  12544. }
  12545. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  12546. this.setColor3("roadColor", this._roadColor);
  12547. };
  12548. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  12549. get: function () {
  12550. return this._roadColor;
  12551. },
  12552. set: function (value) {
  12553. this._roadColor = value;
  12554. this.updateShaderUniforms();
  12555. },
  12556. enumerable: true,
  12557. configurable: true
  12558. });
  12559. return RoadProceduralTexture;
  12560. })(BABYLON.ProceduralTexture);
  12561. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  12562. var BrickProceduralTexture = (function (_super) {
  12563. __extends(BrickProceduralTexture, _super);
  12564. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12565. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  12566. this._numberOfBricksHeight = 15;
  12567. this._numberOfBricksWidth = 5;
  12568. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12569. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12570. this.updateShaderUniforms();
  12571. this.refreshRate = 0;
  12572. }
  12573. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  12574. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  12575. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  12576. this.setColor3("brickColor", this._brickColor);
  12577. this.setColor3("jointColor", this._jointColor);
  12578. };
  12579. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  12580. get: function () {
  12581. return this._numberOfBricksHeight;
  12582. },
  12583. enumerable: true,
  12584. configurable: true
  12585. });
  12586. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  12587. set: function (value) {
  12588. this._numberOfBricksHeight = value;
  12589. this.updateShaderUniforms();
  12590. },
  12591. enumerable: true,
  12592. configurable: true
  12593. });
  12594. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  12595. get: function () {
  12596. return this._numberOfBricksWidth;
  12597. },
  12598. set: function (value) {
  12599. this._numberOfBricksHeight = value;
  12600. this.updateShaderUniforms();
  12601. },
  12602. enumerable: true,
  12603. configurable: true
  12604. });
  12605. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  12606. get: function () {
  12607. return this._jointColor;
  12608. },
  12609. set: function (value) {
  12610. this._jointColor = value;
  12611. this.updateShaderUniforms();
  12612. },
  12613. enumerable: true,
  12614. configurable: true
  12615. });
  12616. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  12617. get: function () {
  12618. return this._brickColor;
  12619. },
  12620. set: function (value) {
  12621. this._brickColor = value;
  12622. this.updateShaderUniforms();
  12623. },
  12624. enumerable: true,
  12625. configurable: true
  12626. });
  12627. return BrickProceduralTexture;
  12628. })(BABYLON.ProceduralTexture);
  12629. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  12630. var MarbleProceduralTexture = (function (_super) {
  12631. __extends(MarbleProceduralTexture, _super);
  12632. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12633. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  12634. this._numberOfTilesHeight = 3;
  12635. this._numberOfTilesWidth = 3;
  12636. this._amplitude = 9.0;
  12637. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12638. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12639. this.updateShaderUniforms();
  12640. this.refreshRate = 0;
  12641. }
  12642. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  12643. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  12644. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  12645. this.setFloat("amplitude", this._amplitude);
  12646. this.setColor3("marbleColor", this._marbleColor);
  12647. this.setColor3("jointColor", this._jointColor);
  12648. };
  12649. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  12650. get: function () {
  12651. return this._numberOfTilesHeight;
  12652. },
  12653. set: function (value) {
  12654. this._numberOfTilesHeight = value;
  12655. this.updateShaderUniforms();
  12656. },
  12657. enumerable: true,
  12658. configurable: true
  12659. });
  12660. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  12661. get: function () {
  12662. return this._numberOfTilesWidth;
  12663. },
  12664. set: function (value) {
  12665. this._numberOfTilesWidth = value;
  12666. this.updateShaderUniforms();
  12667. },
  12668. enumerable: true,
  12669. configurable: true
  12670. });
  12671. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  12672. get: function () {
  12673. return this._jointColor;
  12674. },
  12675. set: function (value) {
  12676. this._jointColor = value;
  12677. this.updateShaderUniforms();
  12678. },
  12679. enumerable: true,
  12680. configurable: true
  12681. });
  12682. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  12683. get: function () {
  12684. return this._marbleColor;
  12685. },
  12686. set: function (value) {
  12687. this._marbleColor = value;
  12688. this.updateShaderUniforms();
  12689. },
  12690. enumerable: true,
  12691. configurable: true
  12692. });
  12693. return MarbleProceduralTexture;
  12694. })(BABYLON.ProceduralTexture);
  12695. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  12696. })(BABYLON || (BABYLON = {}));
  12697. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  12698. var BABYLON;
  12699. (function (BABYLON) {
  12700. var CustomProceduralTexture = (function (_super) {
  12701. __extends(CustomProceduralTexture, _super);
  12702. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  12703. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  12704. this._animate = true;
  12705. this._time = 0;
  12706. this._texturePath = texturePath;
  12707. //Try to load json
  12708. this.loadJson(texturePath);
  12709. this.refreshRate = 1;
  12710. }
  12711. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  12712. var _this = this;
  12713. var that = this;
  12714. function noConfigFile() {
  12715. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  12716. try {
  12717. that.setFragment(that._texturePath);
  12718. }
  12719. catch (ex) {
  12720. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  12721. }
  12722. }
  12723. var configFileUrl = jsonUrl + "/config.json";
  12724. var xhr = new XMLHttpRequest();
  12725. xhr.open("GET", configFileUrl, true);
  12726. xhr.addEventListener("load", function () {
  12727. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  12728. try {
  12729. _this._config = JSON.parse(xhr.response);
  12730. _this.updateShaderUniforms();
  12731. _this.updateTextures();
  12732. _this.setFragment(_this._texturePath + "/custom");
  12733. _this._animate = _this._config.animate;
  12734. _this.refreshRate = _this._config.refreshrate;
  12735. }
  12736. catch (ex) {
  12737. noConfigFile();
  12738. }
  12739. }
  12740. else {
  12741. noConfigFile();
  12742. }
  12743. }, false);
  12744. xhr.addEventListener("error", function () {
  12745. noConfigFile();
  12746. }, false);
  12747. try {
  12748. xhr.send();
  12749. }
  12750. catch (ex) {
  12751. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  12752. }
  12753. };
  12754. CustomProceduralTexture.prototype.isReady = function () {
  12755. if (!_super.prototype.isReady.call(this)) {
  12756. return false;
  12757. }
  12758. for (var name in this._textures) {
  12759. var texture = this._textures[name];
  12760. if (!texture.isReady()) {
  12761. return false;
  12762. }
  12763. }
  12764. return true;
  12765. };
  12766. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12767. if (this._animate) {
  12768. this._time += this.getScene().getAnimationRatio() * 0.03;
  12769. this.updateShaderUniforms();
  12770. }
  12771. _super.prototype.render.call(this, useCameraPostProcess);
  12772. };
  12773. CustomProceduralTexture.prototype.updateTextures = function () {
  12774. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  12775. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  12776. }
  12777. };
  12778. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  12779. if (this._config) {
  12780. for (var j = 0; j < this._config.uniforms.length; j++) {
  12781. var uniform = this._config.uniforms[j];
  12782. switch (uniform.type) {
  12783. case "float":
  12784. this.setFloat(uniform.name, uniform.value);
  12785. break;
  12786. case "color3":
  12787. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  12788. break;
  12789. case "color4":
  12790. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  12791. break;
  12792. case "vector2":
  12793. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  12794. break;
  12795. case "vector3":
  12796. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  12797. break;
  12798. }
  12799. }
  12800. }
  12801. this.setFloat("time", this._time);
  12802. };
  12803. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  12804. get: function () {
  12805. return this._animate;
  12806. },
  12807. set: function (value) {
  12808. this._animate = value;
  12809. },
  12810. enumerable: true,
  12811. configurable: true
  12812. });
  12813. return CustomProceduralTexture;
  12814. })(BABYLON.ProceduralTexture);
  12815. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  12816. })(BABYLON || (BABYLON = {}));
  12817. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  12818. var BABYLON;
  12819. (function (BABYLON) {
  12820. var MirrorTexture = (function (_super) {
  12821. __extends(MirrorTexture, _super);
  12822. function MirrorTexture(name, size, scene, generateMipMaps) {
  12823. var _this = this;
  12824. _super.call(this, name, size, scene, generateMipMaps, true);
  12825. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  12826. this._transformMatrix = BABYLON.Matrix.Zero();
  12827. this._mirrorMatrix = BABYLON.Matrix.Zero();
  12828. this.onBeforeRender = function () {
  12829. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  12830. _this._savedViewMatrix = scene.getViewMatrix();
  12831. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  12832. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  12833. scene.clipPlane = _this.mirrorPlane;
  12834. scene.getEngine().cullBackFaces = false;
  12835. };
  12836. this.onAfterRender = function () {
  12837. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  12838. scene.getEngine().cullBackFaces = true;
  12839. delete scene.clipPlane;
  12840. };
  12841. }
  12842. MirrorTexture.prototype.clone = function () {
  12843. var textureSize = this.getSize();
  12844. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12845. // Base texture
  12846. newTexture.hasAlpha = this.hasAlpha;
  12847. newTexture.level = this.level;
  12848. // Mirror Texture
  12849. newTexture.mirrorPlane = this.mirrorPlane.clone();
  12850. newTexture.renderList = this.renderList.slice(0);
  12851. return newTexture;
  12852. };
  12853. return MirrorTexture;
  12854. })(BABYLON.RenderTargetTexture);
  12855. BABYLON.MirrorTexture = MirrorTexture;
  12856. })(BABYLON || (BABYLON = {}));
  12857. //# sourceMappingURL=babylon.mirrorTexture.js.map
  12858. var BABYLON;
  12859. (function (BABYLON) {
  12860. var DynamicTexture = (function (_super) {
  12861. __extends(DynamicTexture, _super);
  12862. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  12863. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12864. _super.call(this, null, scene, !generateMipMaps);
  12865. this.name = name;
  12866. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12867. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12868. this._generateMipMaps = generateMipMaps;
  12869. if (options.getContext) {
  12870. this._canvas = options;
  12871. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12872. }
  12873. else {
  12874. this._canvas = document.createElement("canvas");
  12875. if (options.width) {
  12876. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12877. }
  12878. else {
  12879. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  12880. }
  12881. }
  12882. var textureSize = this.getSize();
  12883. this._canvas.width = textureSize.width;
  12884. this._canvas.height = textureSize.height;
  12885. this._context = this._canvas.getContext("2d");
  12886. }
  12887. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  12888. get: function () {
  12889. return true;
  12890. },
  12891. enumerable: true,
  12892. configurable: true
  12893. });
  12894. DynamicTexture.prototype.scale = function (ratio) {
  12895. var textureSize = this.getSize();
  12896. textureSize.width *= ratio;
  12897. textureSize.height *= ratio;
  12898. this._canvas.width = textureSize.width;
  12899. this._canvas.height = textureSize.height;
  12900. this.releaseInternalTexture();
  12901. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  12902. };
  12903. DynamicTexture.prototype.getContext = function () {
  12904. return this._context;
  12905. };
  12906. DynamicTexture.prototype.clear = function () {
  12907. var size = this.getSize();
  12908. this._context.fillRect(0, 0, size.width, size.height);
  12909. };
  12910. DynamicTexture.prototype.update = function (invertY) {
  12911. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  12912. };
  12913. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  12914. if (update === void 0) { update = true; }
  12915. var size = this.getSize();
  12916. if (clearColor) {
  12917. this._context.fillStyle = clearColor;
  12918. this._context.fillRect(0, 0, size.width, size.height);
  12919. }
  12920. this._context.font = font;
  12921. if (x === null) {
  12922. var textSize = this._context.measureText(text);
  12923. x = (size.width - textSize.width) / 2;
  12924. }
  12925. this._context.fillStyle = color;
  12926. this._context.fillText(text, x, y);
  12927. if (update) {
  12928. this.update(invertY);
  12929. }
  12930. };
  12931. DynamicTexture.prototype.clone = function () {
  12932. var textureSize = this.getSize();
  12933. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12934. // Base texture
  12935. newTexture.hasAlpha = this.hasAlpha;
  12936. newTexture.level = this.level;
  12937. // Dynamic Texture
  12938. newTexture.wrapU = this.wrapU;
  12939. newTexture.wrapV = this.wrapV;
  12940. return newTexture;
  12941. };
  12942. return DynamicTexture;
  12943. })(BABYLON.Texture);
  12944. BABYLON.DynamicTexture = DynamicTexture;
  12945. })(BABYLON || (BABYLON = {}));
  12946. //# sourceMappingURL=babylon.dynamicTexture.js.map
  12947. var BABYLON;
  12948. (function (BABYLON) {
  12949. var VideoTexture = (function (_super) {
  12950. __extends(VideoTexture, _super);
  12951. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  12952. var _this = this;
  12953. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12954. _super.call(this, null, scene, !generateMipMaps, invertY);
  12955. this._autoLaunch = true;
  12956. this.name = name;
  12957. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12958. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12959. var requiredWidth = size.width || size;
  12960. var requiredHeight = size.height || size;
  12961. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  12962. var textureSize = this.getSize();
  12963. this.video = document.createElement("video");
  12964. this.video.width = textureSize.width;
  12965. this.video.height = textureSize.height;
  12966. this.video.autoplay = false;
  12967. this.video.loop = true;
  12968. this.video.addEventListener("canplaythrough", function () {
  12969. if (_this._texture) {
  12970. _this._texture.isReady = true;
  12971. }
  12972. });
  12973. urls.forEach(function (url) {
  12974. var source = document.createElement("source");
  12975. source.src = url;
  12976. _this.video.appendChild(source);
  12977. });
  12978. this._lastUpdate = BABYLON.Tools.Now;
  12979. }
  12980. VideoTexture.prototype.update = function () {
  12981. if (this._autoLaunch) {
  12982. this._autoLaunch = false;
  12983. this.video.play();
  12984. }
  12985. var now = BABYLON.Tools.Now;
  12986. if (now - this._lastUpdate < 15) {
  12987. return false;
  12988. }
  12989. this._lastUpdate = now;
  12990. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  12991. return true;
  12992. };
  12993. return VideoTexture;
  12994. })(BABYLON.Texture);
  12995. BABYLON.VideoTexture = VideoTexture;
  12996. })(BABYLON || (BABYLON = {}));
  12997. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  12998. (function (BABYLON) {
  12999. var EffectFallbacks = (function () {
  13000. function EffectFallbacks() {
  13001. this._defines = {};
  13002. this._currentRank = 32;
  13003. this._maxRank = -1;
  13004. }
  13005. EffectFallbacks.prototype.addFallback = function (rank, define) {
  13006. if (!this._defines[rank]) {
  13007. if (rank < this._currentRank) {
  13008. this._currentRank = rank;
  13009. }
  13010. if (rank > this._maxRank) {
  13011. this._maxRank = rank;
  13012. }
  13013. this._defines[rank] = new Array();
  13014. }
  13015. this._defines[rank].push(define);
  13016. };
  13017. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  13018. get: function () {
  13019. return this._currentRank <= this._maxRank;
  13020. },
  13021. enumerable: true,
  13022. configurable: true
  13023. });
  13024. EffectFallbacks.prototype.reduce = function (currentDefines) {
  13025. var currentFallbacks = this._defines[this._currentRank];
  13026. for (var index = 0; index < currentFallbacks.length; index++) {
  13027. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  13028. }
  13029. this._currentRank++;
  13030. return currentDefines;
  13031. };
  13032. return EffectFallbacks;
  13033. })();
  13034. BABYLON.EffectFallbacks = EffectFallbacks;
  13035. var Effect = (function () {
  13036. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  13037. var _this = this;
  13038. this._isReady = false;
  13039. this._compilationError = "";
  13040. this._valueCache = [];
  13041. this._engine = engine;
  13042. this.name = baseName;
  13043. this.defines = defines;
  13044. this._uniformsNames = uniformsNames.concat(samplers);
  13045. this._samplers = samplers;
  13046. this._attributesNames = attributesNames;
  13047. this.onError = onError;
  13048. this.onCompiled = onCompiled;
  13049. var vertexSource;
  13050. var fragmentSource;
  13051. if (baseName.vertexElement) {
  13052. vertexSource = document.getElementById(baseName.vertexElement);
  13053. if (!vertexSource) {
  13054. vertexSource = baseName.vertexElement;
  13055. }
  13056. }
  13057. else {
  13058. vertexSource = baseName.vertex || baseName;
  13059. }
  13060. if (baseName.fragmentElement) {
  13061. fragmentSource = document.getElementById(baseName.fragmentElement);
  13062. if (!fragmentSource) {
  13063. fragmentSource = baseName.fragmentElement;
  13064. }
  13065. }
  13066. else {
  13067. fragmentSource = baseName.fragment || baseName;
  13068. }
  13069. this._loadVertexShader(vertexSource, function (vertexCode) {
  13070. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  13071. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  13072. });
  13073. });
  13074. }
  13075. // Properties
  13076. Effect.prototype.isReady = function () {
  13077. return this._isReady;
  13078. };
  13079. Effect.prototype.getProgram = function () {
  13080. return this._program;
  13081. };
  13082. Effect.prototype.getAttributesNames = function () {
  13083. return this._attributesNames;
  13084. };
  13085. Effect.prototype.getAttributeLocation = function (index) {
  13086. return this._attributes[index];
  13087. };
  13088. Effect.prototype.getAttributeLocationByName = function (name) {
  13089. var index = this._attributesNames.indexOf(name);
  13090. return this._attributes[index];
  13091. };
  13092. Effect.prototype.getAttributesCount = function () {
  13093. return this._attributes.length;
  13094. };
  13095. Effect.prototype.getUniformIndex = function (uniformName) {
  13096. return this._uniformsNames.indexOf(uniformName);
  13097. };
  13098. Effect.prototype.getUniform = function (uniformName) {
  13099. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  13100. };
  13101. Effect.prototype.getSamplers = function () {
  13102. return this._samplers;
  13103. };
  13104. Effect.prototype.getCompilationError = function () {
  13105. return this._compilationError;
  13106. };
  13107. // Methods
  13108. Effect.prototype._loadVertexShader = function (vertex, callback) {
  13109. // DOM element ?
  13110. if (vertex instanceof HTMLElement) {
  13111. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  13112. callback(vertexCode);
  13113. return;
  13114. }
  13115. // Is in local store ?
  13116. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  13117. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  13118. return;
  13119. }
  13120. var vertexShaderUrl;
  13121. if (vertex[0] === ".") {
  13122. vertexShaderUrl = vertex;
  13123. }
  13124. else {
  13125. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  13126. }
  13127. // Vertex shader
  13128. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  13129. };
  13130. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  13131. // DOM element ?
  13132. if (fragment instanceof HTMLElement) {
  13133. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  13134. callback(fragmentCode);
  13135. return;
  13136. }
  13137. // Is in local store ?
  13138. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  13139. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  13140. return;
  13141. }
  13142. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  13143. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  13144. return;
  13145. }
  13146. var fragmentShaderUrl;
  13147. if (fragment[0] === ".") {
  13148. fragmentShaderUrl = fragment;
  13149. }
  13150. else {
  13151. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  13152. }
  13153. // Fragment shader
  13154. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  13155. };
  13156. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  13157. try {
  13158. var engine = this._engine;
  13159. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  13160. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  13161. this._attributes = engine.getAttributes(this._program, attributesNames);
  13162. for (var index = 0; index < this._samplers.length; index++) {
  13163. var sampler = this.getUniform(this._samplers[index]);
  13164. if (sampler == null) {
  13165. this._samplers.splice(index, 1);
  13166. index--;
  13167. }
  13168. }
  13169. engine.bindSamplers(this);
  13170. this._isReady = true;
  13171. if (this.onCompiled) {
  13172. this.onCompiled(this);
  13173. }
  13174. }
  13175. catch (e) {
  13176. // Is it a problem with precision?
  13177. if (e.message.indexOf("highp") !== -1) {
  13178. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  13179. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  13180. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13181. return;
  13182. }
  13183. // Let's go through fallbacks then
  13184. if (fallbacks && fallbacks.isMoreFallbacks) {
  13185. defines = fallbacks.reduce(defines);
  13186. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13187. }
  13188. else {
  13189. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  13190. BABYLON.Tools.Error("Defines: " + defines);
  13191. BABYLON.Tools.Error("Error: " + e.message);
  13192. this._compilationError = e.message;
  13193. if (this.onError) {
  13194. this.onError(this, this._compilationError);
  13195. }
  13196. }
  13197. }
  13198. };
  13199. Effect.prototype._bindTexture = function (channel, texture) {
  13200. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  13201. };
  13202. Effect.prototype.setTexture = function (channel, texture) {
  13203. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  13204. };
  13205. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13206. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  13207. };
  13208. //public _cacheMatrix(uniformName, matrix) {
  13209. // if (!this._valueCache[uniformName]) {
  13210. // this._valueCache[uniformName] = new BABYLON.Matrix();
  13211. // }
  13212. // for (var index = 0; index < 16; index++) {
  13213. // this._valueCache[uniformName].m[index] = matrix.m[index];
  13214. // }
  13215. //};
  13216. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  13217. if (!this._valueCache[uniformName]) {
  13218. this._valueCache[uniformName] = [x, y];
  13219. return;
  13220. }
  13221. this._valueCache[uniformName][0] = x;
  13222. this._valueCache[uniformName][1] = y;
  13223. };
  13224. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  13225. if (!this._valueCache[uniformName]) {
  13226. this._valueCache[uniformName] = [x, y, z];
  13227. return;
  13228. }
  13229. this._valueCache[uniformName][0] = x;
  13230. this._valueCache[uniformName][1] = y;
  13231. this._valueCache[uniformName][2] = z;
  13232. };
  13233. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  13234. if (!this._valueCache[uniformName]) {
  13235. this._valueCache[uniformName] = [x, y, z, w];
  13236. return;
  13237. }
  13238. this._valueCache[uniformName][0] = x;
  13239. this._valueCache[uniformName][1] = y;
  13240. this._valueCache[uniformName][2] = z;
  13241. this._valueCache[uniformName][3] = w;
  13242. };
  13243. Effect.prototype.setArray = function (uniformName, array) {
  13244. this._engine.setArray(this.getUniform(uniformName), array);
  13245. return this;
  13246. };
  13247. Effect.prototype.setArray2 = function (uniformName, array) {
  13248. this._engine.setArray2(this.getUniform(uniformName), array);
  13249. return this;
  13250. };
  13251. Effect.prototype.setArray3 = function (uniformName, array) {
  13252. this._engine.setArray3(this.getUniform(uniformName), array);
  13253. return this;
  13254. };
  13255. Effect.prototype.setArray4 = function (uniformName, array) {
  13256. this._engine.setArray4(this.getUniform(uniformName), array);
  13257. return this;
  13258. };
  13259. Effect.prototype.setMatrices = function (uniformName, matrices) {
  13260. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  13261. return this;
  13262. };
  13263. Effect.prototype.setMatrix = function (uniformName, matrix) {
  13264. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  13265. // return;
  13266. //this._cacheMatrix(uniformName, matrix);
  13267. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  13268. return this;
  13269. };
  13270. Effect.prototype.setFloat = function (uniformName, value) {
  13271. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  13272. return this;
  13273. this._valueCache[uniformName] = value;
  13274. this._engine.setFloat(this.getUniform(uniformName), value);
  13275. return this;
  13276. };
  13277. Effect.prototype.setBool = function (uniformName, bool) {
  13278. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  13279. return this;
  13280. this._valueCache[uniformName] = bool;
  13281. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  13282. return this;
  13283. };
  13284. Effect.prototype.setVector2 = function (uniformName, vector2) {
  13285. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  13286. return this;
  13287. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  13288. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  13289. return this;
  13290. };
  13291. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  13292. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  13293. return this;
  13294. this._cacheFloat2(uniformName, x, y);
  13295. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  13296. return this;
  13297. };
  13298. Effect.prototype.setVector3 = function (uniformName, vector3) {
  13299. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  13300. return this;
  13301. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  13302. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  13303. return this;
  13304. };
  13305. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  13306. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  13307. return this;
  13308. this._cacheFloat3(uniformName, x, y, z);
  13309. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  13310. return this;
  13311. };
  13312. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  13313. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  13314. return this;
  13315. this._cacheFloat4(uniformName, x, y, z, w);
  13316. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  13317. return this;
  13318. };
  13319. Effect.prototype.setColor3 = function (uniformName, color3) {
  13320. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  13321. return this;
  13322. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  13323. this._engine.setColor3(this.getUniform(uniformName), color3);
  13324. return this;
  13325. };
  13326. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  13327. 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)
  13328. return this;
  13329. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  13330. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  13331. return this;
  13332. };
  13333. // Statics
  13334. 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}",
  13335. 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}",
  13336. 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}",
  13337. 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}",
  13338. 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}",
  13339. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  13340. 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}",
  13341. 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}",
  13342. defaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform float darkness0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform float darkness1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform float darkness2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform float darkness3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / 1500.0)) < depth.z) visibility -= 0.2;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.0 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, darkness0);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, darkness1);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, darkness2);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, darkness3);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  13343. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef REFLECTION\n vPositionUVW = position;\n#endif \n\n#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#else\n finalWorld = finalWorld * (m0 + m1 + m2);\n#endif \n\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n\n // Point size\n#ifdef POINTSIZE\n gl_PointSize = pointSize;\n#endif\n}",
  13344. 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}",
  13345. depthVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  13346. 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}",
  13347. 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}",
  13348. 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}",
  13349. 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}",
  13350. 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}",
  13351. 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}",
  13352. 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}",
  13353. 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}",
  13354. 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}",
  13355. 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}",
  13356. 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}",
  13357. 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}",
  13358. 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}",
  13359. 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}",
  13360. 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}",
  13361. 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}",
  13362. 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}",
  13363. 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}",
  13364. 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}",
  13365. 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}",
  13366. 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}",
  13367. 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}",
  13368. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\n const vec4 bitOffset = vec4(255. * 255. * 255., 255. * 255., 255., 1.);\n const vec4 bitMask = vec4(0., 1. / 255., 1. / 255., 1. / 255.);\n \n vec4 comp = mod(depth * bitOffset * vec4(254.), vec4(255.)) / vec4(254.);\n comp -= comp.xxyz * bitMask;\n \n return comp;\n}\n\n// Thanks to http://devmaster.net/\nvec2 packHalf(float depth) \n{ \n const vec2 bitOffset = vec2(1.0 / 255., 0.);\n vec2 color = vec2(depth, fract(depth * 255.));\n\n return color - (color.yy * bitOffset);\n}\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n#ifdef VSM\n float moment1 = gl_FragCoord.z / gl_FragCoord.w;\n float moment2 = moment1 * moment1;\n gl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\n gl_FragColor = pack(vPosition.z / vPosition.w);\n#endif\n}",
  13369. shadowMapVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n#ifndef VSM\n vPosition = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  13370. 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}",
  13371. spritesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\n// Uniforms\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\nvoid main(void) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n \n float angle = options.x;\n float size = options.y;\n vec2 offset = options.zw;\n vec2 uvScale = textureInfos.xy;\n\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n\n // Color\n vColor = color;\n \n // Texture\n vec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\n\n vUV = (uvOffset + cellInfo.zw) * uvScale;\n\n // Fog\n#ifdef FOG\n fFogDistance = viewPos.z;\n#endif\n}",
  13372. 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}",
  13373. 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}",
  13374. 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}",
  13375. volumetricLightScatteringPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER) || defined(OPACITY)\nvarying vec2 vUV;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nuniform sampler2D diffuseSampler;\n#endif\n\n#if defined(OPACITY)\nuniform sampler2D opacitySampler;\n#endif\n\nvoid main(void)\n{\n#if defined(ALPHATEST) || defined(OPACITY) || defined(BASIC_RENDER)\n vec4 diffuseColor = texture2D(diffuseSampler, vUV);\n#endif\n\n#ifdef ALPHATEST\n if (diffuseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef BASIC_RENDER\n#ifdef OPACITY\n gl_FragColor = diffuseColor * texture2D(opacitySampler, vUV);\n#else\n gl_FragColor = diffuseColor;\n#endif\n#else\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n#endif\n\n}",
  13376. 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}",
  13377. };
  13378. return Effect;
  13379. })();
  13380. BABYLON.Effect = Effect;
  13381. })(BABYLON || (BABYLON = {}));
  13382. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  13383. (function (BABYLON) {
  13384. var Material = (function () {
  13385. function Material(name, scene, doNotAdd) {
  13386. this.name = name;
  13387. this.checkReadyOnEveryCall = true;
  13388. this.checkReadyOnlyOnce = false;
  13389. this.state = "";
  13390. this.alpha = 1.0;
  13391. this.backFaceCulling = true;
  13392. this._wasPreviouslyReady = false;
  13393. this._fillMode = Material.TriangleFillMode;
  13394. this.pointSize = 1.0;
  13395. this.id = name;
  13396. this._scene = scene;
  13397. if (!doNotAdd) {
  13398. scene.materials.push(this);
  13399. }
  13400. }
  13401. Object.defineProperty(Material, "TriangleFillMode", {
  13402. get: function () {
  13403. return Material._TriangleFillMode;
  13404. },
  13405. enumerable: true,
  13406. configurable: true
  13407. });
  13408. Object.defineProperty(Material, "WireFrameFillMode", {
  13409. get: function () {
  13410. return Material._WireFrameFillMode;
  13411. },
  13412. enumerable: true,
  13413. configurable: true
  13414. });
  13415. Object.defineProperty(Material, "PointFillMode", {
  13416. get: function () {
  13417. return Material._PointFillMode;
  13418. },
  13419. enumerable: true,
  13420. configurable: true
  13421. });
  13422. Object.defineProperty(Material.prototype, "wireframe", {
  13423. get: function () {
  13424. return this._fillMode === Material.WireFrameFillMode;
  13425. },
  13426. set: function (value) {
  13427. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  13428. },
  13429. enumerable: true,
  13430. configurable: true
  13431. });
  13432. Object.defineProperty(Material.prototype, "pointsCloud", {
  13433. get: function () {
  13434. return this._fillMode === Material.PointFillMode;
  13435. },
  13436. set: function (value) {
  13437. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  13438. },
  13439. enumerable: true,
  13440. configurable: true
  13441. });
  13442. Object.defineProperty(Material.prototype, "fillMode", {
  13443. get: function () {
  13444. return this._fillMode;
  13445. },
  13446. set: function (value) {
  13447. this._fillMode = value;
  13448. },
  13449. enumerable: true,
  13450. configurable: true
  13451. });
  13452. Material.prototype.isReady = function (mesh, useInstances) {
  13453. return true;
  13454. };
  13455. Material.prototype.getEffect = function () {
  13456. return this._effect;
  13457. };
  13458. Material.prototype.getScene = function () {
  13459. return this._scene;
  13460. };
  13461. Material.prototype.needAlphaBlending = function () {
  13462. return (this.alpha < 1.0);
  13463. };
  13464. Material.prototype.needAlphaTesting = function () {
  13465. return false;
  13466. };
  13467. Material.prototype.getAlphaTestTexture = function () {
  13468. return null;
  13469. };
  13470. Material.prototype.trackCreation = function (onCompiled, onError) {
  13471. };
  13472. Material.prototype._preBind = function () {
  13473. var engine = this._scene.getEngine();
  13474. engine.enableEffect(this._effect);
  13475. engine.setState(this.backFaceCulling);
  13476. };
  13477. Material.prototype.bind = function (world, mesh) {
  13478. this._scene._cachedMaterial = this;
  13479. if (this.onBind) {
  13480. this.onBind(this);
  13481. }
  13482. };
  13483. Material.prototype.bindOnlyWorldMatrix = function (world) {
  13484. };
  13485. Material.prototype.unbind = function () {
  13486. };
  13487. Material.prototype.dispose = function (forceDisposeEffect) {
  13488. // Remove from scene
  13489. var index = this._scene.materials.indexOf(this);
  13490. this._scene.materials.splice(index, 1);
  13491. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  13492. if (forceDisposeEffect && this._effect) {
  13493. this._scene.getEngine()._releaseEffect(this._effect);
  13494. this._effect = null;
  13495. }
  13496. // Callback
  13497. if (this.onDispose) {
  13498. this.onDispose();
  13499. }
  13500. };
  13501. Material._TriangleFillMode = 0;
  13502. Material._WireFrameFillMode = 1;
  13503. Material._PointFillMode = 2;
  13504. return Material;
  13505. })();
  13506. BABYLON.Material = Material;
  13507. })(BABYLON || (BABYLON = {}));
  13508. //# sourceMappingURL=babylon.material.js.map
  13509. var BABYLON;
  13510. (function (BABYLON) {
  13511. var maxSimultaneousLights = 4;
  13512. var FresnelParameters = (function () {
  13513. function FresnelParameters() {
  13514. this.isEnabled = true;
  13515. this.leftColor = BABYLON.Color3.White();
  13516. this.rightColor = BABYLON.Color3.Black();
  13517. this.bias = 0;
  13518. this.power = 1;
  13519. }
  13520. return FresnelParameters;
  13521. })();
  13522. BABYLON.FresnelParameters = FresnelParameters;
  13523. var StandardMaterial = (function (_super) {
  13524. __extends(StandardMaterial, _super);
  13525. function StandardMaterial(name, scene) {
  13526. var _this = this;
  13527. _super.call(this, name, scene);
  13528. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13529. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  13530. this.specularColor = new BABYLON.Color3(1, 1, 1);
  13531. this.specularPower = 64;
  13532. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  13533. this.useAlphaFromDiffuseTexture = false;
  13534. this.useSpecularOverAlpha = true;
  13535. this.fogEnabled = true;
  13536. this._cachedDefines = null;
  13537. this._renderTargets = new BABYLON.SmartArray(16);
  13538. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  13539. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  13540. this._scaledDiffuse = new BABYLON.Color3();
  13541. this._scaledSpecular = new BABYLON.Color3();
  13542. this.getRenderTargetTextures = function () {
  13543. _this._renderTargets.reset();
  13544. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  13545. _this._renderTargets.push(_this.reflectionTexture);
  13546. }
  13547. return _this._renderTargets;
  13548. };
  13549. }
  13550. StandardMaterial.prototype.needAlphaBlending = function () {
  13551. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  13552. };
  13553. StandardMaterial.prototype.needAlphaTesting = function () {
  13554. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  13555. };
  13556. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  13557. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  13558. };
  13559. StandardMaterial.prototype.getAlphaTestTexture = function () {
  13560. return this.diffuseTexture;
  13561. };
  13562. // Methods
  13563. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  13564. if (this.checkReadyOnlyOnce) {
  13565. if (this._wasPreviouslyReady) {
  13566. return true;
  13567. }
  13568. }
  13569. var scene = this.getScene();
  13570. if (!this.checkReadyOnEveryCall) {
  13571. if (this._renderId === scene.getRenderId()) {
  13572. return true;
  13573. }
  13574. }
  13575. var engine = scene.getEngine();
  13576. var defines = [];
  13577. var fallbacks = new BABYLON.EffectFallbacks();
  13578. // Textures
  13579. if (scene.texturesEnabled) {
  13580. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13581. if (!this.diffuseTexture.isReady()) {
  13582. return false;
  13583. }
  13584. else {
  13585. defines.push("#define DIFFUSE");
  13586. }
  13587. }
  13588. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13589. if (!this.ambientTexture.isReady()) {
  13590. return false;
  13591. }
  13592. else {
  13593. defines.push("#define AMBIENT");
  13594. }
  13595. }
  13596. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13597. if (!this.opacityTexture.isReady()) {
  13598. return false;
  13599. }
  13600. else {
  13601. defines.push("#define OPACITY");
  13602. if (this.opacityTexture.getAlphaFromRGB) {
  13603. defines.push("#define OPACITYRGB");
  13604. }
  13605. }
  13606. }
  13607. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13608. if (!this.reflectionTexture.isReady()) {
  13609. return false;
  13610. }
  13611. else {
  13612. defines.push("#define REFLECTION");
  13613. fallbacks.addFallback(0, "REFLECTION");
  13614. }
  13615. }
  13616. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13617. if (!this.emissiveTexture.isReady()) {
  13618. return false;
  13619. }
  13620. else {
  13621. defines.push("#define EMISSIVE");
  13622. }
  13623. }
  13624. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13625. if (!this.specularTexture.isReady()) {
  13626. return false;
  13627. }
  13628. else {
  13629. defines.push("#define SPECULAR");
  13630. fallbacks.addFallback(0, "SPECULAR");
  13631. }
  13632. }
  13633. }
  13634. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  13635. if (!this.bumpTexture.isReady()) {
  13636. return false;
  13637. }
  13638. else {
  13639. defines.push("#define BUMP");
  13640. fallbacks.addFallback(0, "BUMP");
  13641. }
  13642. }
  13643. // Effect
  13644. if (this.useSpecularOverAlpha) {
  13645. defines.push("#define SPECULAROVERALPHA");
  13646. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  13647. }
  13648. if (scene.clipPlane) {
  13649. defines.push("#define CLIPPLANE");
  13650. }
  13651. if (engine.getAlphaTesting()) {
  13652. defines.push("#define ALPHATEST");
  13653. }
  13654. if (this._shouldUseAlphaFromDiffuseTexture()) {
  13655. defines.push("#define ALPHAFROMDIFFUSE");
  13656. }
  13657. // Point size
  13658. if (this.pointsCloud || scene.forcePointsCloud) {
  13659. defines.push("#define POINTSIZE");
  13660. }
  13661. // Fog
  13662. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13663. defines.push("#define FOG");
  13664. fallbacks.addFallback(1, "FOG");
  13665. }
  13666. var shadowsActivated = false;
  13667. var lightIndex = 0;
  13668. if (scene.lightsEnabled) {
  13669. for (var index = 0; index < scene.lights.length; index++) {
  13670. var light = scene.lights[index];
  13671. if (!light.isEnabled()) {
  13672. continue;
  13673. }
  13674. // Excluded check
  13675. if (light._excludedMeshesIds.length > 0) {
  13676. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  13677. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  13678. if (excludedMesh) {
  13679. light.excludedMeshes.push(excludedMesh);
  13680. }
  13681. }
  13682. light._excludedMeshesIds = [];
  13683. }
  13684. // Included check
  13685. if (light._includedOnlyMeshesIds.length > 0) {
  13686. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  13687. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  13688. if (includedOnlyMesh) {
  13689. light.includedOnlyMeshes.push(includedOnlyMesh);
  13690. }
  13691. }
  13692. light._includedOnlyMeshesIds = [];
  13693. }
  13694. if (!light.canAffectMesh(mesh)) {
  13695. continue;
  13696. }
  13697. defines.push("#define LIGHT" + lightIndex);
  13698. if (lightIndex > 0) {
  13699. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  13700. }
  13701. var type;
  13702. if (light instanceof BABYLON.SpotLight) {
  13703. type = "#define SPOTLIGHT" + lightIndex;
  13704. }
  13705. else if (light instanceof BABYLON.HemisphericLight) {
  13706. type = "#define HEMILIGHT" + lightIndex;
  13707. }
  13708. else {
  13709. type = "#define POINTDIRLIGHT" + lightIndex;
  13710. }
  13711. defines.push(type);
  13712. if (lightIndex > 0) {
  13713. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  13714. }
  13715. // Shadows
  13716. if (scene.shadowsEnabled) {
  13717. var shadowGenerator = light.getShadowGenerator();
  13718. if (mesh && mesh.receiveShadows && shadowGenerator) {
  13719. defines.push("#define SHADOW" + lightIndex);
  13720. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  13721. if (!shadowsActivated) {
  13722. defines.push("#define SHADOWS");
  13723. shadowsActivated = true;
  13724. }
  13725. if (shadowGenerator.useVarianceShadowMap) {
  13726. defines.push("#define SHADOWVSM" + lightIndex);
  13727. if (lightIndex > 0) {
  13728. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  13729. }
  13730. }
  13731. if (shadowGenerator.usePoissonSampling) {
  13732. defines.push("#define SHADOWPCF" + lightIndex);
  13733. if (lightIndex > 0) {
  13734. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  13735. }
  13736. }
  13737. }
  13738. }
  13739. lightIndex++;
  13740. if (lightIndex === maxSimultaneousLights)
  13741. break;
  13742. }
  13743. }
  13744. if (StandardMaterial.FresnelEnabled) {
  13745. // Fresnel
  13746. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13747. var fresnelRank = 1;
  13748. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13749. defines.push("#define DIFFUSEFRESNEL");
  13750. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  13751. fresnelRank++;
  13752. }
  13753. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13754. defines.push("#define OPACITYFRESNEL");
  13755. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  13756. fresnelRank++;
  13757. }
  13758. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13759. defines.push("#define REFLECTIONFRESNEL");
  13760. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  13761. fresnelRank++;
  13762. }
  13763. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13764. defines.push("#define EMISSIVEFRESNEL");
  13765. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  13766. fresnelRank++;
  13767. }
  13768. defines.push("#define FRESNEL");
  13769. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  13770. }
  13771. }
  13772. // Attribs
  13773. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  13774. if (mesh) {
  13775. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13776. attribs.push(BABYLON.VertexBuffer.UVKind);
  13777. defines.push("#define UV1");
  13778. }
  13779. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13780. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  13781. defines.push("#define UV2");
  13782. }
  13783. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13784. attribs.push(BABYLON.VertexBuffer.ColorKind);
  13785. defines.push("#define VERTEXCOLOR");
  13786. if (mesh.hasVertexAlpha) {
  13787. defines.push("#define VERTEXALPHA");
  13788. }
  13789. }
  13790. if (mesh.useBones) {
  13791. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  13792. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  13793. defines.push("#define BONES");
  13794. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  13795. defines.push("#define BONES4");
  13796. fallbacks.addFallback(0, "BONES4");
  13797. }
  13798. // Instances
  13799. if (useInstances) {
  13800. defines.push("#define INSTANCES");
  13801. attribs.push("world0");
  13802. attribs.push("world1");
  13803. attribs.push("world2");
  13804. attribs.push("world3");
  13805. }
  13806. }
  13807. // Get correct effect
  13808. var join = defines.join("\n");
  13809. if (this._cachedDefines !== join) {
  13810. this._cachedDefines = join;
  13811. scene.resetCachedMaterial();
  13812. // Legacy browser patch
  13813. var shaderName = "default";
  13814. if (!scene.getEngine().getCaps().standardDerivatives) {
  13815. shaderName = "legacydefault";
  13816. }
  13817. 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", "darkness0", "darkness1", "darkness2", "darkness3", "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);
  13818. }
  13819. if (!this._effect.isReady()) {
  13820. return false;
  13821. }
  13822. this._renderId = scene.getRenderId();
  13823. this._wasPreviouslyReady = true;
  13824. return true;
  13825. };
  13826. StandardMaterial.prototype.unbind = function () {
  13827. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  13828. this._effect.setTexture("reflection2DSampler", null);
  13829. }
  13830. };
  13831. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  13832. this._effect.setMatrix("world", world);
  13833. };
  13834. StandardMaterial.prototype.bind = function (world, mesh) {
  13835. var scene = this.getScene();
  13836. // Matrices
  13837. this.bindOnlyWorldMatrix(world);
  13838. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  13839. // Bones
  13840. if (mesh.useBones) {
  13841. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  13842. }
  13843. if (scene.getCachedMaterial() !== this) {
  13844. if (StandardMaterial.FresnelEnabled) {
  13845. // Fresnel
  13846. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13847. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  13848. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  13849. }
  13850. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13851. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  13852. }
  13853. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13854. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  13855. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  13856. }
  13857. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13858. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  13859. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  13860. }
  13861. }
  13862. // Textures
  13863. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13864. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  13865. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  13866. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  13867. }
  13868. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13869. this._effect.setTexture("ambientSampler", this.ambientTexture);
  13870. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  13871. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  13872. }
  13873. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13874. this._effect.setTexture("opacitySampler", this.opacityTexture);
  13875. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  13876. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  13877. }
  13878. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13879. if (this.reflectionTexture.isCube) {
  13880. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  13881. }
  13882. else {
  13883. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  13884. }
  13885. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  13886. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  13887. }
  13888. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13889. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  13890. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  13891. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  13892. }
  13893. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13894. this._effect.setTexture("specularSampler", this.specularTexture);
  13895. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  13896. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  13897. }
  13898. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  13899. this._effect.setTexture("bumpSampler", this.bumpTexture);
  13900. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  13901. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  13902. }
  13903. // Clip plane
  13904. if (scene.clipPlane) {
  13905. var clipPlane = scene.clipPlane;
  13906. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  13907. }
  13908. // Point size
  13909. if (this.pointsCloud) {
  13910. this._effect.setFloat("pointSize", this.pointSize);
  13911. }
  13912. // Colors
  13913. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  13914. // Scaling down color according to emissive
  13915. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13916. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13917. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13918. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  13919. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  13920. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  13921. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  13922. }
  13923. // Scaling down color according to emissive
  13924. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13925. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13926. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13927. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  13928. if (scene.lightsEnabled) {
  13929. var lightIndex = 0;
  13930. for (var index = 0; index < scene.lights.length; index++) {
  13931. var light = scene.lights[index];
  13932. if (!light.isEnabled()) {
  13933. continue;
  13934. }
  13935. if (!light.canAffectMesh(mesh)) {
  13936. continue;
  13937. }
  13938. if (light instanceof BABYLON.PointLight) {
  13939. // Point Light
  13940. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13941. }
  13942. else if (light instanceof BABYLON.DirectionalLight) {
  13943. // Directional Light
  13944. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13945. }
  13946. else if (light instanceof BABYLON.SpotLight) {
  13947. // Spot Light
  13948. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  13949. }
  13950. else if (light instanceof BABYLON.HemisphericLight) {
  13951. // Hemispheric Light
  13952. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  13953. }
  13954. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  13955. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  13956. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  13957. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  13958. // Shadows
  13959. if (scene.shadowsEnabled) {
  13960. var shadowGenerator = light.getShadowGenerator();
  13961. if (mesh.receiveShadows && shadowGenerator) {
  13962. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  13963. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  13964. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  13965. }
  13966. }
  13967. lightIndex++;
  13968. if (lightIndex === maxSimultaneousLights)
  13969. break;
  13970. }
  13971. }
  13972. // View
  13973. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  13974. this._effect.setMatrix("view", scene.getViewMatrix());
  13975. }
  13976. // Fog
  13977. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  13978. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  13979. this._effect.setColor3("vFogColor", scene.fogColor);
  13980. }
  13981. _super.prototype.bind.call(this, world, mesh);
  13982. };
  13983. StandardMaterial.prototype.getAnimatables = function () {
  13984. var results = [];
  13985. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  13986. results.push(this.diffuseTexture);
  13987. }
  13988. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  13989. results.push(this.ambientTexture);
  13990. }
  13991. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  13992. results.push(this.opacityTexture);
  13993. }
  13994. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  13995. results.push(this.reflectionTexture);
  13996. }
  13997. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  13998. results.push(this.emissiveTexture);
  13999. }
  14000. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  14001. results.push(this.specularTexture);
  14002. }
  14003. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  14004. results.push(this.bumpTexture);
  14005. }
  14006. return results;
  14007. };
  14008. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  14009. if (this.diffuseTexture) {
  14010. this.diffuseTexture.dispose();
  14011. }
  14012. if (this.ambientTexture) {
  14013. this.ambientTexture.dispose();
  14014. }
  14015. if (this.opacityTexture) {
  14016. this.opacityTexture.dispose();
  14017. }
  14018. if (this.reflectionTexture) {
  14019. this.reflectionTexture.dispose();
  14020. }
  14021. if (this.emissiveTexture) {
  14022. this.emissiveTexture.dispose();
  14023. }
  14024. if (this.specularTexture) {
  14025. this.specularTexture.dispose();
  14026. }
  14027. if (this.bumpTexture) {
  14028. this.bumpTexture.dispose();
  14029. }
  14030. _super.prototype.dispose.call(this, forceDisposeEffect);
  14031. };
  14032. StandardMaterial.prototype.clone = function (name) {
  14033. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  14034. // Base material
  14035. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  14036. newStandardMaterial.alpha = this.alpha;
  14037. newStandardMaterial.fillMode = this.fillMode;
  14038. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  14039. // Standard material
  14040. if (this.diffuseTexture && this.diffuseTexture.clone) {
  14041. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  14042. }
  14043. if (this.ambientTexture && this.ambientTexture.clone) {
  14044. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  14045. }
  14046. if (this.opacityTexture && this.opacityTexture.clone) {
  14047. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  14048. }
  14049. if (this.reflectionTexture && this.reflectionTexture.clone) {
  14050. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  14051. }
  14052. if (this.emissiveTexture && this.emissiveTexture.clone) {
  14053. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  14054. }
  14055. if (this.specularTexture && this.specularTexture.clone) {
  14056. newStandardMaterial.specularTexture = this.specularTexture.clone();
  14057. }
  14058. if (this.bumpTexture && this.bumpTexture.clone) {
  14059. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  14060. }
  14061. newStandardMaterial.ambientColor = this.ambientColor.clone();
  14062. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  14063. newStandardMaterial.specularColor = this.specularColor.clone();
  14064. newStandardMaterial.specularPower = this.specularPower;
  14065. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  14066. return newStandardMaterial;
  14067. };
  14068. // Statics
  14069. // Flags used to enable or disable a type of texture for all Standard Materials
  14070. StandardMaterial.DiffuseTextureEnabled = true;
  14071. StandardMaterial.AmbientTextureEnabled = true;
  14072. StandardMaterial.OpacityTextureEnabled = true;
  14073. StandardMaterial.ReflectionTextureEnabled = true;
  14074. StandardMaterial.EmissiveTextureEnabled = true;
  14075. StandardMaterial.SpecularTextureEnabled = true;
  14076. StandardMaterial.BumpTextureEnabled = true;
  14077. StandardMaterial.FresnelEnabled = true;
  14078. return StandardMaterial;
  14079. })(BABYLON.Material);
  14080. BABYLON.StandardMaterial = StandardMaterial;
  14081. })(BABYLON || (BABYLON = {}));
  14082. //# sourceMappingURL=babylon.standardMaterial.js.map
  14083. var BABYLON;
  14084. (function (BABYLON) {
  14085. var MultiMaterial = (function (_super) {
  14086. __extends(MultiMaterial, _super);
  14087. function MultiMaterial(name, scene) {
  14088. _super.call(this, name, scene, true);
  14089. this.subMaterials = new Array();
  14090. scene.multiMaterials.push(this);
  14091. }
  14092. // Properties
  14093. MultiMaterial.prototype.getSubMaterial = function (index) {
  14094. if (index < 0 || index >= this.subMaterials.length) {
  14095. return this.getScene().defaultMaterial;
  14096. }
  14097. return this.subMaterials[index];
  14098. };
  14099. // Methods
  14100. MultiMaterial.prototype.isReady = function (mesh) {
  14101. for (var index = 0; index < this.subMaterials.length; index++) {
  14102. var subMaterial = this.subMaterials[index];
  14103. if (subMaterial) {
  14104. if (!this.subMaterials[index].isReady(mesh)) {
  14105. return false;
  14106. }
  14107. }
  14108. }
  14109. return true;
  14110. };
  14111. return MultiMaterial;
  14112. })(BABYLON.Material);
  14113. BABYLON.MultiMaterial = MultiMaterial;
  14114. })(BABYLON || (BABYLON = {}));
  14115. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  14116. (function (BABYLON) {
  14117. var Database = (function () {
  14118. function Database(urlToScene, callbackManifestChecked) {
  14119. // Handling various flavors of prefixed version of IndexedDB
  14120. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  14121. this.callbackManifestChecked = callbackManifestChecked;
  14122. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  14123. this.db = null;
  14124. this.enableSceneOffline = false;
  14125. this.enableTexturesOffline = false;
  14126. this.manifestVersionFound = 0;
  14127. this.mustUpdateRessources = false;
  14128. this.hasReachedQuota = false;
  14129. this.checkManifestFile();
  14130. }
  14131. Database.prototype.checkManifestFile = function () {
  14132. var _this = this;
  14133. function noManifestFile() {
  14134. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  14135. that.enableSceneOffline = false;
  14136. that.enableTexturesOffline = false;
  14137. that.callbackManifestChecked(false);
  14138. }
  14139. var that = this;
  14140. var manifestURL = this.currentSceneUrl + ".manifest";
  14141. var xhr = new XMLHttpRequest();
  14142. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  14143. xhr.open("GET", manifestURLTimeStamped, true);
  14144. xhr.addEventListener("load", function () {
  14145. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  14146. try {
  14147. var manifestFile = JSON.parse(xhr.response);
  14148. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  14149. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  14150. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  14151. _this.manifestVersionFound = manifestFile.version;
  14152. }
  14153. if (_this.callbackManifestChecked) {
  14154. _this.callbackManifestChecked(true);
  14155. }
  14156. }
  14157. catch (ex) {
  14158. noManifestFile();
  14159. }
  14160. }
  14161. else {
  14162. noManifestFile();
  14163. }
  14164. }, false);
  14165. xhr.addEventListener("error", function (event) {
  14166. noManifestFile();
  14167. }, false);
  14168. try {
  14169. xhr.send();
  14170. }
  14171. catch (ex) {
  14172. BABYLON.Tools.Error("Error on XHR send request.");
  14173. that.callbackManifestChecked(false);
  14174. }
  14175. };
  14176. Database.prototype.openAsync = function (successCallback, errorCallback) {
  14177. var _this = this;
  14178. function handleError() {
  14179. that.isSupported = false;
  14180. if (errorCallback)
  14181. errorCallback();
  14182. }
  14183. var that = this;
  14184. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  14185. // Your browser doesn't support IndexedDB
  14186. this.isSupported = false;
  14187. if (errorCallback)
  14188. errorCallback();
  14189. }
  14190. else {
  14191. // If the DB hasn't been opened or created yet
  14192. if (!this.db) {
  14193. this.hasReachedQuota = false;
  14194. this.isSupported = true;
  14195. var request = this.idbFactory.open("babylonjs", 1);
  14196. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  14197. request.onerror = function (event) {
  14198. handleError();
  14199. };
  14200. // executes when a version change transaction cannot complete due to other active transactions
  14201. request.onblocked = function (event) {
  14202. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  14203. handleError();
  14204. };
  14205. // DB has been opened successfully
  14206. request.onsuccess = function (event) {
  14207. _this.db = request.result;
  14208. successCallback();
  14209. };
  14210. // Initialization of the DB. Creating Scenes & Textures stores
  14211. request.onupgradeneeded = function (event) {
  14212. _this.db = (event.target).result;
  14213. try {
  14214. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  14215. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  14216. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  14217. }
  14218. catch (ex) {
  14219. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  14220. handleError();
  14221. }
  14222. };
  14223. }
  14224. else {
  14225. if (successCallback)
  14226. successCallback();
  14227. }
  14228. }
  14229. };
  14230. Database.prototype.loadImageFromDB = function (url, image) {
  14231. var _this = this;
  14232. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  14233. var saveAndLoadImage = function () {
  14234. if (!_this.hasReachedQuota && _this.db !== null) {
  14235. // the texture is not yet in the DB, let's try to save it
  14236. _this._saveImageIntoDBAsync(completeURL, image);
  14237. }
  14238. else {
  14239. image.src = url;
  14240. }
  14241. };
  14242. if (!this.mustUpdateRessources) {
  14243. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  14244. }
  14245. else {
  14246. saveAndLoadImage();
  14247. }
  14248. };
  14249. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  14250. if (this.isSupported && this.db !== null) {
  14251. var texture;
  14252. var transaction = this.db.transaction(["textures"]);
  14253. transaction.onabort = function (event) {
  14254. image.src = url;
  14255. };
  14256. transaction.oncomplete = function (event) {
  14257. var blobTextureURL;
  14258. if (texture) {
  14259. var URL = window.URL || window.webkitURL;
  14260. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  14261. image.onerror = function () {
  14262. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  14263. image.src = url;
  14264. };
  14265. image.src = blobTextureURL;
  14266. }
  14267. else {
  14268. notInDBCallback();
  14269. }
  14270. };
  14271. var getRequest = transaction.objectStore("textures").get(url);
  14272. getRequest.onsuccess = function (event) {
  14273. texture = (event.target).result;
  14274. };
  14275. getRequest.onerror = function (event) {
  14276. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  14277. image.src = url;
  14278. };
  14279. }
  14280. else {
  14281. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14282. image.src = url;
  14283. }
  14284. };
  14285. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  14286. var _this = this;
  14287. if (this.isSupported) {
  14288. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  14289. var generateBlobUrl = function () {
  14290. var blobTextureURL;
  14291. if (blob) {
  14292. var URL = window.URL || window.webkitURL;
  14293. try {
  14294. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  14295. }
  14296. catch (ex) {
  14297. blobTextureURL = URL.createObjectURL(blob);
  14298. }
  14299. }
  14300. image.src = blobTextureURL;
  14301. };
  14302. if (BABYLON.Database.isUASupportingBlobStorage) {
  14303. var xhr = new XMLHttpRequest(), blob;
  14304. xhr.open("GET", url, true);
  14305. xhr.responseType = "blob";
  14306. xhr.addEventListener("load", function () {
  14307. if (xhr.status === 200) {
  14308. // Blob as response (XHR2)
  14309. blob = xhr.response;
  14310. var transaction = _this.db.transaction(["textures"], "readwrite");
  14311. // the transaction could abort because of a QuotaExceededError error
  14312. transaction.onabort = function (event) {
  14313. try {
  14314. if (event.srcElement.error.name === "QuotaExceededError") {
  14315. this.hasReachedQuota = true;
  14316. }
  14317. }
  14318. catch (ex) {
  14319. }
  14320. generateBlobUrl();
  14321. };
  14322. transaction.oncomplete = function (event) {
  14323. generateBlobUrl();
  14324. };
  14325. var newTexture = { textureUrl: url, data: blob };
  14326. try {
  14327. // Put the blob into the dabase
  14328. var addRequest = transaction.objectStore("textures").put(newTexture);
  14329. addRequest.onsuccess = function (event) {
  14330. };
  14331. addRequest.onerror = function (event) {
  14332. generateBlobUrl();
  14333. };
  14334. }
  14335. catch (ex) {
  14336. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  14337. if (ex.code === 25) {
  14338. BABYLON.Database.isUASupportingBlobStorage = false;
  14339. }
  14340. image.src = url;
  14341. }
  14342. }
  14343. else {
  14344. image.src = url;
  14345. }
  14346. }, false);
  14347. xhr.addEventListener("error", function (event) {
  14348. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  14349. image.src = url;
  14350. }, false);
  14351. xhr.send();
  14352. }
  14353. else {
  14354. image.src = url;
  14355. }
  14356. }
  14357. else {
  14358. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14359. image.src = url;
  14360. }
  14361. };
  14362. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  14363. var _this = this;
  14364. var updateVersion = function (event) {
  14365. // the version is not yet in the DB or we need to update it
  14366. _this._saveVersionIntoDBAsync(url, versionLoaded);
  14367. };
  14368. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  14369. };
  14370. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  14371. var _this = this;
  14372. if (this.isSupported) {
  14373. var version;
  14374. try {
  14375. var transaction = this.db.transaction(["versions"]);
  14376. transaction.oncomplete = function (event) {
  14377. if (version) {
  14378. // If the version in the JSON file is > than the version in DB
  14379. if (_this.manifestVersionFound > version.data) {
  14380. _this.mustUpdateRessources = true;
  14381. updateInDBCallback();
  14382. }
  14383. else {
  14384. callback(version.data);
  14385. }
  14386. }
  14387. else {
  14388. _this.mustUpdateRessources = true;
  14389. updateInDBCallback();
  14390. }
  14391. };
  14392. transaction.onabort = function (event) {
  14393. callback(-1);
  14394. };
  14395. var getRequest = transaction.objectStore("versions").get(url);
  14396. getRequest.onsuccess = function (event) {
  14397. version = (event.target).result;
  14398. };
  14399. getRequest.onerror = function (event) {
  14400. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  14401. callback(-1);
  14402. };
  14403. }
  14404. catch (ex) {
  14405. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  14406. callback(-1);
  14407. }
  14408. }
  14409. else {
  14410. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14411. callback(-1);
  14412. }
  14413. };
  14414. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  14415. var _this = this;
  14416. if (this.isSupported && !this.hasReachedQuota) {
  14417. try {
  14418. // Open a transaction to the database
  14419. var transaction = this.db.transaction(["versions"], "readwrite");
  14420. // the transaction could abort because of a QuotaExceededError error
  14421. transaction.onabort = function (event) {
  14422. try {
  14423. if (event.srcElement.error.name === "QuotaExceededError") {
  14424. _this.hasReachedQuota = true;
  14425. }
  14426. }
  14427. catch (ex) {
  14428. }
  14429. callback(-1);
  14430. };
  14431. transaction.oncomplete = function (event) {
  14432. callback(_this.manifestVersionFound);
  14433. };
  14434. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  14435. // Put the scene into the database
  14436. var addRequest = transaction.objectStore("versions").put(newVersion);
  14437. addRequest.onsuccess = function (event) {
  14438. };
  14439. addRequest.onerror = function (event) {
  14440. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  14441. };
  14442. }
  14443. catch (ex) {
  14444. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  14445. callback(-1);
  14446. }
  14447. }
  14448. else {
  14449. callback(-1);
  14450. }
  14451. };
  14452. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  14453. var _this = this;
  14454. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  14455. var saveAndLoadFile = function (event) {
  14456. // the scene is not yet in the DB, let's try to save it
  14457. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  14458. };
  14459. this._checkVersionFromDB(completeUrl, function (version) {
  14460. if (version !== -1) {
  14461. if (!_this.mustUpdateRessources) {
  14462. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  14463. }
  14464. else {
  14465. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  14466. }
  14467. }
  14468. else {
  14469. errorCallback();
  14470. }
  14471. });
  14472. };
  14473. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  14474. if (this.isSupported) {
  14475. var targetStore;
  14476. if (url.indexOf(".babylon") !== -1) {
  14477. targetStore = "scenes";
  14478. }
  14479. else {
  14480. targetStore = "textures";
  14481. }
  14482. var file;
  14483. var transaction = this.db.transaction([targetStore]);
  14484. transaction.oncomplete = function (event) {
  14485. if (file) {
  14486. callback(file.data);
  14487. }
  14488. else {
  14489. notInDBCallback();
  14490. }
  14491. };
  14492. transaction.onabort = function (event) {
  14493. notInDBCallback();
  14494. };
  14495. var getRequest = transaction.objectStore(targetStore).get(url);
  14496. getRequest.onsuccess = function (event) {
  14497. file = (event.target).result;
  14498. };
  14499. getRequest.onerror = function (event) {
  14500. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  14501. notInDBCallback();
  14502. };
  14503. }
  14504. else {
  14505. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14506. callback();
  14507. }
  14508. };
  14509. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  14510. var _this = this;
  14511. if (this.isSupported) {
  14512. var targetStore;
  14513. if (url.indexOf(".babylon") !== -1) {
  14514. targetStore = "scenes";
  14515. }
  14516. else {
  14517. targetStore = "textures";
  14518. }
  14519. // Create XHR
  14520. var xhr = new XMLHttpRequest(), fileData;
  14521. xhr.open("GET", url, true);
  14522. if (useArrayBuffer) {
  14523. xhr.responseType = "arraybuffer";
  14524. }
  14525. xhr.onprogress = progressCallback;
  14526. xhr.addEventListener("load", function () {
  14527. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  14528. // Blob as response (XHR2)
  14529. //fileData = xhr.responseText;
  14530. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  14531. if (!_this.hasReachedQuota) {
  14532. // Open a transaction to the database
  14533. var transaction = _this.db.transaction([targetStore], "readwrite");
  14534. // the transaction could abort because of a QuotaExceededError error
  14535. transaction.onabort = function (event) {
  14536. try {
  14537. if (event.srcElement.error.name === "QuotaExceededError") {
  14538. this.hasReachedQuota = true;
  14539. }
  14540. }
  14541. catch (ex) {
  14542. }
  14543. callback(fileData);
  14544. };
  14545. transaction.oncomplete = function (event) {
  14546. callback(fileData);
  14547. };
  14548. var newFile;
  14549. if (targetStore === "scenes") {
  14550. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  14551. }
  14552. else {
  14553. newFile = { textureUrl: url, data: fileData };
  14554. }
  14555. try {
  14556. // Put the scene into the database
  14557. var addRequest = transaction.objectStore(targetStore).put(newFile);
  14558. addRequest.onsuccess = function (event) {
  14559. };
  14560. addRequest.onerror = function (event) {
  14561. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  14562. };
  14563. }
  14564. catch (ex) {
  14565. callback(fileData);
  14566. }
  14567. }
  14568. else {
  14569. callback(fileData);
  14570. }
  14571. }
  14572. else {
  14573. callback();
  14574. }
  14575. }, false);
  14576. xhr.addEventListener("error", function (event) {
  14577. BABYLON.Tools.Error("error on XHR request.");
  14578. callback();
  14579. }, false);
  14580. xhr.send();
  14581. }
  14582. else {
  14583. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14584. callback();
  14585. }
  14586. };
  14587. Database.isUASupportingBlobStorage = true;
  14588. Database.parseURL = function (url) {
  14589. var a = document.createElement('a');
  14590. a.href = url;
  14591. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  14592. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  14593. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  14594. return absLocation;
  14595. };
  14596. Database.ReturnFullUrlLocation = function (url) {
  14597. if (url.indexOf("http:/") === -1) {
  14598. return (BABYLON.Database.parseURL(window.location.href) + url);
  14599. }
  14600. else {
  14601. return url;
  14602. }
  14603. };
  14604. return Database;
  14605. })();
  14606. BABYLON.Database = Database;
  14607. })(BABYLON || (BABYLON = {}));
  14608. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  14609. (function (BABYLON) {
  14610. var SpriteManager = (function () {
  14611. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  14612. this.name = name;
  14613. this.cellSize = cellSize;
  14614. this.sprites = new Array();
  14615. this.renderingGroupId = 0;
  14616. this.fogEnabled = true;
  14617. this._vertexDeclaration = [3, 4, 4, 4];
  14618. this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  14619. this._capacity = capacity;
  14620. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  14621. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14622. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14623. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  14624. this._scene = scene;
  14625. this._scene.spriteManagers.push(this);
  14626. // VBO
  14627. this._vertexDeclaration = [3, 4, 4, 4];
  14628. this._vertexStrideSize = 15 * 4;
  14629. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14630. var indices = [];
  14631. var index = 0;
  14632. for (var count = 0; count < capacity; count++) {
  14633. indices.push(index);
  14634. indices.push(index + 1);
  14635. indices.push(index + 2);
  14636. indices.push(index);
  14637. indices.push(index + 2);
  14638. indices.push(index + 3);
  14639. index += 4;
  14640. }
  14641. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14642. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14643. // Effects
  14644. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  14645. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  14646. }
  14647. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  14648. var arrayOffset = index * 15;
  14649. if (offsetX == 0)
  14650. offsetX = this._epsilon;
  14651. else if (offsetX == 1)
  14652. offsetX = 1 - this._epsilon;
  14653. if (offsetY == 0)
  14654. offsetY = this._epsilon;
  14655. else if (offsetY == 1)
  14656. offsetY = 1 - this._epsilon;
  14657. this._vertices[arrayOffset] = sprite.position.x;
  14658. this._vertices[arrayOffset + 1] = sprite.position.y;
  14659. this._vertices[arrayOffset + 2] = sprite.position.z;
  14660. this._vertices[arrayOffset + 3] = sprite.angle;
  14661. this._vertices[arrayOffset + 4] = sprite.size;
  14662. this._vertices[arrayOffset + 5] = offsetX;
  14663. this._vertices[arrayOffset + 6] = offsetY;
  14664. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  14665. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  14666. var offset = (sprite.cellIndex / rowSize) >> 0;
  14667. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  14668. this._vertices[arrayOffset + 10] = offset;
  14669. // Color
  14670. this._vertices[arrayOffset + 11] = sprite.color.r;
  14671. this._vertices[arrayOffset + 12] = sprite.color.g;
  14672. this._vertices[arrayOffset + 13] = sprite.color.b;
  14673. this._vertices[arrayOffset + 14] = sprite.color.a;
  14674. };
  14675. SpriteManager.prototype.render = function () {
  14676. // Check
  14677. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  14678. return;
  14679. var engine = this._scene.getEngine();
  14680. var baseSize = this._spriteTexture.getBaseSize();
  14681. // Sprites
  14682. var deltaTime = engine.getDeltaTime();
  14683. var max = Math.min(this._capacity, this.sprites.length);
  14684. var rowSize = baseSize.width / this.cellSize;
  14685. var offset = 0;
  14686. for (var index = 0; index < max; index++) {
  14687. var sprite = this.sprites[index];
  14688. if (!sprite) {
  14689. continue;
  14690. }
  14691. sprite._animate(deltaTime);
  14692. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  14693. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  14694. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  14695. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  14696. }
  14697. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14698. // Render
  14699. var effect = this._effectBase;
  14700. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14701. effect = this._effectFog;
  14702. }
  14703. engine.enableEffect(effect);
  14704. var viewMatrix = this._scene.getViewMatrix();
  14705. effect.setTexture("diffuseSampler", this._spriteTexture);
  14706. effect.setMatrix("view", viewMatrix);
  14707. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14708. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  14709. // Fog
  14710. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14711. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  14712. effect.setColor3("vFogColor", this._scene.fogColor);
  14713. }
  14714. // VBOs
  14715. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14716. // Draw order
  14717. effect.setBool("alphaTest", true);
  14718. engine.setColorWrite(false);
  14719. engine.draw(true, 0, max * 6);
  14720. engine.setColorWrite(true);
  14721. effect.setBool("alphaTest", false);
  14722. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14723. engine.draw(true, 0, max * 6);
  14724. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14725. };
  14726. SpriteManager.prototype.dispose = function () {
  14727. if (this._vertexBuffer) {
  14728. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14729. this._vertexBuffer = null;
  14730. }
  14731. if (this._indexBuffer) {
  14732. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14733. this._indexBuffer = null;
  14734. }
  14735. if (this._spriteTexture) {
  14736. this._spriteTexture.dispose();
  14737. this._spriteTexture = null;
  14738. }
  14739. // Remove from scene
  14740. var index = this._scene.spriteManagers.indexOf(this);
  14741. this._scene.spriteManagers.splice(index, 1);
  14742. // Callback
  14743. if (this.onDispose) {
  14744. this.onDispose();
  14745. }
  14746. };
  14747. return SpriteManager;
  14748. })();
  14749. BABYLON.SpriteManager = SpriteManager;
  14750. })(BABYLON || (BABYLON = {}));
  14751. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  14752. (function (BABYLON) {
  14753. var Sprite = (function () {
  14754. function Sprite(name, manager) {
  14755. this.name = name;
  14756. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14757. this.size = 1.0;
  14758. this.angle = 0;
  14759. this.cellIndex = 0;
  14760. this.invertU = 0;
  14761. this.invertV = 0;
  14762. this.animations = new Array();
  14763. this._animationStarted = false;
  14764. this._loopAnimation = false;
  14765. this._fromIndex = 0;
  14766. this._toIndex = 0;
  14767. this._delay = 0;
  14768. this._direction = 1;
  14769. this._frameCount = 0;
  14770. this._time = 0;
  14771. this._manager = manager;
  14772. this._manager.sprites.push(this);
  14773. this.position = BABYLON.Vector3.Zero();
  14774. }
  14775. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  14776. this._fromIndex = from;
  14777. this._toIndex = to;
  14778. this._loopAnimation = loop;
  14779. this._delay = delay;
  14780. this._animationStarted = true;
  14781. this._direction = from < to ? 1 : -1;
  14782. this.cellIndex = from;
  14783. this._time = 0;
  14784. };
  14785. Sprite.prototype.stopAnimation = function () {
  14786. this._animationStarted = false;
  14787. };
  14788. Sprite.prototype._animate = function (deltaTime) {
  14789. if (!this._animationStarted)
  14790. return;
  14791. this._time += deltaTime;
  14792. if (this._time > this._delay) {
  14793. this._time = this._time % this._delay;
  14794. this.cellIndex += this._direction;
  14795. if (this.cellIndex == this._toIndex) {
  14796. if (this._loopAnimation) {
  14797. this.cellIndex = this._fromIndex;
  14798. }
  14799. else {
  14800. this._animationStarted = false;
  14801. if (this.disposeWhenFinishedAnimating) {
  14802. this.dispose();
  14803. }
  14804. }
  14805. }
  14806. }
  14807. };
  14808. Sprite.prototype.dispose = function () {
  14809. for (var i = 0; i < this._manager.sprites.length; i++) {
  14810. if (this._manager.sprites[i] == this) {
  14811. this._manager.sprites.splice(i, 1);
  14812. }
  14813. }
  14814. };
  14815. return Sprite;
  14816. })();
  14817. BABYLON.Sprite = Sprite;
  14818. })(BABYLON || (BABYLON = {}));
  14819. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  14820. (function (BABYLON) {
  14821. var Layer = (function () {
  14822. function Layer(name, imgUrl, scene, isBackground, color) {
  14823. this.name = name;
  14824. this._vertexDeclaration = [2];
  14825. this._vertexStrideSize = 2 * 4;
  14826. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  14827. this.isBackground = isBackground === undefined ? true : isBackground;
  14828. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  14829. this._scene = scene;
  14830. this._scene.layers.push(this);
  14831. // VBO
  14832. var vertices = [];
  14833. vertices.push(1, 1);
  14834. vertices.push(-1, 1);
  14835. vertices.push(-1, -1);
  14836. vertices.push(1, -1);
  14837. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14838. // Indices
  14839. var indices = [];
  14840. indices.push(0);
  14841. indices.push(1);
  14842. indices.push(2);
  14843. indices.push(0);
  14844. indices.push(2);
  14845. indices.push(3);
  14846. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14847. // Effects
  14848. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  14849. }
  14850. Layer.prototype.render = function () {
  14851. // Check
  14852. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  14853. return;
  14854. var engine = this._scene.getEngine();
  14855. // Render
  14856. engine.enableEffect(this._effect);
  14857. engine.setState(false);
  14858. // Texture
  14859. this._effect.setTexture("textureSampler", this.texture);
  14860. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  14861. // Color
  14862. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  14863. // VBOs
  14864. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  14865. // Draw order
  14866. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14867. engine.draw(true, 0, 6);
  14868. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14869. };
  14870. Layer.prototype.dispose = function () {
  14871. if (this._vertexBuffer) {
  14872. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14873. this._vertexBuffer = null;
  14874. }
  14875. if (this._indexBuffer) {
  14876. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14877. this._indexBuffer = null;
  14878. }
  14879. if (this.texture) {
  14880. this.texture.dispose();
  14881. this.texture = null;
  14882. }
  14883. // Remove from scene
  14884. var index = this._scene.layers.indexOf(this);
  14885. this._scene.layers.splice(index, 1);
  14886. // Callback
  14887. if (this.onDispose) {
  14888. this.onDispose();
  14889. }
  14890. };
  14891. return Layer;
  14892. })();
  14893. BABYLON.Layer = Layer;
  14894. })(BABYLON || (BABYLON = {}));
  14895. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  14896. (function (BABYLON) {
  14897. var Particle = (function () {
  14898. function Particle() {
  14899. this.position = BABYLON.Vector3.Zero();
  14900. this.direction = BABYLON.Vector3.Zero();
  14901. this.color = new BABYLON.Color4(0, 0, 0, 0);
  14902. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  14903. this.lifeTime = 1.0;
  14904. this.age = 0;
  14905. this.size = 0;
  14906. this.angle = 0;
  14907. this.angularSpeed = 0;
  14908. }
  14909. Particle.prototype.copyTo = function (other) {
  14910. other.position.copyFrom(this.position);
  14911. other.direction.copyFrom(this.direction);
  14912. other.color.copyFrom(this.color);
  14913. other.colorStep.copyFrom(this.colorStep);
  14914. other.lifeTime = this.lifeTime;
  14915. other.age = this.age;
  14916. other.size = this.size;
  14917. other.angle = this.angle;
  14918. other.angularSpeed = this.angularSpeed;
  14919. };
  14920. return Particle;
  14921. })();
  14922. BABYLON.Particle = Particle;
  14923. })(BABYLON || (BABYLON = {}));
  14924. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  14925. (function (BABYLON) {
  14926. var randomNumber = function (min, max) {
  14927. if (min === max) {
  14928. return (min);
  14929. }
  14930. var random = Math.random();
  14931. return ((random * (max - min)) + min);
  14932. };
  14933. var ParticleSystem = (function () {
  14934. function ParticleSystem(name, capacity, scene, customEffect) {
  14935. var _this = this;
  14936. this.name = name;
  14937. this.renderingGroupId = 0;
  14938. this.emitter = null;
  14939. this.emitRate = 10;
  14940. this.manualEmitCount = -1;
  14941. this.updateSpeed = 0.01;
  14942. this.targetStopDuration = 0;
  14943. this.disposeOnStop = false;
  14944. this.minEmitPower = 1;
  14945. this.maxEmitPower = 1;
  14946. this.minLifeTime = 1;
  14947. this.maxLifeTime = 1;
  14948. this.minSize = 1;
  14949. this.maxSize = 1;
  14950. this.minAngularSpeed = 0;
  14951. this.maxAngularSpeed = 0;
  14952. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  14953. this.forceDepthWrite = false;
  14954. this.gravity = BABYLON.Vector3.Zero();
  14955. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  14956. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  14957. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  14958. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14959. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14960. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14961. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  14962. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14963. this.particles = new Array();
  14964. this._vertexDeclaration = [3, 4, 4];
  14965. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  14966. this._stockParticles = new Array();
  14967. this._newPartsExcess = 0;
  14968. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  14969. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  14970. this._scaledDirection = BABYLON.Vector3.Zero();
  14971. this._scaledGravity = BABYLON.Vector3.Zero();
  14972. this._currentRenderId = -1;
  14973. this._started = false;
  14974. this._stopped = false;
  14975. this._actualFrame = 0;
  14976. this.id = name;
  14977. this._capacity = capacity;
  14978. this._scene = scene;
  14979. this._customEffect = customEffect;
  14980. scene.particleSystems.push(this);
  14981. // VBO
  14982. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14983. var indices = [];
  14984. var index = 0;
  14985. for (var count = 0; count < capacity; count++) {
  14986. indices.push(index);
  14987. indices.push(index + 1);
  14988. indices.push(index + 2);
  14989. indices.push(index);
  14990. indices.push(index + 2);
  14991. indices.push(index + 3);
  14992. index += 4;
  14993. }
  14994. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14995. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14996. // Default behaviors
  14997. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  14998. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  14999. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  15000. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  15001. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  15002. };
  15003. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  15004. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  15005. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  15006. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  15007. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  15008. };
  15009. this.updateFunction = function (particles) {
  15010. for (var index = 0; index < particles.length; index++) {
  15011. var particle = particles[index];
  15012. particle.age += _this._scaledUpdateSpeed;
  15013. if (particle.age >= particle.lifeTime) {
  15014. _this.recycleParticle(particle);
  15015. index--;
  15016. continue;
  15017. }
  15018. else {
  15019. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  15020. particle.color.addInPlace(_this._scaledColorStep);
  15021. if (particle.color.a < 0)
  15022. particle.color.a = 0;
  15023. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  15024. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  15025. particle.position.addInPlace(_this._scaledDirection);
  15026. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  15027. particle.direction.addInPlace(_this._scaledGravity);
  15028. }
  15029. }
  15030. };
  15031. }
  15032. ParticleSystem.prototype.recycleParticle = function (particle) {
  15033. var lastParticle = this.particles.pop();
  15034. if (lastParticle !== particle) {
  15035. lastParticle.copyTo(particle);
  15036. this._stockParticles.push(lastParticle);
  15037. }
  15038. };
  15039. ParticleSystem.prototype.getCapacity = function () {
  15040. return this._capacity;
  15041. };
  15042. ParticleSystem.prototype.isAlive = function () {
  15043. return this._alive;
  15044. };
  15045. ParticleSystem.prototype.isStarted = function () {
  15046. return this._started;
  15047. };
  15048. ParticleSystem.prototype.start = function () {
  15049. this._started = true;
  15050. this._stopped = false;
  15051. this._actualFrame = 0;
  15052. };
  15053. ParticleSystem.prototype.stop = function () {
  15054. this._stopped = true;
  15055. };
  15056. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  15057. var offset = index * 11;
  15058. this._vertices[offset] = particle.position.x;
  15059. this._vertices[offset + 1] = particle.position.y;
  15060. this._vertices[offset + 2] = particle.position.z;
  15061. this._vertices[offset + 3] = particle.color.r;
  15062. this._vertices[offset + 4] = particle.color.g;
  15063. this._vertices[offset + 5] = particle.color.b;
  15064. this._vertices[offset + 6] = particle.color.a;
  15065. this._vertices[offset + 7] = particle.angle;
  15066. this._vertices[offset + 8] = particle.size;
  15067. this._vertices[offset + 9] = offsetX;
  15068. this._vertices[offset + 10] = offsetY;
  15069. };
  15070. ParticleSystem.prototype._update = function (newParticles) {
  15071. // Update current
  15072. this._alive = this.particles.length > 0;
  15073. this.updateFunction(this.particles);
  15074. // Add new ones
  15075. var worldMatrix;
  15076. if (this.emitter.position) {
  15077. worldMatrix = this.emitter.getWorldMatrix();
  15078. }
  15079. else {
  15080. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  15081. }
  15082. for (var index = 0; index < newParticles; index++) {
  15083. if (this.particles.length === this._capacity) {
  15084. break;
  15085. }
  15086. if (this._stockParticles.length !== 0) {
  15087. var particle = this._stockParticles.pop();
  15088. particle.age = 0;
  15089. }
  15090. else {
  15091. particle = new BABYLON.Particle();
  15092. }
  15093. this.particles.push(particle);
  15094. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  15095. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  15096. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  15097. particle.size = randomNumber(this.minSize, this.maxSize);
  15098. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  15099. this.startPositionFunction(worldMatrix, particle.position);
  15100. var step = randomNumber(0, 1.0);
  15101. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  15102. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  15103. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  15104. }
  15105. };
  15106. ParticleSystem.prototype._getEffect = function () {
  15107. if (this._customEffect) {
  15108. return this._customEffect;
  15109. }
  15110. ;
  15111. var defines = [];
  15112. if (this._scene.clipPlane) {
  15113. defines.push("#define CLIPPLANE");
  15114. }
  15115. // Effect
  15116. var join = defines.join("\n");
  15117. if (this._cachedDefines !== join) {
  15118. this._cachedDefines = join;
  15119. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  15120. }
  15121. return this._effect;
  15122. };
  15123. ParticleSystem.prototype.animate = function () {
  15124. if (!this._started)
  15125. return;
  15126. var effect = this._getEffect();
  15127. // Check
  15128. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  15129. return;
  15130. if (this._currentRenderId === this._scene.getRenderId()) {
  15131. return;
  15132. }
  15133. this._currentRenderId = this._scene.getRenderId();
  15134. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  15135. // determine the number of particles we need to create
  15136. var emitCout;
  15137. if (this.manualEmitCount > -1) {
  15138. emitCout = this.manualEmitCount;
  15139. this.manualEmitCount = 0;
  15140. }
  15141. else {
  15142. emitCout = this.emitRate;
  15143. }
  15144. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  15145. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  15146. if (this._newPartsExcess > 1.0) {
  15147. newParticles += this._newPartsExcess >> 0;
  15148. this._newPartsExcess -= this._newPartsExcess >> 0;
  15149. }
  15150. this._alive = false;
  15151. if (!this._stopped) {
  15152. this._actualFrame += this._scaledUpdateSpeed;
  15153. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  15154. this.stop();
  15155. }
  15156. else {
  15157. newParticles = 0;
  15158. }
  15159. this._update(newParticles);
  15160. // Stopped?
  15161. if (this._stopped) {
  15162. if (!this._alive) {
  15163. this._started = false;
  15164. if (this.disposeOnStop) {
  15165. this._scene._toBeDisposed.push(this);
  15166. }
  15167. }
  15168. }
  15169. // Update VBO
  15170. var offset = 0;
  15171. for (var index = 0; index < this.particles.length; index++) {
  15172. var particle = this.particles[index];
  15173. this._appendParticleVertex(offset++, particle, 0, 0);
  15174. this._appendParticleVertex(offset++, particle, 1, 0);
  15175. this._appendParticleVertex(offset++, particle, 1, 1);
  15176. this._appendParticleVertex(offset++, particle, 0, 1);
  15177. }
  15178. var engine = this._scene.getEngine();
  15179. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15180. };
  15181. ParticleSystem.prototype.render = function () {
  15182. var effect = this._getEffect();
  15183. // Check
  15184. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  15185. return 0;
  15186. var engine = this._scene.getEngine();
  15187. // Render
  15188. engine.enableEffect(effect);
  15189. engine.setState(false);
  15190. var viewMatrix = this._scene.getViewMatrix();
  15191. effect.setTexture("diffuseSampler", this.particleTexture);
  15192. effect.setMatrix("view", viewMatrix);
  15193. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15194. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  15195. if (this._scene.clipPlane) {
  15196. var clipPlane = this._scene.clipPlane;
  15197. var invView = viewMatrix.clone();
  15198. invView.invert();
  15199. effect.setMatrix("invView", invView);
  15200. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15201. }
  15202. // VBOs
  15203. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15204. // Draw order
  15205. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  15206. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15207. }
  15208. else {
  15209. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15210. }
  15211. if (this.forceDepthWrite) {
  15212. engine.setDepthWrite(true);
  15213. }
  15214. engine.draw(true, 0, this.particles.length * 6);
  15215. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15216. return this.particles.length;
  15217. };
  15218. ParticleSystem.prototype.dispose = function () {
  15219. if (this._vertexBuffer) {
  15220. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15221. this._vertexBuffer = null;
  15222. }
  15223. if (this._indexBuffer) {
  15224. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15225. this._indexBuffer = null;
  15226. }
  15227. if (this.particleTexture) {
  15228. this.particleTexture.dispose();
  15229. this.particleTexture = null;
  15230. }
  15231. // Remove from scene
  15232. var index = this._scene.particleSystems.indexOf(this);
  15233. this._scene.particleSystems.splice(index, 1);
  15234. // Callback
  15235. if (this.onDispose) {
  15236. this.onDispose();
  15237. }
  15238. };
  15239. // Clone
  15240. ParticleSystem.prototype.clone = function (name, newEmitter) {
  15241. var result = new ParticleSystem(name, this._capacity, this._scene);
  15242. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  15243. if (newEmitter === undefined) {
  15244. newEmitter = this.emitter;
  15245. }
  15246. result.emitter = newEmitter;
  15247. if (this.particleTexture) {
  15248. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  15249. }
  15250. result.start();
  15251. return result;
  15252. };
  15253. // Statics
  15254. ParticleSystem.BLENDMODE_ONEONE = 0;
  15255. ParticleSystem.BLENDMODE_STANDARD = 1;
  15256. return ParticleSystem;
  15257. })();
  15258. BABYLON.ParticleSystem = ParticleSystem;
  15259. })(BABYLON || (BABYLON = {}));
  15260. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  15261. (function (BABYLON) {
  15262. var Animation = (function () {
  15263. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  15264. this.name = name;
  15265. this.targetProperty = targetProperty;
  15266. this.framePerSecond = framePerSecond;
  15267. this.dataType = dataType;
  15268. this.loopMode = loopMode;
  15269. this._offsetsCache = {};
  15270. this._highLimitsCache = {};
  15271. this._stopped = false;
  15272. this.targetPropertyPath = targetProperty.split(".");
  15273. this.dataType = dataType;
  15274. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  15275. }
  15276. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  15277. var dataType = undefined;
  15278. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  15279. dataType = Animation.ANIMATIONTYPE_FLOAT;
  15280. }
  15281. else if (from instanceof BABYLON.Quaternion) {
  15282. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  15283. }
  15284. else if (from instanceof BABYLON.Vector3) {
  15285. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  15286. }
  15287. else if (from instanceof BABYLON.Vector2) {
  15288. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  15289. }
  15290. else if (from instanceof BABYLON.Color3) {
  15291. dataType = Animation.ANIMATIONTYPE_COLOR3;
  15292. }
  15293. if (dataType == undefined) {
  15294. return;
  15295. }
  15296. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  15297. var keys = [];
  15298. keys.push({ frame: 0, value: from });
  15299. keys.push({ frame: totalFrame, value: to });
  15300. animation.setKeys(keys);
  15301. mesh.animations.push(animation);
  15302. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  15303. };
  15304. // Methods
  15305. Animation.prototype.isStopped = function () {
  15306. return this._stopped;
  15307. };
  15308. Animation.prototype.getKeys = function () {
  15309. return this._keys;
  15310. };
  15311. Animation.prototype.getEasingFunction = function () {
  15312. return this._easingFunction;
  15313. };
  15314. Animation.prototype.setEasingFunction = function (easingFunction) {
  15315. this._easingFunction = easingFunction;
  15316. };
  15317. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  15318. return startValue + (endValue - startValue) * gradient;
  15319. };
  15320. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  15321. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  15322. };
  15323. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  15324. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  15325. };
  15326. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  15327. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  15328. };
  15329. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  15330. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  15331. };
  15332. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  15333. var startScale = new BABYLON.Vector3(0, 0, 0);
  15334. var startRotation = new BABYLON.Quaternion();
  15335. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  15336. startValue.decompose(startScale, startRotation, startTranslation);
  15337. var endScale = new BABYLON.Vector3(0, 0, 0);
  15338. var endRotation = new BABYLON.Quaternion();
  15339. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  15340. endValue.decompose(endScale, endRotation, endTranslation);
  15341. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  15342. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  15343. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  15344. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  15345. return result;
  15346. };
  15347. Animation.prototype.clone = function () {
  15348. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  15349. clone.setKeys(this._keys);
  15350. return clone;
  15351. };
  15352. Animation.prototype.setKeys = function (values) {
  15353. this._keys = values.slice(0);
  15354. this._offsetsCache = {};
  15355. this._highLimitsCache = {};
  15356. };
  15357. Animation.prototype._getKeyValue = function (value) {
  15358. if (typeof value === "function") {
  15359. return value();
  15360. }
  15361. return value;
  15362. };
  15363. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  15364. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  15365. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  15366. }
  15367. this.currentFrame = currentFrame;
  15368. for (var key = 0; key < this._keys.length; key++) {
  15369. // for each frame, we need the key just before the frame superior
  15370. if (this._keys[key + 1].frame >= currentFrame) {
  15371. var startValue = this._getKeyValue(this._keys[key].value);
  15372. var endValue = this._getKeyValue(this._keys[key + 1].value);
  15373. // gradient : percent of currentFrame between the frame inf and the frame sup
  15374. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  15375. // check for easingFunction and correction of gradient
  15376. if (this._easingFunction != null) {
  15377. gradient = this._easingFunction.ease(gradient);
  15378. }
  15379. switch (this.dataType) {
  15380. case Animation.ANIMATIONTYPE_FLOAT:
  15381. switch (loopMode) {
  15382. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15383. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15384. return this.floatInterpolateFunction(startValue, endValue, gradient);
  15385. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15386. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  15387. }
  15388. break;
  15389. case Animation.ANIMATIONTYPE_QUATERNION:
  15390. var quaternion = null;
  15391. switch (loopMode) {
  15392. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15393. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15394. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  15395. break;
  15396. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15397. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15398. break;
  15399. }
  15400. return quaternion;
  15401. case Animation.ANIMATIONTYPE_VECTOR3:
  15402. switch (loopMode) {
  15403. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15404. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15405. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  15406. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15407. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15408. }
  15409. case Animation.ANIMATIONTYPE_VECTOR2:
  15410. switch (loopMode) {
  15411. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15412. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15413. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  15414. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15415. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15416. }
  15417. case Animation.ANIMATIONTYPE_COLOR3:
  15418. switch (loopMode) {
  15419. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15420. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15421. return this.color3InterpolateFunction(startValue, endValue, gradient);
  15422. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15423. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15424. }
  15425. case Animation.ANIMATIONTYPE_MATRIX:
  15426. switch (loopMode) {
  15427. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15428. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15429. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15430. return startValue;
  15431. }
  15432. default:
  15433. break;
  15434. }
  15435. break;
  15436. }
  15437. }
  15438. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  15439. };
  15440. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  15441. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  15442. this._stopped = true;
  15443. return false;
  15444. }
  15445. var returnValue = true;
  15446. // Adding a start key at frame 0 if missing
  15447. if (this._keys[0].frame !== 0) {
  15448. var newKey = { frame: 0, value: this._keys[0].value };
  15449. this._keys.splice(0, 0, newKey);
  15450. }
  15451. // Check limits
  15452. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  15453. from = this._keys[0].frame;
  15454. }
  15455. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  15456. to = this._keys[this._keys.length - 1].frame;
  15457. }
  15458. // Compute ratio
  15459. var range = to - from;
  15460. var offsetValue;
  15461. // ratio represents the frame delta between from and to
  15462. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  15463. var highLimitValue = 0;
  15464. if (ratio > range && !loop) {
  15465. returnValue = false;
  15466. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  15467. }
  15468. else {
  15469. // Get max value if required
  15470. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  15471. var keyOffset = to.toString() + from.toString();
  15472. if (!this._offsetsCache[keyOffset]) {
  15473. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15474. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15475. switch (this.dataType) {
  15476. case Animation.ANIMATIONTYPE_FLOAT:
  15477. this._offsetsCache[keyOffset] = toValue - fromValue;
  15478. break;
  15479. case Animation.ANIMATIONTYPE_QUATERNION:
  15480. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15481. break;
  15482. case Animation.ANIMATIONTYPE_VECTOR3:
  15483. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15484. case Animation.ANIMATIONTYPE_VECTOR2:
  15485. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15486. case Animation.ANIMATIONTYPE_COLOR3:
  15487. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15488. default:
  15489. break;
  15490. }
  15491. this._highLimitsCache[keyOffset] = toValue;
  15492. }
  15493. highLimitValue = this._highLimitsCache[keyOffset];
  15494. offsetValue = this._offsetsCache[keyOffset];
  15495. }
  15496. }
  15497. if (offsetValue === undefined) {
  15498. switch (this.dataType) {
  15499. case Animation.ANIMATIONTYPE_FLOAT:
  15500. offsetValue = 0;
  15501. break;
  15502. case Animation.ANIMATIONTYPE_QUATERNION:
  15503. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  15504. break;
  15505. case Animation.ANIMATIONTYPE_VECTOR3:
  15506. offsetValue = BABYLON.Vector3.Zero();
  15507. break;
  15508. case Animation.ANIMATIONTYPE_VECTOR2:
  15509. offsetValue = BABYLON.Vector2.Zero();
  15510. break;
  15511. case Animation.ANIMATIONTYPE_COLOR3:
  15512. offsetValue = BABYLON.Color3.Black();
  15513. }
  15514. }
  15515. // Compute value
  15516. var repeatCount = (ratio / range) >> 0;
  15517. var currentFrame = returnValue ? from + ratio % range : to;
  15518. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  15519. // Set value
  15520. if (this.targetPropertyPath.length > 1) {
  15521. var property = this._target[this.targetPropertyPath[0]];
  15522. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  15523. property = property[this.targetPropertyPath[index]];
  15524. }
  15525. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  15526. }
  15527. else {
  15528. this._target[this.targetPropertyPath[0]] = currentValue;
  15529. }
  15530. if (this._target.markAsDirty) {
  15531. this._target.markAsDirty(this.targetProperty);
  15532. }
  15533. if (!returnValue) {
  15534. this._stopped = true;
  15535. }
  15536. return returnValue;
  15537. };
  15538. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  15539. get: function () {
  15540. return Animation._ANIMATIONTYPE_FLOAT;
  15541. },
  15542. enumerable: true,
  15543. configurable: true
  15544. });
  15545. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  15546. get: function () {
  15547. return Animation._ANIMATIONTYPE_VECTOR3;
  15548. },
  15549. enumerable: true,
  15550. configurable: true
  15551. });
  15552. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  15553. get: function () {
  15554. return Animation._ANIMATIONTYPE_VECTOR2;
  15555. },
  15556. enumerable: true,
  15557. configurable: true
  15558. });
  15559. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  15560. get: function () {
  15561. return Animation._ANIMATIONTYPE_QUATERNION;
  15562. },
  15563. enumerable: true,
  15564. configurable: true
  15565. });
  15566. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  15567. get: function () {
  15568. return Animation._ANIMATIONTYPE_MATRIX;
  15569. },
  15570. enumerable: true,
  15571. configurable: true
  15572. });
  15573. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  15574. get: function () {
  15575. return Animation._ANIMATIONTYPE_COLOR3;
  15576. },
  15577. enumerable: true,
  15578. configurable: true
  15579. });
  15580. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  15581. get: function () {
  15582. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  15583. },
  15584. enumerable: true,
  15585. configurable: true
  15586. });
  15587. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  15588. get: function () {
  15589. return Animation._ANIMATIONLOOPMODE_CYCLE;
  15590. },
  15591. enumerable: true,
  15592. configurable: true
  15593. });
  15594. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  15595. get: function () {
  15596. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  15597. },
  15598. enumerable: true,
  15599. configurable: true
  15600. });
  15601. // Statics
  15602. Animation._ANIMATIONTYPE_FLOAT = 0;
  15603. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  15604. Animation._ANIMATIONTYPE_QUATERNION = 2;
  15605. Animation._ANIMATIONTYPE_MATRIX = 3;
  15606. Animation._ANIMATIONTYPE_COLOR3 = 4;
  15607. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  15608. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  15609. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  15610. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  15611. return Animation;
  15612. })();
  15613. BABYLON.Animation = Animation;
  15614. })(BABYLON || (BABYLON = {}));
  15615. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  15616. (function (BABYLON) {
  15617. var Animatable = (function () {
  15618. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  15619. if (fromFrame === void 0) { fromFrame = 0; }
  15620. if (toFrame === void 0) { toFrame = 100; }
  15621. if (loopAnimation === void 0) { loopAnimation = false; }
  15622. if (speedRatio === void 0) { speedRatio = 1.0; }
  15623. this.target = target;
  15624. this.fromFrame = fromFrame;
  15625. this.toFrame = toFrame;
  15626. this.loopAnimation = loopAnimation;
  15627. this.speedRatio = speedRatio;
  15628. this.onAnimationEnd = onAnimationEnd;
  15629. this._animations = new Array();
  15630. this._paused = false;
  15631. this.animationStarted = false;
  15632. if (animations) {
  15633. this.appendAnimations(target, animations);
  15634. }
  15635. this._scene = scene;
  15636. scene._activeAnimatables.push(this);
  15637. }
  15638. // Methods
  15639. Animatable.prototype.appendAnimations = function (target, animations) {
  15640. for (var index = 0; index < animations.length; index++) {
  15641. var animation = animations[index];
  15642. animation._target = target;
  15643. this._animations.push(animation);
  15644. }
  15645. };
  15646. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  15647. var animations = this._animations;
  15648. for (var index = 0; index < animations.length; index++) {
  15649. if (animations[index].targetProperty === property) {
  15650. return animations[index];
  15651. }
  15652. }
  15653. return null;
  15654. };
  15655. Animatable.prototype.pause = function () {
  15656. if (this._paused) {
  15657. return;
  15658. }
  15659. this._paused = true;
  15660. };
  15661. Animatable.prototype.restart = function () {
  15662. this._paused = false;
  15663. };
  15664. Animatable.prototype.stop = function () {
  15665. var index = this._scene._activeAnimatables.indexOf(this);
  15666. if (index > -1) {
  15667. this._scene._activeAnimatables.splice(index, 1);
  15668. }
  15669. if (this.onAnimationEnd) {
  15670. this.onAnimationEnd();
  15671. }
  15672. };
  15673. Animatable.prototype._animate = function (delay) {
  15674. if (this._paused) {
  15675. if (!this._pausedDelay) {
  15676. this._pausedDelay = delay;
  15677. }
  15678. return true;
  15679. }
  15680. if (!this._localDelayOffset) {
  15681. this._localDelayOffset = delay;
  15682. }
  15683. else if (this._pausedDelay) {
  15684. this._localDelayOffset += delay - this._pausedDelay;
  15685. this._pausedDelay = null;
  15686. }
  15687. // Animating
  15688. var running = false;
  15689. var animations = this._animations;
  15690. for (var index = 0; index < animations.length; index++) {
  15691. var animation = animations[index];
  15692. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  15693. running = running || isRunning;
  15694. }
  15695. if (!running && this.onAnimationEnd) {
  15696. this.onAnimationEnd();
  15697. }
  15698. return running;
  15699. };
  15700. return Animatable;
  15701. })();
  15702. BABYLON.Animatable = Animatable;
  15703. })(BABYLON || (BABYLON = {}));
  15704. //# sourceMappingURL=babylon.animatable.js.map
  15705. var BABYLON;
  15706. (function (BABYLON) {
  15707. var EasingFunction = (function () {
  15708. function EasingFunction() {
  15709. // Properties
  15710. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  15711. }
  15712. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  15713. get: function () {
  15714. return EasingFunction._EASINGMODE_EASEIN;
  15715. },
  15716. enumerable: true,
  15717. configurable: true
  15718. });
  15719. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  15720. get: function () {
  15721. return EasingFunction._EASINGMODE_EASEOUT;
  15722. },
  15723. enumerable: true,
  15724. configurable: true
  15725. });
  15726. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  15727. get: function () {
  15728. return EasingFunction._EASINGMODE_EASEINOUT;
  15729. },
  15730. enumerable: true,
  15731. configurable: true
  15732. });
  15733. EasingFunction.prototype.setEasingMode = function (easingMode) {
  15734. var n = Math.min(Math.max(easingMode, 0), 2);
  15735. this._easingMode = n;
  15736. };
  15737. EasingFunction.prototype.getEasingMode = function () {
  15738. return this._easingMode;
  15739. };
  15740. EasingFunction.prototype.easeInCore = function (gradient) {
  15741. throw new Error('You must implement this method');
  15742. };
  15743. EasingFunction.prototype.ease = function (gradient) {
  15744. switch (this._easingMode) {
  15745. case EasingFunction.EASINGMODE_EASEIN:
  15746. return this.easeInCore(gradient);
  15747. case EasingFunction.EASINGMODE_EASEOUT:
  15748. return (1 - this.easeInCore(1 - gradient));
  15749. }
  15750. if (gradient >= 0.5) {
  15751. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  15752. }
  15753. return (this.easeInCore(gradient * 2) * 0.5);
  15754. };
  15755. //Statics
  15756. EasingFunction._EASINGMODE_EASEIN = 0;
  15757. EasingFunction._EASINGMODE_EASEOUT = 1;
  15758. EasingFunction._EASINGMODE_EASEINOUT = 2;
  15759. return EasingFunction;
  15760. })();
  15761. BABYLON.EasingFunction = EasingFunction;
  15762. var CircleEase = (function (_super) {
  15763. __extends(CircleEase, _super);
  15764. function CircleEase() {
  15765. _super.apply(this, arguments);
  15766. }
  15767. CircleEase.prototype.easeInCore = function (gradient) {
  15768. gradient = Math.max(0, Math.min(1, gradient));
  15769. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  15770. };
  15771. return CircleEase;
  15772. })(EasingFunction);
  15773. BABYLON.CircleEase = CircleEase;
  15774. var BackEase = (function (_super) {
  15775. __extends(BackEase, _super);
  15776. function BackEase(amplitude) {
  15777. if (amplitude === void 0) { amplitude = 1; }
  15778. _super.call(this);
  15779. this.amplitude = amplitude;
  15780. }
  15781. BackEase.prototype.easeInCore = function (gradient) {
  15782. var num = Math.max(0, this.amplitude);
  15783. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  15784. };
  15785. return BackEase;
  15786. })(EasingFunction);
  15787. BABYLON.BackEase = BackEase;
  15788. var BounceEase = (function (_super) {
  15789. __extends(BounceEase, _super);
  15790. function BounceEase(bounces, bounciness) {
  15791. if (bounces === void 0) { bounces = 3; }
  15792. if (bounciness === void 0) { bounciness = 2; }
  15793. _super.call(this);
  15794. this.bounces = bounces;
  15795. this.bounciness = bounciness;
  15796. }
  15797. BounceEase.prototype.easeInCore = function (gradient) {
  15798. var y = Math.max(0.0, this.bounces);
  15799. var bounciness = this.bounciness;
  15800. if (bounciness <= 1.0) {
  15801. bounciness = 1.001;
  15802. }
  15803. var num9 = Math.pow(bounciness, y);
  15804. var num5 = 1.0 - bounciness;
  15805. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  15806. var num15 = gradient * num4;
  15807. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  15808. var num3 = Math.floor(num65);
  15809. var num13 = num3 + 1.0;
  15810. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  15811. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  15812. var num7 = (num8 + num12) * 0.5;
  15813. var num6 = gradient - num7;
  15814. var num2 = num7 - num8;
  15815. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  15816. };
  15817. return BounceEase;
  15818. })(EasingFunction);
  15819. BABYLON.BounceEase = BounceEase;
  15820. var CubicEase = (function (_super) {
  15821. __extends(CubicEase, _super);
  15822. function CubicEase() {
  15823. _super.apply(this, arguments);
  15824. }
  15825. CubicEase.prototype.easeInCore = function (gradient) {
  15826. return (gradient * gradient * gradient);
  15827. };
  15828. return CubicEase;
  15829. })(EasingFunction);
  15830. BABYLON.CubicEase = CubicEase;
  15831. var ElasticEase = (function (_super) {
  15832. __extends(ElasticEase, _super);
  15833. function ElasticEase(oscillations, springiness) {
  15834. if (oscillations === void 0) { oscillations = 3; }
  15835. if (springiness === void 0) { springiness = 3; }
  15836. _super.call(this);
  15837. this.oscillations = oscillations;
  15838. this.springiness = springiness;
  15839. }
  15840. ElasticEase.prototype.easeInCore = function (gradient) {
  15841. var num2;
  15842. var num3 = Math.max(0.0, this.oscillations);
  15843. var num = Math.max(0.0, this.springiness);
  15844. if (num == 0) {
  15845. num2 = gradient;
  15846. }
  15847. else {
  15848. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  15849. }
  15850. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  15851. };
  15852. return ElasticEase;
  15853. })(EasingFunction);
  15854. BABYLON.ElasticEase = ElasticEase;
  15855. var ExponentialEase = (function (_super) {
  15856. __extends(ExponentialEase, _super);
  15857. function ExponentialEase(exponent) {
  15858. if (exponent === void 0) { exponent = 2; }
  15859. _super.call(this);
  15860. this.exponent = exponent;
  15861. }
  15862. ExponentialEase.prototype.easeInCore = function (gradient) {
  15863. if (this.exponent <= 0) {
  15864. return gradient;
  15865. }
  15866. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  15867. };
  15868. return ExponentialEase;
  15869. })(EasingFunction);
  15870. BABYLON.ExponentialEase = ExponentialEase;
  15871. var PowerEase = (function (_super) {
  15872. __extends(PowerEase, _super);
  15873. function PowerEase(power) {
  15874. if (power === void 0) { power = 2; }
  15875. _super.call(this);
  15876. this.power = power;
  15877. }
  15878. PowerEase.prototype.easeInCore = function (gradient) {
  15879. var y = Math.max(0.0, this.power);
  15880. return Math.pow(gradient, y);
  15881. };
  15882. return PowerEase;
  15883. })(EasingFunction);
  15884. BABYLON.PowerEase = PowerEase;
  15885. var QuadraticEase = (function (_super) {
  15886. __extends(QuadraticEase, _super);
  15887. function QuadraticEase() {
  15888. _super.apply(this, arguments);
  15889. }
  15890. QuadraticEase.prototype.easeInCore = function (gradient) {
  15891. return (gradient * gradient);
  15892. };
  15893. return QuadraticEase;
  15894. })(EasingFunction);
  15895. BABYLON.QuadraticEase = QuadraticEase;
  15896. var QuarticEase = (function (_super) {
  15897. __extends(QuarticEase, _super);
  15898. function QuarticEase() {
  15899. _super.apply(this, arguments);
  15900. }
  15901. QuarticEase.prototype.easeInCore = function (gradient) {
  15902. return (gradient * gradient * gradient * gradient);
  15903. };
  15904. return QuarticEase;
  15905. })(EasingFunction);
  15906. BABYLON.QuarticEase = QuarticEase;
  15907. var QuinticEase = (function (_super) {
  15908. __extends(QuinticEase, _super);
  15909. function QuinticEase() {
  15910. _super.apply(this, arguments);
  15911. }
  15912. QuinticEase.prototype.easeInCore = function (gradient) {
  15913. return (gradient * gradient * gradient * gradient * gradient);
  15914. };
  15915. return QuinticEase;
  15916. })(EasingFunction);
  15917. BABYLON.QuinticEase = QuinticEase;
  15918. var SineEase = (function (_super) {
  15919. __extends(SineEase, _super);
  15920. function SineEase() {
  15921. _super.apply(this, arguments);
  15922. }
  15923. SineEase.prototype.easeInCore = function (gradient) {
  15924. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  15925. };
  15926. return SineEase;
  15927. })(EasingFunction);
  15928. BABYLON.SineEase = SineEase;
  15929. var BezierCurveEase = (function (_super) {
  15930. __extends(BezierCurveEase, _super);
  15931. function BezierCurveEase(x1, y1, x2, y2) {
  15932. if (x1 === void 0) { x1 = 0; }
  15933. if (y1 === void 0) { y1 = 0; }
  15934. if (x2 === void 0) { x2 = 1; }
  15935. if (y2 === void 0) { y2 = 1; }
  15936. _super.call(this);
  15937. this.x1 = x1;
  15938. this.y1 = y1;
  15939. this.x2 = x2;
  15940. this.y2 = y2;
  15941. }
  15942. BezierCurveEase.prototype.easeInCore = function (gradient) {
  15943. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  15944. };
  15945. return BezierCurveEase;
  15946. })(EasingFunction);
  15947. BABYLON.BezierCurveEase = BezierCurveEase;
  15948. })(BABYLON || (BABYLON = {}));
  15949. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  15950. (function (BABYLON) {
  15951. var Octree = (function () {
  15952. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  15953. if (maxDepth === void 0) { maxDepth = 2; }
  15954. this.maxDepth = maxDepth;
  15955. this.dynamicContent = new Array();
  15956. this._maxBlockCapacity = maxBlockCapacity || 64;
  15957. this._selectionContent = new BABYLON.SmartArray(1024);
  15958. this._creationFunc = creationFunc;
  15959. }
  15960. // Methods
  15961. Octree.prototype.update = function (worldMin, worldMax, entries) {
  15962. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  15963. };
  15964. Octree.prototype.addMesh = function (entry) {
  15965. for (var index = 0; index < this.blocks.length; index++) {
  15966. var block = this.blocks[index];
  15967. block.addEntry(entry);
  15968. }
  15969. };
  15970. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  15971. this._selectionContent.reset();
  15972. for (var index = 0; index < this.blocks.length; index++) {
  15973. var block = this.blocks[index];
  15974. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  15975. }
  15976. if (allowDuplicate) {
  15977. this._selectionContent.concat(this.dynamicContent);
  15978. }
  15979. else {
  15980. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15981. }
  15982. return this._selectionContent;
  15983. };
  15984. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  15985. this._selectionContent.reset();
  15986. for (var index = 0; index < this.blocks.length; index++) {
  15987. var block = this.blocks[index];
  15988. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  15989. }
  15990. if (allowDuplicate) {
  15991. this._selectionContent.concat(this.dynamicContent);
  15992. }
  15993. else {
  15994. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15995. }
  15996. return this._selectionContent;
  15997. };
  15998. Octree.prototype.intersectsRay = function (ray) {
  15999. this._selectionContent.reset();
  16000. for (var index = 0; index < this.blocks.length; index++) {
  16001. var block = this.blocks[index];
  16002. block.intersectsRay(ray, this._selectionContent);
  16003. }
  16004. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16005. return this._selectionContent;
  16006. };
  16007. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  16008. target.blocks = new Array();
  16009. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  16010. for (var x = 0; x < 2; x++) {
  16011. for (var y = 0; y < 2; y++) {
  16012. for (var z = 0; z < 2; z++) {
  16013. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  16014. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  16015. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  16016. block.addEntries(entries);
  16017. target.blocks.push(block);
  16018. }
  16019. }
  16020. }
  16021. };
  16022. Octree.CreationFuncForMeshes = function (entry, block) {
  16023. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16024. block.entries.push(entry);
  16025. }
  16026. };
  16027. Octree.CreationFuncForSubMeshes = function (entry, block) {
  16028. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16029. block.entries.push(entry);
  16030. }
  16031. };
  16032. return Octree;
  16033. })();
  16034. BABYLON.Octree = Octree;
  16035. })(BABYLON || (BABYLON = {}));
  16036. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  16037. (function (BABYLON) {
  16038. var OctreeBlock = (function () {
  16039. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  16040. this.entries = new Array();
  16041. this._boundingVectors = new Array();
  16042. this._capacity = capacity;
  16043. this._depth = depth;
  16044. this._maxDepth = maxDepth;
  16045. this._creationFunc = creationFunc;
  16046. this._minPoint = minPoint;
  16047. this._maxPoint = maxPoint;
  16048. this._boundingVectors.push(minPoint.clone());
  16049. this._boundingVectors.push(maxPoint.clone());
  16050. this._boundingVectors.push(minPoint.clone());
  16051. this._boundingVectors[2].x = maxPoint.x;
  16052. this._boundingVectors.push(minPoint.clone());
  16053. this._boundingVectors[3].y = maxPoint.y;
  16054. this._boundingVectors.push(minPoint.clone());
  16055. this._boundingVectors[4].z = maxPoint.z;
  16056. this._boundingVectors.push(maxPoint.clone());
  16057. this._boundingVectors[5].z = minPoint.z;
  16058. this._boundingVectors.push(maxPoint.clone());
  16059. this._boundingVectors[6].x = minPoint.x;
  16060. this._boundingVectors.push(maxPoint.clone());
  16061. this._boundingVectors[7].y = minPoint.y;
  16062. }
  16063. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  16064. // Property
  16065. get: function () {
  16066. return this._capacity;
  16067. },
  16068. enumerable: true,
  16069. configurable: true
  16070. });
  16071. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  16072. get: function () {
  16073. return this._minPoint;
  16074. },
  16075. enumerable: true,
  16076. configurable: true
  16077. });
  16078. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  16079. get: function () {
  16080. return this._maxPoint;
  16081. },
  16082. enumerable: true,
  16083. configurable: true
  16084. });
  16085. // Methods
  16086. OctreeBlock.prototype.addEntry = function (entry) {
  16087. if (this.blocks) {
  16088. for (var index = 0; index < this.blocks.length; index++) {
  16089. var block = this.blocks[index];
  16090. block.addEntry(entry);
  16091. }
  16092. return;
  16093. }
  16094. this._creationFunc(entry, this);
  16095. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  16096. this.createInnerBlocks();
  16097. }
  16098. };
  16099. OctreeBlock.prototype.addEntries = function (entries) {
  16100. for (var index = 0; index < entries.length; index++) {
  16101. var mesh = entries[index];
  16102. this.addEntry(mesh);
  16103. }
  16104. };
  16105. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  16106. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  16107. if (this.blocks) {
  16108. for (var index = 0; index < this.blocks.length; index++) {
  16109. var block = this.blocks[index];
  16110. block.select(frustumPlanes, selection, allowDuplicate);
  16111. }
  16112. return;
  16113. }
  16114. if (allowDuplicate) {
  16115. selection.concat(this.entries);
  16116. }
  16117. else {
  16118. selection.concatWithNoDuplicate(this.entries);
  16119. }
  16120. }
  16121. };
  16122. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  16123. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  16124. if (this.blocks) {
  16125. for (var index = 0; index < this.blocks.length; index++) {
  16126. var block = this.blocks[index];
  16127. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  16128. }
  16129. return;
  16130. }
  16131. if (allowDuplicate) {
  16132. selection.concat(this.entries);
  16133. }
  16134. else {
  16135. selection.concatWithNoDuplicate(this.entries);
  16136. }
  16137. }
  16138. };
  16139. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  16140. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  16141. if (this.blocks) {
  16142. for (var index = 0; index < this.blocks.length; index++) {
  16143. var block = this.blocks[index];
  16144. block.intersectsRay(ray, selection);
  16145. }
  16146. return;
  16147. }
  16148. selection.concatWithNoDuplicate(this.entries);
  16149. }
  16150. };
  16151. OctreeBlock.prototype.createInnerBlocks = function () {
  16152. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  16153. };
  16154. return OctreeBlock;
  16155. })();
  16156. BABYLON.OctreeBlock = OctreeBlock;
  16157. })(BABYLON || (BABYLON = {}));
  16158. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  16159. (function (BABYLON) {
  16160. var Bone = (function () {
  16161. function Bone(name, skeleton, parentBone, matrix) {
  16162. this.name = name;
  16163. this.children = new Array();
  16164. this.animations = new Array();
  16165. this._worldTransform = new BABYLON.Matrix();
  16166. this._absoluteTransform = new BABYLON.Matrix();
  16167. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  16168. this._skeleton = skeleton;
  16169. this._matrix = matrix;
  16170. this._baseMatrix = matrix;
  16171. skeleton.bones.push(this);
  16172. if (parentBone) {
  16173. this._parent = parentBone;
  16174. parentBone.children.push(this);
  16175. }
  16176. else {
  16177. this._parent = null;
  16178. }
  16179. this._updateDifferenceMatrix();
  16180. }
  16181. // Members
  16182. Bone.prototype.getParent = function () {
  16183. return this._parent;
  16184. };
  16185. Bone.prototype.getLocalMatrix = function () {
  16186. return this._matrix;
  16187. };
  16188. Bone.prototype.getBaseMatrix = function () {
  16189. return this._baseMatrix;
  16190. };
  16191. Bone.prototype.getWorldMatrix = function () {
  16192. return this._worldTransform;
  16193. };
  16194. Bone.prototype.getInvertedAbsoluteTransform = function () {
  16195. return this._invertedAbsoluteTransform;
  16196. };
  16197. Bone.prototype.getAbsoluteMatrix = function () {
  16198. var matrix = this._matrix.clone();
  16199. var parent = this._parent;
  16200. while (parent) {
  16201. matrix = matrix.multiply(parent.getLocalMatrix());
  16202. parent = parent.getParent();
  16203. }
  16204. return matrix;
  16205. };
  16206. // Methods
  16207. Bone.prototype.updateMatrix = function (matrix) {
  16208. this._matrix = matrix;
  16209. this._skeleton._markAsDirty();
  16210. this._updateDifferenceMatrix();
  16211. };
  16212. Bone.prototype._updateDifferenceMatrix = function () {
  16213. if (this._parent) {
  16214. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  16215. }
  16216. else {
  16217. this._absoluteTransform.copyFrom(this._matrix);
  16218. }
  16219. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  16220. for (var index = 0; index < this.children.length; index++) {
  16221. this.children[index]._updateDifferenceMatrix();
  16222. }
  16223. };
  16224. Bone.prototype.markAsDirty = function () {
  16225. this._skeleton._markAsDirty();
  16226. };
  16227. return Bone;
  16228. })();
  16229. BABYLON.Bone = Bone;
  16230. })(BABYLON || (BABYLON = {}));
  16231. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  16232. (function (BABYLON) {
  16233. var Skeleton = (function () {
  16234. function Skeleton(name, id, scene) {
  16235. this.name = name;
  16236. this.id = id;
  16237. this.bones = new Array();
  16238. this._isDirty = true;
  16239. this._identity = BABYLON.Matrix.Identity();
  16240. this.bones = [];
  16241. this._scene = scene;
  16242. scene.skeletons.push(this);
  16243. }
  16244. // Members
  16245. Skeleton.prototype.getTransformMatrices = function () {
  16246. return this._transformMatrices;
  16247. };
  16248. // Methods
  16249. Skeleton.prototype._markAsDirty = function () {
  16250. this._isDirty = true;
  16251. };
  16252. Skeleton.prototype.prepare = function () {
  16253. if (!this._isDirty) {
  16254. return;
  16255. }
  16256. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  16257. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  16258. }
  16259. for (var index = 0; index < this.bones.length; index++) {
  16260. var bone = this.bones[index];
  16261. var parentBone = bone.getParent();
  16262. if (parentBone) {
  16263. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  16264. }
  16265. else {
  16266. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  16267. }
  16268. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  16269. }
  16270. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  16271. this._isDirty = false;
  16272. };
  16273. Skeleton.prototype.getAnimatables = function () {
  16274. if (!this._animatables || this._animatables.length != this.bones.length) {
  16275. this._animatables = [];
  16276. for (var index = 0; index < this.bones.length; index++) {
  16277. this._animatables.push(this.bones[index]);
  16278. }
  16279. }
  16280. return this._animatables;
  16281. };
  16282. Skeleton.prototype.clone = function (name, id) {
  16283. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  16284. for (var index = 0; index < this.bones.length; index++) {
  16285. var source = this.bones[index];
  16286. var parentBone = null;
  16287. if (source.getParent()) {
  16288. var parentIndex = this.bones.indexOf(source.getParent());
  16289. parentBone = result.bones[parentIndex];
  16290. }
  16291. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  16292. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  16293. }
  16294. return result;
  16295. };
  16296. return Skeleton;
  16297. })();
  16298. BABYLON.Skeleton = Skeleton;
  16299. })(BABYLON || (BABYLON = {}));
  16300. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  16301. (function (BABYLON) {
  16302. var PostProcess = (function () {
  16303. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  16304. this.name = name;
  16305. this.width = -1;
  16306. this.height = -1;
  16307. this._reusable = false;
  16308. this._textures = new BABYLON.SmartArray(2);
  16309. this._currentRenderTextureInd = 0;
  16310. if (camera != null) {
  16311. this._camera = camera;
  16312. this._scene = camera.getScene();
  16313. camera.attachPostProcess(this);
  16314. this._engine = this._scene.getEngine();
  16315. }
  16316. else {
  16317. this._engine = engine;
  16318. }
  16319. this._renderRatio = ratio;
  16320. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  16321. this._reusable = reusable || false;
  16322. samplers = samplers || [];
  16323. samplers.push("textureSampler");
  16324. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  16325. }
  16326. PostProcess.prototype.isReusable = function () {
  16327. return this._reusable;
  16328. };
  16329. PostProcess.prototype.activate = function (camera, sourceTexture) {
  16330. camera = camera || this._camera;
  16331. var scene = camera.getScene();
  16332. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  16333. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  16334. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  16335. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  16336. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  16337. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  16338. if (this._textures.length > 0) {
  16339. for (var i = 0; i < this._textures.length; i++) {
  16340. this._engine._releaseTexture(this._textures.data[i]);
  16341. }
  16342. this._textures.reset();
  16343. }
  16344. this.width = desiredWidth;
  16345. this.height = desiredHeight;
  16346. 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 }));
  16347. if (this._reusable) {
  16348. 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 }));
  16349. }
  16350. if (this.onSizeChanged) {
  16351. this.onSizeChanged();
  16352. }
  16353. }
  16354. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  16355. if (this.onActivate) {
  16356. this.onActivate(camera);
  16357. }
  16358. // Clear
  16359. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  16360. if (this._reusable) {
  16361. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  16362. }
  16363. };
  16364. PostProcess.prototype.apply = function () {
  16365. // Check
  16366. if (!this._effect.isReady())
  16367. return null;
  16368. // States
  16369. this._engine.enableEffect(this._effect);
  16370. this._engine.setState(false);
  16371. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16372. this._engine.setDepthBuffer(false);
  16373. this._engine.setDepthWrite(false);
  16374. // Texture
  16375. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  16376. // Parameters
  16377. if (this.onApply) {
  16378. this.onApply(this._effect);
  16379. }
  16380. return this._effect;
  16381. };
  16382. PostProcess.prototype.dispose = function (camera) {
  16383. camera = camera || this._camera;
  16384. if (this._textures.length > 0) {
  16385. for (var i = 0; i < this._textures.length; i++) {
  16386. this._engine._releaseTexture(this._textures.data[i]);
  16387. }
  16388. this._textures.reset();
  16389. }
  16390. camera.detachPostProcess(this);
  16391. var index = camera._postProcesses.indexOf(this);
  16392. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  16393. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  16394. }
  16395. };
  16396. return PostProcess;
  16397. })();
  16398. BABYLON.PostProcess = PostProcess;
  16399. })(BABYLON || (BABYLON = {}));
  16400. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  16401. (function (BABYLON) {
  16402. var PostProcessManager = (function () {
  16403. function PostProcessManager(scene) {
  16404. this._vertexDeclaration = [2];
  16405. this._vertexStrideSize = 2 * 4;
  16406. this._scene = scene;
  16407. // VBO
  16408. var vertices = [];
  16409. vertices.push(1, 1);
  16410. vertices.push(-1, 1);
  16411. vertices.push(-1, -1);
  16412. vertices.push(1, -1);
  16413. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16414. // Indices
  16415. var indices = [];
  16416. indices.push(0);
  16417. indices.push(1);
  16418. indices.push(2);
  16419. indices.push(0);
  16420. indices.push(2);
  16421. indices.push(3);
  16422. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16423. }
  16424. // Methods
  16425. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  16426. var postProcesses = this._scene.activeCamera._postProcesses;
  16427. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16428. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16429. return false;
  16430. }
  16431. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  16432. return true;
  16433. };
  16434. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  16435. var postProcesses = this._scene.activeCamera._postProcesses;
  16436. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16437. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16438. return;
  16439. }
  16440. var engine = this._scene.getEngine();
  16441. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  16442. if (index < postProcessesTakenIndices.length - 1) {
  16443. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  16444. }
  16445. else {
  16446. if (targetTexture) {
  16447. engine.bindFramebuffer(targetTexture);
  16448. }
  16449. else {
  16450. engine.restoreDefaultFramebuffer();
  16451. }
  16452. }
  16453. if (doNotPresent) {
  16454. break;
  16455. }
  16456. var pp = postProcesses[postProcessesTakenIndices[index]];
  16457. var effect = pp.apply();
  16458. if (effect) {
  16459. if (pp.onBeforeRender) {
  16460. pp.onBeforeRender(effect);
  16461. }
  16462. // VBOs
  16463. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16464. // Draw order
  16465. engine.draw(true, 0, 6);
  16466. }
  16467. }
  16468. // Restore depth buffer
  16469. engine.setDepthBuffer(true);
  16470. engine.setDepthWrite(true);
  16471. };
  16472. PostProcessManager.prototype.dispose = function () {
  16473. if (this._vertexBuffer) {
  16474. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16475. this._vertexBuffer = null;
  16476. }
  16477. if (this._indexBuffer) {
  16478. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16479. this._indexBuffer = null;
  16480. }
  16481. };
  16482. return PostProcessManager;
  16483. })();
  16484. BABYLON.PostProcessManager = PostProcessManager;
  16485. })(BABYLON || (BABYLON = {}));
  16486. //# sourceMappingURL=babylon.postProcessManager.js.map
  16487. var BABYLON;
  16488. (function (BABYLON) {
  16489. var PassPostProcess = (function (_super) {
  16490. __extends(PassPostProcess, _super);
  16491. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16492. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  16493. }
  16494. return PassPostProcess;
  16495. })(BABYLON.PostProcess);
  16496. BABYLON.PassPostProcess = PassPostProcess;
  16497. })(BABYLON || (BABYLON = {}));
  16498. //# sourceMappingURL=babylon.passPostProcess.js.map
  16499. var BABYLON;
  16500. (function (BABYLON) {
  16501. var BlurPostProcess = (function (_super) {
  16502. __extends(BlurPostProcess, _super);
  16503. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  16504. var _this = this;
  16505. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  16506. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  16507. this.direction = direction;
  16508. this.blurWidth = blurWidth;
  16509. this.onApply = function (effect) {
  16510. effect.setFloat2("screenSize", _this.width, _this.height);
  16511. effect.setVector2("direction", _this.direction);
  16512. effect.setFloat("blurWidth", _this.blurWidth);
  16513. };
  16514. }
  16515. return BlurPostProcess;
  16516. })(BABYLON.PostProcess);
  16517. BABYLON.BlurPostProcess = BlurPostProcess;
  16518. })(BABYLON || (BABYLON = {}));
  16519. //# sourceMappingURL=babylon.blurPostProcess.js.map
  16520. var BABYLON;
  16521. (function (BABYLON) {
  16522. var FilterPostProcess = (function (_super) {
  16523. __extends(FilterPostProcess, _super);
  16524. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  16525. var _this = this;
  16526. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  16527. this.kernelMatrix = kernelMatrix;
  16528. this.onApply = function (effect) {
  16529. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  16530. };
  16531. }
  16532. return FilterPostProcess;
  16533. })(BABYLON.PostProcess);
  16534. BABYLON.FilterPostProcess = FilterPostProcess;
  16535. })(BABYLON || (BABYLON = {}));
  16536. //# sourceMappingURL=babylon.filterPostProcess.js.map
  16537. var BABYLON;
  16538. (function (BABYLON) {
  16539. var RefractionPostProcess = (function (_super) {
  16540. __extends(RefractionPostProcess, _super);
  16541. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  16542. var _this = this;
  16543. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  16544. this.color = color;
  16545. this.depth = depth;
  16546. this.colorLevel = colorLevel;
  16547. this.onActivate = function (cam) {
  16548. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  16549. };
  16550. this.onApply = function (effect) {
  16551. effect.setColor3("baseColor", _this.color);
  16552. effect.setFloat("depth", _this.depth);
  16553. effect.setFloat("colorLevel", _this.colorLevel);
  16554. effect.setTexture("refractionSampler", _this._refRexture);
  16555. };
  16556. }
  16557. // Methods
  16558. RefractionPostProcess.prototype.dispose = function (camera) {
  16559. if (this._refRexture) {
  16560. this._refRexture.dispose();
  16561. }
  16562. _super.prototype.dispose.call(this, camera);
  16563. };
  16564. return RefractionPostProcess;
  16565. })(BABYLON.PostProcess);
  16566. BABYLON.RefractionPostProcess = RefractionPostProcess;
  16567. })(BABYLON || (BABYLON = {}));
  16568. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  16569. var BABYLON;
  16570. (function (BABYLON) {
  16571. var BlackAndWhitePostProcess = (function (_super) {
  16572. __extends(BlackAndWhitePostProcess, _super);
  16573. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16574. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  16575. }
  16576. return BlackAndWhitePostProcess;
  16577. })(BABYLON.PostProcess);
  16578. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  16579. })(BABYLON || (BABYLON = {}));
  16580. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  16581. var BABYLON;
  16582. (function (BABYLON) {
  16583. var ConvolutionPostProcess = (function (_super) {
  16584. __extends(ConvolutionPostProcess, _super);
  16585. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  16586. var _this = this;
  16587. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  16588. this.kernel = kernel;
  16589. this.onApply = function (effect) {
  16590. effect.setFloat2("screenSize", _this.width, _this.height);
  16591. effect.setArray("kernel", _this.kernel);
  16592. };
  16593. }
  16594. // Statics
  16595. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  16596. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  16597. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  16598. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  16599. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  16600. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  16601. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  16602. return ConvolutionPostProcess;
  16603. })(BABYLON.PostProcess);
  16604. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  16605. })(BABYLON || (BABYLON = {}));
  16606. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  16607. var BABYLON;
  16608. (function (BABYLON) {
  16609. var FxaaPostProcess = (function (_super) {
  16610. __extends(FxaaPostProcess, _super);
  16611. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16612. var _this = this;
  16613. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  16614. this.onSizeChanged = function () {
  16615. _this.texelWidth = 1.0 / _this.width;
  16616. _this.texelHeight = 1.0 / _this.height;
  16617. };
  16618. this.onApply = function (effect) {
  16619. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  16620. };
  16621. }
  16622. return FxaaPostProcess;
  16623. })(BABYLON.PostProcess);
  16624. BABYLON.FxaaPostProcess = FxaaPostProcess;
  16625. })(BABYLON || (BABYLON = {}));
  16626. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  16627. (function (BABYLON) {
  16628. var LensFlare = (function () {
  16629. function LensFlare(size, position, color, imgUrl, system) {
  16630. this.size = size;
  16631. this.position = position;
  16632. this.dispose = function () {
  16633. if (this.texture) {
  16634. this.texture.dispose();
  16635. }
  16636. // Remove from scene
  16637. var index = this._system.lensFlares.indexOf(this);
  16638. this._system.lensFlares.splice(index, 1);
  16639. };
  16640. this.color = color || new BABYLON.Color3(1, 1, 1);
  16641. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  16642. this._system = system;
  16643. system.lensFlares.push(this);
  16644. }
  16645. return LensFlare;
  16646. })();
  16647. BABYLON.LensFlare = LensFlare;
  16648. })(BABYLON || (BABYLON = {}));
  16649. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  16650. (function (BABYLON) {
  16651. var LensFlareSystem = (function () {
  16652. function LensFlareSystem(name, emitter, scene) {
  16653. this.name = name;
  16654. this.lensFlares = new Array();
  16655. this.borderLimit = 300;
  16656. this._vertexDeclaration = [2];
  16657. this._vertexStrideSize = 2 * 4;
  16658. this._isEnabled = true;
  16659. this._scene = scene;
  16660. this._emitter = emitter;
  16661. scene.lensFlareSystems.push(this);
  16662. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  16663. // VBO
  16664. var vertices = [];
  16665. vertices.push(1, 1);
  16666. vertices.push(-1, 1);
  16667. vertices.push(-1, -1);
  16668. vertices.push(1, -1);
  16669. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16670. // Indices
  16671. var indices = [];
  16672. indices.push(0);
  16673. indices.push(1);
  16674. indices.push(2);
  16675. indices.push(0);
  16676. indices.push(2);
  16677. indices.push(3);
  16678. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16679. // Effects
  16680. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  16681. }
  16682. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  16683. get: function () {
  16684. return this._isEnabled;
  16685. },
  16686. set: function (value) {
  16687. this._isEnabled = value;
  16688. },
  16689. enumerable: true,
  16690. configurable: true
  16691. });
  16692. LensFlareSystem.prototype.getScene = function () {
  16693. return this._scene;
  16694. };
  16695. LensFlareSystem.prototype.getEmitter = function () {
  16696. return this._emitter;
  16697. };
  16698. LensFlareSystem.prototype.getEmitterPosition = function () {
  16699. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  16700. };
  16701. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  16702. var position = this.getEmitterPosition();
  16703. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  16704. this._positionX = position.x;
  16705. this._positionY = position.y;
  16706. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  16707. if (position.z > 0) {
  16708. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  16709. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  16710. return true;
  16711. }
  16712. }
  16713. return false;
  16714. };
  16715. LensFlareSystem.prototype._isVisible = function () {
  16716. if (!this._isEnabled) {
  16717. return false;
  16718. }
  16719. var emitterPosition = this.getEmitterPosition();
  16720. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  16721. var distance = direction.length();
  16722. direction.normalize();
  16723. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  16724. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  16725. return !pickInfo.hit || pickInfo.distance > distance;
  16726. };
  16727. LensFlareSystem.prototype.render = function () {
  16728. if (!this._effect.isReady())
  16729. return false;
  16730. var engine = this._scene.getEngine();
  16731. var viewport = this._scene.activeCamera.viewport;
  16732. var globalViewport = viewport.toGlobal(engine);
  16733. // Position
  16734. if (!this.computeEffectivePosition(globalViewport)) {
  16735. return false;
  16736. }
  16737. // Visibility
  16738. if (!this._isVisible()) {
  16739. return false;
  16740. }
  16741. // Intensity
  16742. var awayX;
  16743. var awayY;
  16744. if (this._positionX < this.borderLimit + globalViewport.x) {
  16745. awayX = this.borderLimit + globalViewport.x - this._positionX;
  16746. }
  16747. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  16748. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  16749. }
  16750. else {
  16751. awayX = 0;
  16752. }
  16753. if (this._positionY < this.borderLimit + globalViewport.y) {
  16754. awayY = this.borderLimit + globalViewport.y - this._positionY;
  16755. }
  16756. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  16757. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  16758. }
  16759. else {
  16760. awayY = 0;
  16761. }
  16762. var away = (awayX > awayY) ? awayX : awayY;
  16763. if (away > this.borderLimit) {
  16764. away = this.borderLimit;
  16765. }
  16766. var intensity = 1.0 - (away / this.borderLimit);
  16767. if (intensity < 0) {
  16768. return false;
  16769. }
  16770. if (intensity > 1.0) {
  16771. intensity = 1.0;
  16772. }
  16773. // Position
  16774. var centerX = globalViewport.x + globalViewport.width / 2;
  16775. var centerY = globalViewport.y + globalViewport.height / 2;
  16776. var distX = centerX - this._positionX;
  16777. var distY = centerY - this._positionY;
  16778. // Effects
  16779. engine.enableEffect(this._effect);
  16780. engine.setState(false);
  16781. engine.setDepthBuffer(false);
  16782. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16783. // VBOs
  16784. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16785. for (var index = 0; index < this.lensFlares.length; index++) {
  16786. var flare = this.lensFlares[index];
  16787. var x = centerX - (distX * flare.position);
  16788. var y = centerY - (distY * flare.position);
  16789. var cw = flare.size;
  16790. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  16791. var cx = 2 * (x / globalViewport.width) - 1.0;
  16792. var cy = 1.0 - 2 * (y / globalViewport.height);
  16793. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  16794. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  16795. // Texture
  16796. this._effect.setTexture("textureSampler", flare.texture);
  16797. // Color
  16798. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  16799. // Draw order
  16800. engine.draw(true, 0, 6);
  16801. }
  16802. engine.setDepthBuffer(true);
  16803. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16804. return true;
  16805. };
  16806. LensFlareSystem.prototype.dispose = function () {
  16807. if (this._vertexBuffer) {
  16808. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16809. this._vertexBuffer = null;
  16810. }
  16811. if (this._indexBuffer) {
  16812. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16813. this._indexBuffer = null;
  16814. }
  16815. while (this.lensFlares.length) {
  16816. this.lensFlares[0].dispose();
  16817. }
  16818. // Remove from scene
  16819. var index = this._scene.lensFlareSystems.indexOf(this);
  16820. this._scene.lensFlareSystems.splice(index, 1);
  16821. };
  16822. return LensFlareSystem;
  16823. })();
  16824. BABYLON.LensFlareSystem = LensFlareSystem;
  16825. })(BABYLON || (BABYLON = {}));
  16826. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  16827. (function (BABYLON) {
  16828. var IntersectionInfo = (function () {
  16829. function IntersectionInfo(bu, bv, distance) {
  16830. this.bu = bu;
  16831. this.bv = bv;
  16832. this.distance = distance;
  16833. this.faceId = 0;
  16834. }
  16835. return IntersectionInfo;
  16836. })();
  16837. BABYLON.IntersectionInfo = IntersectionInfo;
  16838. var PickingInfo = (function () {
  16839. function PickingInfo() {
  16840. this.hit = false;
  16841. this.distance = 0;
  16842. this.pickedPoint = null;
  16843. this.pickedMesh = null;
  16844. this.bu = 0;
  16845. this.bv = 0;
  16846. this.faceId = -1;
  16847. }
  16848. // Methods
  16849. PickingInfo.prototype.getNormal = function () {
  16850. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16851. return null;
  16852. }
  16853. var indices = this.pickedMesh.getIndices();
  16854. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16855. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  16856. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  16857. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  16858. normal0 = normal0.scale(this.bu);
  16859. normal1 = normal1.scale(this.bv);
  16860. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  16861. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  16862. };
  16863. PickingInfo.prototype.getTextureCoordinates = function () {
  16864. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16865. return null;
  16866. }
  16867. var indices = this.pickedMesh.getIndices();
  16868. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16869. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  16870. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  16871. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  16872. uv0 = uv0.scale(this.bu);
  16873. uv1 = uv1.scale(this.bv);
  16874. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  16875. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  16876. };
  16877. return PickingInfo;
  16878. })();
  16879. BABYLON.PickingInfo = PickingInfo;
  16880. })(BABYLON || (BABYLON = {}));
  16881. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  16882. (function (BABYLON) {
  16883. var FilesInput = (function () {
  16884. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  16885. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  16886. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  16887. this.engine = p_engine;
  16888. this.canvas = p_canvas;
  16889. this.currentScene = p_scene;
  16890. this.sceneLoadedCallback = p_sceneLoadedCallback;
  16891. this.progressCallback = p_progressCallback;
  16892. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  16893. this.textureLoadingCallback = p_textureLoadingCallback;
  16894. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  16895. }
  16896. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  16897. var _this = this;
  16898. if (p_elementToMonitor) {
  16899. this.elementToMonitor = p_elementToMonitor;
  16900. this.elementToMonitor.addEventListener("dragenter", function (e) {
  16901. _this.drag(e);
  16902. }, false);
  16903. this.elementToMonitor.addEventListener("dragover", function (e) {
  16904. _this.drag(e);
  16905. }, false);
  16906. this.elementToMonitor.addEventListener("drop", function (e) {
  16907. _this.drop(e);
  16908. }, false);
  16909. }
  16910. };
  16911. FilesInput.prototype.renderFunction = function () {
  16912. if (this.additionnalRenderLoopLogicCallback) {
  16913. this.additionnalRenderLoopLogicCallback();
  16914. }
  16915. if (this.currentScene) {
  16916. if (this.textureLoadingCallback) {
  16917. var remaining = this.currentScene.getWaitingItemsCount();
  16918. if (remaining > 0) {
  16919. this.textureLoadingCallback(remaining);
  16920. }
  16921. }
  16922. this.currentScene.render();
  16923. }
  16924. };
  16925. FilesInput.prototype.drag = function (e) {
  16926. e.stopPropagation();
  16927. e.preventDefault();
  16928. };
  16929. FilesInput.prototype.drop = function (eventDrop) {
  16930. eventDrop.stopPropagation();
  16931. eventDrop.preventDefault();
  16932. this.loadFiles(eventDrop);
  16933. };
  16934. FilesInput.prototype.loadFiles = function (event) {
  16935. var _this = this;
  16936. var that = this;
  16937. if (this.startingProcessingFilesCallback)
  16938. this.startingProcessingFilesCallback();
  16939. var sceneFileToLoad;
  16940. var filesToLoad;
  16941. // Handling data transfer via drag'n'drop
  16942. if (event && event.dataTransfer && event.dataTransfer.files) {
  16943. filesToLoad = event.dataTransfer.files;
  16944. }
  16945. // Handling files from input files
  16946. if (event && event.target && event.target.files) {
  16947. filesToLoad = event.target.files;
  16948. }
  16949. if (filesToLoad && filesToLoad.length > 0) {
  16950. for (var i = 0; i < filesToLoad.length; i++) {
  16951. switch (filesToLoad[i].type) {
  16952. case "image/jpeg":
  16953. case "image/png":
  16954. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  16955. break;
  16956. case "image/targa":
  16957. case "image/vnd.ms-dds":
  16958. case "audio/wav":
  16959. case "audio/x-wav":
  16960. case "audio/mp3":
  16961. case "audio/mpeg":
  16962. case "audio/mpeg3":
  16963. case "audio/x-mpeg-3":
  16964. case "audio/ogg":
  16965. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  16966. break;
  16967. default:
  16968. if (filesToLoad[i].name.indexOf(".babylon") !== -1 && filesToLoad[i].name.indexOf(".manifest") === -1 && filesToLoad[i].name.indexOf(".incremental") === -1 && filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  16969. sceneFileToLoad = filesToLoad[i];
  16970. }
  16971. break;
  16972. }
  16973. }
  16974. // If a ".babylon" file has been provided
  16975. if (sceneFileToLoad) {
  16976. if (this.currentScene) {
  16977. this.engine.stopRenderLoop();
  16978. this.currentScene.dispose();
  16979. }
  16980. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  16981. that.currentScene = newScene;
  16982. // Wait for textures and shaders to be ready
  16983. that.currentScene.executeWhenReady(function () {
  16984. // Attach camera to canvas inputs
  16985. if (that.currentScene.activeCamera) {
  16986. that.currentScene.activeCamera.attachControl(that.canvas);
  16987. }
  16988. if (that.sceneLoadedCallback) {
  16989. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  16990. }
  16991. that.engine.runRenderLoop(function () {
  16992. that.renderFunction();
  16993. });
  16994. });
  16995. }, function (progress) {
  16996. if (_this.progressCallback) {
  16997. _this.progressCallback(progress);
  16998. }
  16999. });
  17000. }
  17001. else {
  17002. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  17003. }
  17004. }
  17005. };
  17006. FilesInput.FilesTextures = new Array();
  17007. FilesInput.FilesToLoad = new Array();
  17008. return FilesInput;
  17009. })();
  17010. BABYLON.FilesInput = FilesInput;
  17011. })(BABYLON || (BABYLON = {}));
  17012. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  17013. (function (BABYLON) {
  17014. var OimoJSPlugin = (function () {
  17015. function OimoJSPlugin() {
  17016. this._registeredMeshes = [];
  17017. /**
  17018. * Update the body position according to the mesh position
  17019. * @param mesh
  17020. */
  17021. this.updateBodyPosition = function (mesh) {
  17022. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17023. var registeredMesh = this._registeredMeshes[index];
  17024. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17025. var body = registeredMesh.body.body;
  17026. mesh.computeWorldMatrix(true);
  17027. var center = mesh.getBoundingInfo().boundingBox.center;
  17028. body.setPosition(center.x, center.y, center.z);
  17029. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  17030. return;
  17031. }
  17032. // Case where the parent has been updated
  17033. if (registeredMesh.mesh.parent === mesh) {
  17034. mesh.computeWorldMatrix(true);
  17035. registeredMesh.mesh.computeWorldMatrix(true);
  17036. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  17037. var absoluteRotation = mesh.rotation;
  17038. body = registeredMesh.body.body;
  17039. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  17040. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  17041. return;
  17042. }
  17043. }
  17044. };
  17045. }
  17046. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  17047. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17048. };
  17049. OimoJSPlugin.prototype.initialize = function (iterations) {
  17050. this._world = new OIMO.World();
  17051. this._world.clear();
  17052. };
  17053. OimoJSPlugin.prototype.setGravity = function (gravity) {
  17054. this._world.gravity = gravity;
  17055. };
  17056. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17057. var body = null;
  17058. this.unregisterMesh(mesh);
  17059. mesh.computeWorldMatrix(true);
  17060. switch (impostor) {
  17061. case BABYLON.PhysicsEngine.SphereImpostor:
  17062. var initialRotation = null;
  17063. if (mesh.rotationQuaternion) {
  17064. initialRotation = mesh.rotationQuaternion.clone();
  17065. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17066. mesh.computeWorldMatrix(true);
  17067. }
  17068. var bbox = mesh.getBoundingInfo().boundingBox;
  17069. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17070. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17071. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17072. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17073. // The delta between the mesh position and the mesh bounding box center
  17074. var deltaPosition = mesh.position.subtract(bbox.center);
  17075. // Transform delta position with the rotation
  17076. if (initialRotation) {
  17077. var m = new BABYLON.Matrix();
  17078. initialRotation.toRotationMatrix(m);
  17079. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  17080. }
  17081. body = new OIMO.Body({
  17082. type: 'sphere',
  17083. size: [size],
  17084. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17085. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17086. move: options.mass != 0,
  17087. config: [options.mass, options.friction, options.restitution],
  17088. world: this._world
  17089. });
  17090. // Restore rotation
  17091. if (initialRotation) {
  17092. body.setQuaternion(initialRotation);
  17093. }
  17094. this._registeredMeshes.push({
  17095. mesh: mesh,
  17096. body: body,
  17097. delta: deltaPosition
  17098. });
  17099. break;
  17100. case BABYLON.PhysicsEngine.PlaneImpostor:
  17101. case BABYLON.PhysicsEngine.BoxImpostor:
  17102. initialRotation = null;
  17103. if (mesh.rotationQuaternion) {
  17104. initialRotation = mesh.rotationQuaternion.clone();
  17105. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17106. mesh.computeWorldMatrix(true);
  17107. }
  17108. bbox = mesh.getBoundingInfo().boundingBox;
  17109. var min = bbox.minimumWorld;
  17110. var max = bbox.maximumWorld;
  17111. var box = max.subtract(min);
  17112. var sizeX = this._checkWithEpsilon(box.x);
  17113. var sizeY = this._checkWithEpsilon(box.y);
  17114. var sizeZ = this._checkWithEpsilon(box.z);
  17115. // The delta between the mesh position and the mesh boudning box center
  17116. deltaPosition = mesh.position.subtract(bbox.center);
  17117. // Transform delta position with the rotation
  17118. if (initialRotation) {
  17119. m = new BABYLON.Matrix();
  17120. initialRotation.toRotationMatrix(m);
  17121. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  17122. }
  17123. body = new OIMO.Body({
  17124. type: 'box',
  17125. size: [sizeX, sizeY, sizeZ],
  17126. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17127. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17128. move: options.mass != 0,
  17129. config: [options.mass, options.friction, options.restitution],
  17130. world: this._world
  17131. });
  17132. if (initialRotation) {
  17133. body.setQuaternion(initialRotation);
  17134. }
  17135. this._registeredMeshes.push({
  17136. mesh: mesh,
  17137. body: body,
  17138. delta: deltaPosition
  17139. });
  17140. break;
  17141. }
  17142. return body;
  17143. };
  17144. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  17145. var types = [], sizes = [], positions = [], rotations = [];
  17146. var initialMesh = parts[0].mesh;
  17147. for (var index = 0; index < parts.length; index++) {
  17148. var part = parts[index];
  17149. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  17150. types.push(bodyParameters.type);
  17151. sizes.push.apply(sizes, bodyParameters.size);
  17152. positions.push.apply(positions, bodyParameters.pos);
  17153. rotations.push.apply(rotations, bodyParameters.rot);
  17154. }
  17155. var body = new OIMO.Body({
  17156. type: types,
  17157. size: sizes,
  17158. pos: positions,
  17159. rot: rotations,
  17160. move: options.mass != 0,
  17161. config: [options.mass, options.friction, options.restitution],
  17162. world: this._world
  17163. });
  17164. this._registeredMeshes.push({
  17165. mesh: initialMesh,
  17166. body: body
  17167. });
  17168. return body;
  17169. };
  17170. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  17171. var bodyParameters = null;
  17172. var mesh = part.mesh;
  17173. // We need the bounding box/sphere info to compute the physics body
  17174. mesh.computeWorldMatrix();
  17175. switch (part.impostor) {
  17176. case BABYLON.PhysicsEngine.SphereImpostor:
  17177. var bbox = mesh.getBoundingInfo().boundingBox;
  17178. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17179. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17180. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17181. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17182. bodyParameters = {
  17183. type: 'sphere',
  17184. /* bug with oimo : sphere needs 3 sizes in this case */
  17185. size: [size, -1, -1],
  17186. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  17187. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17188. };
  17189. break;
  17190. case BABYLON.PhysicsEngine.PlaneImpostor:
  17191. case BABYLON.PhysicsEngine.BoxImpostor:
  17192. bbox = mesh.getBoundingInfo().boundingBox;
  17193. var min = bbox.minimumWorld;
  17194. var max = bbox.maximumWorld;
  17195. var box = max.subtract(min);
  17196. var sizeX = this._checkWithEpsilon(box.x);
  17197. var sizeY = this._checkWithEpsilon(box.y);
  17198. var sizeZ = this._checkWithEpsilon(box.z);
  17199. var relativePosition = mesh.position;
  17200. bodyParameters = {
  17201. type: 'box',
  17202. size: [sizeX, sizeY, sizeZ],
  17203. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  17204. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17205. };
  17206. break;
  17207. }
  17208. return bodyParameters;
  17209. };
  17210. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  17211. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17212. var registeredMesh = this._registeredMeshes[index];
  17213. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17214. if (registeredMesh.body) {
  17215. this._world.removeRigidBody(registeredMesh.body.body);
  17216. this._unbindBody(registeredMesh.body);
  17217. }
  17218. this._registeredMeshes.splice(index, 1);
  17219. return;
  17220. }
  17221. }
  17222. };
  17223. OimoJSPlugin.prototype._unbindBody = function (body) {
  17224. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17225. var registeredMesh = this._registeredMeshes[index];
  17226. if (registeredMesh.body === body) {
  17227. registeredMesh.body = null;
  17228. }
  17229. }
  17230. };
  17231. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17232. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17233. var registeredMesh = this._registeredMeshes[index];
  17234. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17235. // Get object mass to have a behaviour similar to cannon.js
  17236. var mass = registeredMesh.body.body.massInfo.mass;
  17237. // The force is scaled with the mass of object
  17238. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  17239. return;
  17240. }
  17241. }
  17242. };
  17243. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17244. var body1 = null, body2 = null;
  17245. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17246. var registeredMesh = this._registeredMeshes[index];
  17247. if (registeredMesh.mesh === mesh1) {
  17248. body1 = registeredMesh.body.body;
  17249. }
  17250. else if (registeredMesh.mesh === mesh2) {
  17251. body2 = registeredMesh.body.body;
  17252. }
  17253. }
  17254. if (!body1 || !body2) {
  17255. return false;
  17256. }
  17257. if (!options) {
  17258. options = {};
  17259. }
  17260. new OIMO.Link({
  17261. type: options.type,
  17262. body1: body1,
  17263. body2: body2,
  17264. min: options.min,
  17265. max: options.max,
  17266. axe1: options.axe1,
  17267. axe2: options.axe2,
  17268. pos1: [pivot1.x, pivot1.y, pivot1.z],
  17269. pos2: [pivot2.x, pivot2.y, pivot2.z],
  17270. collision: options.collision,
  17271. spring: options.spring,
  17272. world: this._world
  17273. });
  17274. return true;
  17275. };
  17276. OimoJSPlugin.prototype.dispose = function () {
  17277. this._world.clear();
  17278. while (this._registeredMeshes.length) {
  17279. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17280. }
  17281. };
  17282. OimoJSPlugin.prototype.isSupported = function () {
  17283. return OIMO !== undefined;
  17284. };
  17285. OimoJSPlugin.prototype._getLastShape = function (body) {
  17286. var lastShape = body.shapes;
  17287. while (lastShape.next) {
  17288. lastShape = lastShape.next;
  17289. }
  17290. return lastShape;
  17291. };
  17292. OimoJSPlugin.prototype.runOneStep = function (time) {
  17293. this._world.step();
  17294. // Update the position of all registered meshes
  17295. var i = this._registeredMeshes.length;
  17296. var m;
  17297. while (i--) {
  17298. var body = this._registeredMeshes[i].body.body;
  17299. var mesh = this._registeredMeshes[i].mesh;
  17300. var delta = this._registeredMeshes[i].delta;
  17301. if (!body.sleeping) {
  17302. if (body.shapes.next) {
  17303. var parentShape = this._getLastShape(body);
  17304. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  17305. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  17306. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  17307. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  17308. if (!mesh.rotationQuaternion) {
  17309. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17310. }
  17311. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17312. mesh.computeWorldMatrix();
  17313. }
  17314. else {
  17315. m = body.getMatrix();
  17316. mtx = BABYLON.Matrix.FromArray(m);
  17317. // Body position
  17318. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  17319. if (!delta) {
  17320. mesh.position.x = bodyX;
  17321. mesh.position.y = bodyY;
  17322. mesh.position.z = bodyZ;
  17323. }
  17324. else {
  17325. mesh.position.x = bodyX + delta.x;
  17326. mesh.position.y = bodyY + delta.y;
  17327. mesh.position.z = bodyZ + delta.z;
  17328. }
  17329. if (!mesh.rotationQuaternion) {
  17330. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17331. }
  17332. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17333. mesh.computeWorldMatrix();
  17334. }
  17335. }
  17336. }
  17337. };
  17338. return OimoJSPlugin;
  17339. })();
  17340. BABYLON.OimoJSPlugin = OimoJSPlugin;
  17341. })(BABYLON || (BABYLON = {}));
  17342. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  17343. (function (BABYLON) {
  17344. var PhysicsEngine = (function () {
  17345. function PhysicsEngine(plugin) {
  17346. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  17347. }
  17348. PhysicsEngine.prototype._initialize = function (gravity) {
  17349. this._currentPlugin.initialize();
  17350. this._setGravity(gravity);
  17351. };
  17352. PhysicsEngine.prototype._runOneStep = function (delta) {
  17353. if (delta > 0.1) {
  17354. delta = 0.1;
  17355. }
  17356. else if (delta <= 0) {
  17357. delta = 1.0 / 60.0;
  17358. }
  17359. this._currentPlugin.runOneStep(delta);
  17360. };
  17361. PhysicsEngine.prototype._setGravity = function (gravity) {
  17362. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  17363. this._currentPlugin.setGravity(this.gravity);
  17364. };
  17365. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  17366. return this._currentPlugin.registerMesh(mesh, impostor, options);
  17367. };
  17368. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  17369. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  17370. };
  17371. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  17372. this._currentPlugin.unregisterMesh(mesh);
  17373. };
  17374. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  17375. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  17376. };
  17377. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17378. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  17379. };
  17380. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  17381. this._currentPlugin.updateBodyPosition(mesh);
  17382. };
  17383. PhysicsEngine.prototype.dispose = function () {
  17384. this._currentPlugin.dispose();
  17385. };
  17386. PhysicsEngine.prototype.isSupported = function () {
  17387. return this._currentPlugin.isSupported();
  17388. };
  17389. // Statics
  17390. PhysicsEngine.NoImpostor = 0;
  17391. PhysicsEngine.SphereImpostor = 1;
  17392. PhysicsEngine.BoxImpostor = 2;
  17393. PhysicsEngine.PlaneImpostor = 3;
  17394. PhysicsEngine.MeshImpostor = 4;
  17395. PhysicsEngine.CapsuleImpostor = 5;
  17396. PhysicsEngine.ConeImpostor = 6;
  17397. PhysicsEngine.CylinderImpostor = 7;
  17398. PhysicsEngine.ConvexHullImpostor = 8;
  17399. PhysicsEngine.Epsilon = 0.001;
  17400. return PhysicsEngine;
  17401. })();
  17402. BABYLON.PhysicsEngine = PhysicsEngine;
  17403. })(BABYLON || (BABYLON = {}));
  17404. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  17405. (function (BABYLON) {
  17406. var serializeLight = function (light) {
  17407. var serializationObject = {};
  17408. serializationObject.name = light.name;
  17409. serializationObject.id = light.id;
  17410. serializationObject.tags = BABYLON.Tags.GetTags(light);
  17411. if (light instanceof BABYLON.PointLight) {
  17412. serializationObject.type = 0;
  17413. serializationObject.position = light.position.asArray();
  17414. }
  17415. else if (light instanceof BABYLON.DirectionalLight) {
  17416. serializationObject.type = 1;
  17417. var directionalLight = light;
  17418. serializationObject.position = directionalLight.position.asArray();
  17419. serializationObject.direction = directionalLight.direction.asArray();
  17420. }
  17421. else if (light instanceof BABYLON.SpotLight) {
  17422. serializationObject.type = 2;
  17423. var spotLight = light;
  17424. serializationObject.position = spotLight.position.asArray();
  17425. serializationObject.direction = spotLight.position.asArray();
  17426. serializationObject.angle = spotLight.angle;
  17427. serializationObject.exponent = spotLight.exponent;
  17428. }
  17429. else if (light instanceof BABYLON.HemisphericLight) {
  17430. serializationObject.type = 3;
  17431. var hemisphericLight = light;
  17432. serializationObject.direction = hemisphericLight.direction.asArray();
  17433. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  17434. }
  17435. if (light.intensity) {
  17436. serializationObject.intensity = light.intensity;
  17437. }
  17438. serializationObject.range = light.range;
  17439. serializationObject.diffuse = light.diffuse.asArray();
  17440. serializationObject.specular = light.specular.asArray();
  17441. return serializationObject;
  17442. };
  17443. var serializeFresnelParameter = function (fresnelParameter) {
  17444. var serializationObject = {};
  17445. serializationObject.isEnabled = fresnelParameter.isEnabled;
  17446. serializationObject.leftColor = fresnelParameter.leftColor;
  17447. serializationObject.rightColor = fresnelParameter.rightColor;
  17448. serializationObject.bias = fresnelParameter.bias;
  17449. serializationObject.power = fresnelParameter.power;
  17450. return serializationObject;
  17451. };
  17452. var serializeCamera = function (camera) {
  17453. var serializationObject = {};
  17454. serializationObject.name = camera.name;
  17455. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  17456. serializationObject.id = camera.id;
  17457. serializationObject.position = camera.position.asArray();
  17458. // Parent
  17459. if (camera.parent) {
  17460. serializationObject.parentId = camera.parent.id;
  17461. }
  17462. // Target
  17463. serializationObject.rotation = camera.rotation.asArray();
  17464. // Locked target
  17465. if (camera.lockedTarget && camera.lockedTarget.id) {
  17466. serializationObject.lockedTargetId = camera.lockedTarget.id;
  17467. }
  17468. serializationObject.fov = camera.fov;
  17469. serializationObject.minZ = camera.minZ;
  17470. serializationObject.maxZ = camera.maxZ;
  17471. serializationObject.speed = camera.speed;
  17472. serializationObject.inertia = camera.inertia;
  17473. serializationObject.checkCollisions = camera.checkCollisions;
  17474. serializationObject.applyGravity = camera.applyGravity;
  17475. if (camera.ellipsoid) {
  17476. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  17477. }
  17478. // Animations
  17479. appendAnimations(camera, serializationObject);
  17480. // Layer mask
  17481. serializationObject.layerMask = camera.layerMask;
  17482. return serializationObject;
  17483. };
  17484. var appendAnimations = function (source, destination) {
  17485. if (source.animations) {
  17486. destination.animations = [];
  17487. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  17488. var animation = source.animations[animationIndex];
  17489. destination.animations.push(serializeAnimation(animation));
  17490. }
  17491. }
  17492. };
  17493. var serializeAnimation = function (animation) {
  17494. var serializationObject = {};
  17495. serializationObject.name = animation.name;
  17496. serializationObject.property = animation.targetProperty;
  17497. serializationObject.framePerSecond = animation.framePerSecond;
  17498. serializationObject.dataType = animation.dataType;
  17499. serializationObject.loopBehavior = animation.loopMode;
  17500. var dataType = animation.dataType;
  17501. serializationObject.keys = [];
  17502. var keys = animation.getKeys();
  17503. for (var index = 0; index < keys.length; index++) {
  17504. var animationKey = keys[index];
  17505. var key = {};
  17506. key.frame = animationKey.frame;
  17507. switch (dataType) {
  17508. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17509. key.values = [animationKey.value];
  17510. break;
  17511. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17512. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17513. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17514. key.values = animationKey.value.asArray();
  17515. break;
  17516. }
  17517. serializationObject.keys.push(key);
  17518. }
  17519. return serializationObject;
  17520. };
  17521. var serializeMultiMaterial = function (material) {
  17522. var serializationObject = {};
  17523. serializationObject.name = material.name;
  17524. serializationObject.id = material.id;
  17525. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17526. serializationObject.materials = [];
  17527. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  17528. var subMat = material.subMaterials[matIndex];
  17529. if (subMat) {
  17530. serializationObject.materials.push(subMat.id);
  17531. }
  17532. else {
  17533. serializationObject.materials.push(null);
  17534. }
  17535. }
  17536. return serializationObject;
  17537. };
  17538. var serializeMaterial = function (material) {
  17539. var serializationObject = {};
  17540. serializationObject.name = material.name;
  17541. serializationObject.ambient = material.ambientColor.asArray();
  17542. serializationObject.diffuse = material.diffuseColor.asArray();
  17543. serializationObject.specular = material.specularColor.asArray();
  17544. serializationObject.specularPower = material.specularPower;
  17545. serializationObject.emissive = material.emissiveColor.asArray();
  17546. serializationObject.alpha = material.alpha;
  17547. serializationObject.id = material.id;
  17548. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17549. serializationObject.backFaceCulling = material.backFaceCulling;
  17550. if (material.diffuseTexture) {
  17551. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  17552. }
  17553. if (material.diffuseFresnelParameters) {
  17554. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  17555. }
  17556. if (material.ambientTexture) {
  17557. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  17558. }
  17559. if (material.opacityTexture) {
  17560. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  17561. }
  17562. if (material.opacityFresnelParameters) {
  17563. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  17564. }
  17565. if (material.reflectionTexture) {
  17566. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  17567. }
  17568. if (material.reflectionFresnelParameters) {
  17569. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  17570. }
  17571. if (material.emissiveTexture) {
  17572. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  17573. }
  17574. if (material.emissiveFresnelParameters) {
  17575. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  17576. }
  17577. if (material.specularTexture) {
  17578. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  17579. }
  17580. if (material.bumpTexture) {
  17581. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  17582. }
  17583. return serializationObject;
  17584. };
  17585. var serializeTexture = function (texture) {
  17586. var serializationObject = {};
  17587. if (!texture.name) {
  17588. return null;
  17589. }
  17590. if (texture instanceof BABYLON.CubeTexture) {
  17591. serializationObject.name = texture.name;
  17592. serializationObject.hasAlpha = texture.hasAlpha;
  17593. serializationObject.level = texture.level;
  17594. serializationObject.coordinatesMode = texture.coordinatesMode;
  17595. return serializationObject;
  17596. }
  17597. if (texture instanceof BABYLON.MirrorTexture) {
  17598. var mirrorTexture = texture;
  17599. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  17600. serializationObject.renderList = [];
  17601. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  17602. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  17603. }
  17604. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  17605. }
  17606. else if (texture instanceof BABYLON.RenderTargetTexture) {
  17607. var renderTargetTexture = texture;
  17608. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  17609. serializationObject.renderList = [];
  17610. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  17611. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  17612. }
  17613. }
  17614. var regularTexture = texture;
  17615. serializationObject.name = texture.name;
  17616. serializationObject.hasAlpha = texture.hasAlpha;
  17617. serializationObject.level = texture.level;
  17618. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  17619. serializationObject.coordinatesMode = texture.coordinatesMode;
  17620. serializationObject.uOffset = regularTexture.uOffset;
  17621. serializationObject.vOffset = regularTexture.vOffset;
  17622. serializationObject.uScale = regularTexture.uScale;
  17623. serializationObject.vScale = regularTexture.vScale;
  17624. serializationObject.uAng = regularTexture.uAng;
  17625. serializationObject.vAng = regularTexture.vAng;
  17626. serializationObject.wAng = regularTexture.wAng;
  17627. serializationObject.wrapU = texture.wrapU;
  17628. serializationObject.wrapV = texture.wrapV;
  17629. // Animations
  17630. appendAnimations(texture, serializationObject);
  17631. return serializationObject;
  17632. };
  17633. var serializeSkeleton = function (skeleton) {
  17634. var serializationObject = {};
  17635. serializationObject.name = skeleton.name;
  17636. serializationObject.id = skeleton.id;
  17637. serializationObject.bones = [];
  17638. for (var index = 0; index < skeleton.bones.length; index++) {
  17639. var bone = skeleton.bones[index];
  17640. var serializedBone = {
  17641. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  17642. name: bone.name,
  17643. matrix: bone.getLocalMatrix().toArray()
  17644. };
  17645. serializationObject.bones.push(serializedBone);
  17646. if (bone.animations && bone.animations.length > 0) {
  17647. serializedBone.animation = serializeAnimation(bone.animations[0]);
  17648. }
  17649. }
  17650. return serializationObject;
  17651. };
  17652. var serializeParticleSystem = function (particleSystem) {
  17653. var serializationObject = {};
  17654. serializationObject.emitterId = particleSystem.emitter.id;
  17655. serializationObject.capacity = particleSystem.getCapacity();
  17656. if (particleSystem.particleTexture) {
  17657. serializationObject.textureName = particleSystem.particleTexture.name;
  17658. }
  17659. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  17660. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  17661. serializationObject.minSize = particleSystem.minSize;
  17662. serializationObject.maxSize = particleSystem.maxSize;
  17663. serializationObject.minLifeTime = particleSystem.minLifeTime;
  17664. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  17665. serializationObject.emitRate = particleSystem.emitRate;
  17666. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  17667. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  17668. serializationObject.gravity = particleSystem.gravity.asArray();
  17669. serializationObject.direction1 = particleSystem.direction1.asArray();
  17670. serializationObject.direction2 = particleSystem.direction2.asArray();
  17671. serializationObject.color1 = particleSystem.color1.asArray();
  17672. serializationObject.color2 = particleSystem.color2.asArray();
  17673. serializationObject.colorDead = particleSystem.colorDead.asArray();
  17674. serializationObject.updateSpeed = particleSystem.updateSpeed;
  17675. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  17676. serializationObject.textureMask = particleSystem.textureMask.asArray();
  17677. serializationObject.blendMode = particleSystem.blendMode;
  17678. return serializationObject;
  17679. };
  17680. var serializeLensFlareSystem = function (lensFlareSystem) {
  17681. var serializationObject = {};
  17682. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  17683. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  17684. serializationObject.flares = [];
  17685. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  17686. var flare = lensFlareSystem.lensFlares[index];
  17687. serializationObject.flares.push({
  17688. size: flare.size,
  17689. position: flare.position,
  17690. color: flare.color.asArray(),
  17691. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  17692. });
  17693. }
  17694. return serializationObject;
  17695. };
  17696. var serializeShadowGenerator = function (light) {
  17697. var serializationObject = {};
  17698. var shadowGenerator = light.getShadowGenerator();
  17699. serializationObject.lightId = light.id;
  17700. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  17701. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  17702. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  17703. serializationObject.renderList = [];
  17704. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  17705. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  17706. serializationObject.renderList.push(mesh.id);
  17707. }
  17708. return serializationObject;
  17709. };
  17710. var serializedGeometries = [];
  17711. var serializeGeometry = function (geometry, serializationGeometries) {
  17712. if (serializedGeometries[geometry.id]) {
  17713. return;
  17714. }
  17715. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  17716. serializationGeometries.boxes.push(serializeBox(geometry));
  17717. }
  17718. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  17719. serializationGeometries.spheres.push(serializeSphere(geometry));
  17720. }
  17721. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  17722. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  17723. }
  17724. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  17725. serializationGeometries.toruses.push(serializeTorus(geometry));
  17726. }
  17727. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  17728. serializationGeometries.grounds.push(serializeGround(geometry));
  17729. }
  17730. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  17731. serializationGeometries.planes.push(serializePlane(geometry));
  17732. }
  17733. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  17734. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  17735. }
  17736. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  17737. throw new Error("Unknow primitive type");
  17738. }
  17739. else {
  17740. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  17741. }
  17742. serializedGeometries[geometry.id] = true;
  17743. };
  17744. var serializeGeometryBase = function (geometry) {
  17745. var serializationObject = {};
  17746. serializationObject.id = geometry.id;
  17747. if (BABYLON.Tags.HasTags(geometry)) {
  17748. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  17749. }
  17750. return serializationObject;
  17751. };
  17752. var serializeVertexData = function (vertexData) {
  17753. var serializationObject = serializeGeometryBase(vertexData);
  17754. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17755. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17756. }
  17757. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17758. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17759. }
  17760. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17761. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17762. }
  17763. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17764. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  17765. }
  17766. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17767. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  17768. }
  17769. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17770. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17771. serializationObject.matricesIndices._isExpanded = true;
  17772. }
  17773. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17774. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17775. }
  17776. serializationObject.indices = vertexData.getIndices();
  17777. return serializationObject;
  17778. };
  17779. var serializePrimitive = function (primitive) {
  17780. var serializationObject = serializeGeometryBase(primitive);
  17781. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  17782. return serializationObject;
  17783. };
  17784. var serializeBox = function (box) {
  17785. var serializationObject = serializePrimitive(box);
  17786. serializationObject.size = box.size;
  17787. return serializationObject;
  17788. };
  17789. var serializeSphere = function (sphere) {
  17790. var serializationObject = serializePrimitive(sphere);
  17791. serializationObject.segments = sphere.segments;
  17792. serializationObject.diameter = sphere.diameter;
  17793. return serializationObject;
  17794. };
  17795. var serializeCylinder = function (cylinder) {
  17796. var serializationObject = serializePrimitive(cylinder);
  17797. serializationObject.height = cylinder.height;
  17798. serializationObject.diameterTop = cylinder.diameterTop;
  17799. serializationObject.diameterBottom = cylinder.diameterBottom;
  17800. serializationObject.tessellation = cylinder.tessellation;
  17801. return serializationObject;
  17802. };
  17803. var serializeTorus = function (torus) {
  17804. var serializationObject = serializePrimitive(torus);
  17805. serializationObject.diameter = torus.diameter;
  17806. serializationObject.thickness = torus.thickness;
  17807. serializationObject.tessellation = torus.tessellation;
  17808. return serializationObject;
  17809. };
  17810. var serializeGround = function (ground) {
  17811. var serializationObject = serializePrimitive(ground);
  17812. serializationObject.width = ground.width;
  17813. serializationObject.height = ground.height;
  17814. serializationObject.subdivisions = ground.subdivisions;
  17815. return serializationObject;
  17816. };
  17817. var serializePlane = function (plane) {
  17818. var serializationObject = serializePrimitive(plane);
  17819. serializationObject.size = plane.size;
  17820. return serializationObject;
  17821. };
  17822. var serializeTorusKnot = function (torusKnot) {
  17823. var serializationObject = serializePrimitive(torusKnot);
  17824. serializationObject.radius = torusKnot.radius;
  17825. serializationObject.tube = torusKnot.tube;
  17826. serializationObject.radialSegments = torusKnot.radialSegments;
  17827. serializationObject.tubularSegments = torusKnot.tubularSegments;
  17828. serializationObject.p = torusKnot.p;
  17829. serializationObject.q = torusKnot.q;
  17830. return serializationObject;
  17831. };
  17832. var serializeMesh = function (mesh, serializationScene) {
  17833. var serializationObject = {};
  17834. serializationObject.name = mesh.name;
  17835. serializationObject.id = mesh.id;
  17836. if (BABYLON.Tags.HasTags(mesh)) {
  17837. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  17838. }
  17839. serializationObject.position = mesh.position.asArray();
  17840. if (mesh.rotationQuaternion) {
  17841. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  17842. }
  17843. else if (mesh.rotation) {
  17844. serializationObject.rotation = mesh.rotation.asArray();
  17845. }
  17846. serializationObject.scaling = mesh.scaling.asArray();
  17847. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  17848. serializationObject.isEnabled = mesh.isEnabled();
  17849. serializationObject.isVisible = mesh.isVisible;
  17850. serializationObject.infiniteDistance = mesh.infiniteDistance;
  17851. serializationObject.pickable = mesh.isPickable;
  17852. serializationObject.receiveShadows = mesh.receiveShadows;
  17853. serializationObject.billboardMode = mesh.billboardMode;
  17854. serializationObject.visibility = mesh.visibility;
  17855. serializationObject.checkCollisions = mesh.checkCollisions;
  17856. // Parent
  17857. if (mesh.parent) {
  17858. serializationObject.parentId = mesh.parent.id;
  17859. }
  17860. // Geometry
  17861. var geometry = mesh._geometry;
  17862. if (geometry) {
  17863. var geometryId = geometry.id;
  17864. serializationObject.geometryId = geometryId;
  17865. if (!mesh.getScene().getGeometryByID(geometryId)) {
  17866. // 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
  17867. serializeGeometry(geometry, serializationScene.geometries);
  17868. }
  17869. // SubMeshes
  17870. serializationObject.subMeshes = [];
  17871. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17872. var subMesh = mesh.subMeshes[subIndex];
  17873. serializationObject.subMeshes.push({
  17874. materialIndex: subMesh.materialIndex,
  17875. verticesStart: subMesh.verticesStart,
  17876. verticesCount: subMesh.verticesCount,
  17877. indexStart: subMesh.indexStart,
  17878. indexCount: subMesh.indexCount
  17879. });
  17880. }
  17881. }
  17882. // Material
  17883. if (mesh.material) {
  17884. serializationObject.materialId = mesh.material.id;
  17885. }
  17886. else {
  17887. mesh.material = null;
  17888. }
  17889. // Skeleton
  17890. if (mesh.skeleton) {
  17891. serializationObject.skeletonId = mesh.skeleton.id;
  17892. }
  17893. // Physics
  17894. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  17895. serializationObject.physicsMass = mesh.getPhysicsMass();
  17896. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  17897. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  17898. switch (mesh.getPhysicsImpostor()) {
  17899. case BABYLON.PhysicsEngine.BoxImpostor:
  17900. serializationObject.physicsImpostor = 1;
  17901. break;
  17902. case BABYLON.PhysicsEngine.SphereImpostor:
  17903. serializationObject.physicsImpostor = 2;
  17904. break;
  17905. }
  17906. }
  17907. // Instances
  17908. serializationObject.instances = [];
  17909. for (var index = 0; index < mesh.instances.length; index++) {
  17910. var instance = mesh.instances[index];
  17911. var serializationInstance = {
  17912. name: instance.name,
  17913. position: instance.position,
  17914. rotation: instance.rotation,
  17915. rotationQuaternion: instance.rotationQuaternion,
  17916. scaling: instance.scaling
  17917. };
  17918. serializationObject.instances.push(serializationInstance);
  17919. // Animations
  17920. appendAnimations(instance, serializationInstance);
  17921. }
  17922. // Animations
  17923. appendAnimations(mesh, serializationObject);
  17924. // Layer mask
  17925. serializationObject.layerMask = mesh.layerMask;
  17926. return serializationObject;
  17927. };
  17928. var SceneSerializer = (function () {
  17929. function SceneSerializer() {
  17930. }
  17931. SceneSerializer.Serialize = function (scene) {
  17932. var serializationObject = {};
  17933. // Scene
  17934. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  17935. serializationObject.autoClear = scene.autoClear;
  17936. serializationObject.clearColor = scene.clearColor.asArray();
  17937. serializationObject.ambientColor = scene.ambientColor.asArray();
  17938. serializationObject.gravity = scene.gravity.asArray();
  17939. // Fog
  17940. if (scene.fogMode && scene.fogMode !== 0) {
  17941. serializationObject.fogMode = scene.fogMode;
  17942. serializationObject.fogColor = scene.fogColor.asArray();
  17943. serializationObject.fogStart = scene.fogStart;
  17944. serializationObject.fogEnd = scene.fogEnd;
  17945. serializationObject.fogDensity = scene.fogDensity;
  17946. }
  17947. // Lights
  17948. serializationObject.lights = [];
  17949. for (var index = 0; index < scene.lights.length; index++) {
  17950. var light = scene.lights[index];
  17951. serializationObject.lights.push(serializeLight(light));
  17952. }
  17953. // Cameras
  17954. serializationObject.cameras = [];
  17955. for (index = 0; index < scene.cameras.length; index++) {
  17956. var camera = scene.cameras[index];
  17957. if (camera instanceof BABYLON.FreeCamera) {
  17958. serializationObject.cameras.push(serializeCamera(camera));
  17959. }
  17960. }
  17961. if (scene.activeCamera) {
  17962. serializationObject.activeCameraID = scene.activeCamera.id;
  17963. }
  17964. // Materials
  17965. serializationObject.materials = [];
  17966. serializationObject.multiMaterials = [];
  17967. for (index = 0; index < scene.materials.length; index++) {
  17968. var material = scene.materials[index];
  17969. if (material instanceof BABYLON.StandardMaterial) {
  17970. serializationObject.materials.push(serializeMaterial(material));
  17971. }
  17972. else if (material instanceof BABYLON.MultiMaterial) {
  17973. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  17974. }
  17975. }
  17976. // Skeletons
  17977. serializationObject.skeletons = [];
  17978. for (index = 0; index < scene.skeletons.length; index++) {
  17979. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  17980. }
  17981. // Geometries
  17982. serializationObject.geometries = {};
  17983. serializationObject.geometries.boxes = [];
  17984. serializationObject.geometries.spheres = [];
  17985. serializationObject.geometries.cylinders = [];
  17986. serializationObject.geometries.toruses = [];
  17987. serializationObject.geometries.grounds = [];
  17988. serializationObject.geometries.planes = [];
  17989. serializationObject.geometries.torusKnots = [];
  17990. serializationObject.geometries.vertexData = [];
  17991. serializedGeometries = [];
  17992. var geometries = scene.getGeometries();
  17993. for (var index = 0; index < geometries.length; index++) {
  17994. var geometry = geometries[index];
  17995. if (geometry.isReady()) {
  17996. serializeGeometry(geometry, serializationObject.geometries);
  17997. }
  17998. }
  17999. // Meshes
  18000. serializationObject.meshes = [];
  18001. for (index = 0; index < scene.meshes.length; index++) {
  18002. var abstractMesh = scene.meshes[index];
  18003. if (abstractMesh instanceof BABYLON.Mesh) {
  18004. var mesh = abstractMesh;
  18005. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  18006. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  18007. }
  18008. }
  18009. }
  18010. // Particles Systems
  18011. serializationObject.particleSystems = [];
  18012. for (index = 0; index < scene.particleSystems.length; index++) {
  18013. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  18014. }
  18015. // Lens flares
  18016. serializationObject.lensFlareSystems = [];
  18017. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  18018. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  18019. }
  18020. // Shadows
  18021. serializationObject.shadowGenerators = [];
  18022. for (index = 0; index < scene.lights.length; index++) {
  18023. light = scene.lights[index];
  18024. if (light.getShadowGenerator()) {
  18025. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  18026. }
  18027. }
  18028. return serializationObject;
  18029. };
  18030. return SceneSerializer;
  18031. })();
  18032. BABYLON.SceneSerializer = SceneSerializer;
  18033. })(BABYLON || (BABYLON = {}));
  18034. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  18035. (function (BABYLON) {
  18036. var SceneLoader = (function () {
  18037. function SceneLoader() {
  18038. }
  18039. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18040. get: function () {
  18041. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18042. },
  18043. set: function (value) {
  18044. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18045. },
  18046. enumerable: true,
  18047. configurable: true
  18048. });
  18049. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18050. get: function () {
  18051. return SceneLoader._ShowLoadingScreen;
  18052. },
  18053. set: function (value) {
  18054. SceneLoader._ShowLoadingScreen = value;
  18055. },
  18056. enumerable: true,
  18057. configurable: true
  18058. });
  18059. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18060. var dotPosition = sceneFilename.lastIndexOf(".");
  18061. var queryStringPosition = sceneFilename.indexOf("?");
  18062. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18063. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18064. var plugin = this._registeredPlugins[index];
  18065. if (plugin.extensions.indexOf(extension) !== -1) {
  18066. return plugin;
  18067. }
  18068. }
  18069. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18070. };
  18071. // Public functions
  18072. SceneLoader.RegisterPlugin = function (plugin) {
  18073. plugin.extensions = plugin.extensions.toLowerCase();
  18074. SceneLoader._registeredPlugins.push(plugin);
  18075. };
  18076. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18077. var manifestChecked = function (success) {
  18078. scene.database = database;
  18079. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18080. var importMeshFromData = function (data) {
  18081. var meshes = [];
  18082. var particleSystems = [];
  18083. var skeletons = [];
  18084. try {
  18085. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18086. if (onerror) {
  18087. onerror(scene, 'unable to load the scene');
  18088. }
  18089. return;
  18090. }
  18091. }
  18092. catch (e) {
  18093. if (onerror) {
  18094. onerror(scene, e);
  18095. }
  18096. return;
  18097. }
  18098. if (onsuccess) {
  18099. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18100. onsuccess(meshes, particleSystems, skeletons);
  18101. }
  18102. };
  18103. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18104. // Direct load
  18105. importMeshFromData(sceneFilename.substr(5));
  18106. return;
  18107. }
  18108. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18109. importMeshFromData(data);
  18110. }, progressCallBack, database);
  18111. };
  18112. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18113. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18114. };
  18115. /**
  18116. * Load a scene
  18117. * @param rootUrl a string that defines the root url for scene and resources
  18118. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18119. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18120. */
  18121. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18122. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18123. };
  18124. /**
  18125. * Append a scene
  18126. * @param rootUrl a string that defines the root url for scene and resources
  18127. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18128. * @param scene is the instance of BABYLON.Scene to append to
  18129. */
  18130. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18131. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18132. var database;
  18133. if (SceneLoader.ShowLoadingScreen) {
  18134. scene.getEngine().displayLoadingUI();
  18135. }
  18136. var loadSceneFromData = function (data) {
  18137. scene.database = database;
  18138. if (!plugin.load(scene, data, rootUrl)) {
  18139. if (onerror) {
  18140. onerror(scene);
  18141. }
  18142. scene.getEngine().hideLoadingUI();
  18143. return;
  18144. }
  18145. if (onsuccess) {
  18146. onsuccess(scene);
  18147. }
  18148. if (SceneLoader.ShowLoadingScreen) {
  18149. scene.executeWhenReady(function () {
  18150. scene.getEngine().hideLoadingUI();
  18151. });
  18152. }
  18153. };
  18154. var manifestChecked = function (success) {
  18155. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18156. };
  18157. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18158. // Direct load
  18159. loadSceneFromData(sceneFilename.substr(5));
  18160. return;
  18161. }
  18162. if (rootUrl.indexOf("file:") === -1) {
  18163. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18164. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18165. }
  18166. else {
  18167. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18168. }
  18169. };
  18170. // Flags
  18171. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18172. SceneLoader._ShowLoadingScreen = true;
  18173. // Members
  18174. SceneLoader._registeredPlugins = new Array();
  18175. return SceneLoader;
  18176. })();
  18177. BABYLON.SceneLoader = SceneLoader;
  18178. ;
  18179. })(BABYLON || (BABYLON = {}));
  18180. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  18181. (function (BABYLON) {
  18182. var Internals;
  18183. (function (Internals) {
  18184. var checkColors4 = function (colors, count) {
  18185. // Check if color3 was used
  18186. if (colors.length === count * 3) {
  18187. var colors4 = [];
  18188. for (var index = 0; index < colors.length; index += 3) {
  18189. var newIndex = (index / 3) * 4;
  18190. colors4[newIndex] = colors[index];
  18191. colors4[newIndex + 1] = colors[index + 1];
  18192. colors4[newIndex + 2] = colors[index + 2];
  18193. colors4[newIndex + 3] = 1.0;
  18194. }
  18195. return colors4;
  18196. }
  18197. return colors;
  18198. };
  18199. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18200. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18201. texture.name = parsedTexture.name;
  18202. texture.hasAlpha = parsedTexture.hasAlpha;
  18203. texture.level = parsedTexture.level;
  18204. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18205. return texture;
  18206. };
  18207. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18208. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18209. return null;
  18210. }
  18211. if (parsedTexture.isCube) {
  18212. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18213. }
  18214. var texture;
  18215. if (parsedTexture.mirrorPlane) {
  18216. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18217. texture._waitingRenderList = parsedTexture.renderList;
  18218. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18219. }
  18220. else if (parsedTexture.isRenderTarget) {
  18221. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18222. texture._waitingRenderList = parsedTexture.renderList;
  18223. }
  18224. else {
  18225. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18226. }
  18227. texture.name = parsedTexture.name;
  18228. texture.hasAlpha = parsedTexture.hasAlpha;
  18229. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18230. texture.level = parsedTexture.level;
  18231. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18232. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18233. texture.uOffset = parsedTexture.uOffset;
  18234. texture.vOffset = parsedTexture.vOffset;
  18235. texture.uScale = parsedTexture.uScale;
  18236. texture.vScale = parsedTexture.vScale;
  18237. texture.uAng = parsedTexture.uAng;
  18238. texture.vAng = parsedTexture.vAng;
  18239. texture.wAng = parsedTexture.wAng;
  18240. texture.wrapU = parsedTexture.wrapU;
  18241. texture.wrapV = parsedTexture.wrapV;
  18242. // Animations
  18243. if (parsedTexture.animations) {
  18244. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18245. var parsedAnimation = parsedTexture.animations[animationIndex];
  18246. texture.animations.push(parseAnimation(parsedAnimation));
  18247. }
  18248. }
  18249. return texture;
  18250. };
  18251. var parseSkeleton = function (parsedSkeleton, scene) {
  18252. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18253. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18254. var parsedBone = parsedSkeleton.bones[index];
  18255. var parentBone = null;
  18256. if (parsedBone.parentBoneIndex > -1) {
  18257. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18258. }
  18259. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18260. if (parsedBone.animation) {
  18261. bone.animations.push(parseAnimation(parsedBone.animation));
  18262. }
  18263. }
  18264. return skeleton;
  18265. };
  18266. var parseFresnelParameters = function (parsedFresnelParameters) {
  18267. var fresnelParameters = new BABYLON.FresnelParameters();
  18268. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18269. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18270. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18271. fresnelParameters.bias = parsedFresnelParameters.bias;
  18272. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18273. return fresnelParameters;
  18274. };
  18275. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18276. var material;
  18277. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18278. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18279. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18280. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18281. material.specularPower = parsedMaterial.specularPower;
  18282. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18283. material.alpha = parsedMaterial.alpha;
  18284. material.id = parsedMaterial.id;
  18285. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18286. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18287. material.wireframe = parsedMaterial.wireframe;
  18288. if (parsedMaterial.diffuseTexture) {
  18289. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18290. }
  18291. if (parsedMaterial.diffuseFresnelParameters) {
  18292. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18293. }
  18294. if (parsedMaterial.ambientTexture) {
  18295. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18296. }
  18297. if (parsedMaterial.opacityTexture) {
  18298. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18299. }
  18300. if (parsedMaterial.opacityFresnelParameters) {
  18301. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18302. }
  18303. if (parsedMaterial.reflectionTexture) {
  18304. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18305. }
  18306. if (parsedMaterial.reflectionFresnelParameters) {
  18307. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18308. }
  18309. if (parsedMaterial.emissiveTexture) {
  18310. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18311. }
  18312. if (parsedMaterial.emissiveFresnelParameters) {
  18313. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18314. }
  18315. if (parsedMaterial.specularTexture) {
  18316. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18317. }
  18318. if (parsedMaterial.bumpTexture) {
  18319. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18320. }
  18321. return material;
  18322. };
  18323. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18324. for (var index = 0; index < parsedData.materials.length; index++) {
  18325. var parsedMaterial = parsedData.materials[index];
  18326. if (parsedMaterial.id === id) {
  18327. return parseMaterial(parsedMaterial, scene, rootUrl);
  18328. }
  18329. }
  18330. return null;
  18331. };
  18332. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18333. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18334. multiMaterial.id = parsedMultiMaterial.id;
  18335. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18336. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18337. var subMatId = parsedMultiMaterial.materials[matIndex];
  18338. if (subMatId) {
  18339. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18340. }
  18341. else {
  18342. multiMaterial.subMaterials.push(null);
  18343. }
  18344. }
  18345. return multiMaterial;
  18346. };
  18347. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18348. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18349. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18350. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18351. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18352. var parsedFlare = parsedLensFlareSystem.flares[index];
  18353. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18354. }
  18355. return lensFlareSystem;
  18356. };
  18357. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18358. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18359. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18360. if (parsedParticleSystem.textureName) {
  18361. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18362. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18363. }
  18364. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18365. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18366. particleSystem.minSize = parsedParticleSystem.minSize;
  18367. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18368. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18369. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18370. particleSystem.emitter = emitter;
  18371. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18372. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18373. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18374. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18375. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18376. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18377. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18378. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18379. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18380. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18381. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18382. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18383. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18384. particleSystem.start();
  18385. return particleSystem;
  18386. };
  18387. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18388. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18389. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18390. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18391. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18392. shadowGenerator.getShadowMap().renderList.push(mesh);
  18393. }
  18394. if (parsedShadowGenerator.usePoissonSampling) {
  18395. shadowGenerator.usePoissonSampling = true;
  18396. }
  18397. else {
  18398. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  18399. }
  18400. return shadowGenerator;
  18401. };
  18402. var parseAnimation = function (parsedAnimation) {
  18403. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  18404. var dataType = parsedAnimation.dataType;
  18405. var keys = [];
  18406. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  18407. var key = parsedAnimation.keys[index];
  18408. var data;
  18409. switch (dataType) {
  18410. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18411. data = key.values[0];
  18412. break;
  18413. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18414. data = BABYLON.Quaternion.FromArray(key.values);
  18415. break;
  18416. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18417. data = BABYLON.Matrix.FromArray(key.values);
  18418. break;
  18419. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18420. default:
  18421. data = BABYLON.Vector3.FromArray(key.values);
  18422. break;
  18423. }
  18424. keys.push({
  18425. frame: key.frame,
  18426. value: data
  18427. });
  18428. }
  18429. animation.setKeys(keys);
  18430. return animation;
  18431. };
  18432. var parseLight = function (parsedLight, scene) {
  18433. var light;
  18434. switch (parsedLight.type) {
  18435. case 0:
  18436. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  18437. break;
  18438. case 1:
  18439. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18440. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  18441. break;
  18442. case 2:
  18443. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  18444. break;
  18445. case 3:
  18446. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18447. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  18448. break;
  18449. }
  18450. light.id = parsedLight.id;
  18451. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  18452. if (parsedLight.intensity !== undefined) {
  18453. light.intensity = parsedLight.intensity;
  18454. }
  18455. if (parsedLight.range) {
  18456. light.range = parsedLight.range;
  18457. }
  18458. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  18459. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  18460. if (parsedLight.excludedMeshesIds) {
  18461. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18462. }
  18463. // Parent
  18464. if (parsedLight.parentId) {
  18465. light._waitingParentId = parsedLight.parentId;
  18466. }
  18467. if (parsedLight.includedOnlyMeshesIds) {
  18468. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18469. }
  18470. // Animations
  18471. if (parsedLight.animations) {
  18472. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18473. var parsedAnimation = parsedLight.animations[animationIndex];
  18474. light.animations.push(parseAnimation(parsedAnimation));
  18475. }
  18476. }
  18477. if (parsedLight.autoAnimate) {
  18478. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  18479. }
  18480. };
  18481. var parseCamera = function (parsedCamera, scene) {
  18482. var camera;
  18483. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  18484. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  18485. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  18486. var alpha = parsedCamera.alpha;
  18487. var beta = parsedCamera.beta;
  18488. var radius = parsedCamera.radius;
  18489. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  18490. var eye_space = parsedCamera.eye_space;
  18491. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  18492. }
  18493. else {
  18494. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  18495. }
  18496. }
  18497. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  18498. eye_space = parsedCamera.eye_space;
  18499. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  18500. }
  18501. else if (parsedCamera.type === "DeviceOrientationCamera") {
  18502. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  18503. }
  18504. else if (parsedCamera.type === "FollowCamera") {
  18505. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  18506. camera.heightOffset = parsedCamera.heightOffset;
  18507. camera.radius = parsedCamera.radius;
  18508. camera.rotationOffset = parsedCamera.rotationOffset;
  18509. if (lockedTargetMesh)
  18510. camera.target = lockedTargetMesh;
  18511. }
  18512. else if (parsedCamera.type === "GamepadCamera") {
  18513. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  18514. }
  18515. else if (parsedCamera.type === "OculusCamera") {
  18516. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  18517. }
  18518. else if (parsedCamera.type === "OculusGamepadCamera") {
  18519. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  18520. }
  18521. else if (parsedCamera.type === "TouchCamera") {
  18522. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  18523. }
  18524. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  18525. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  18526. }
  18527. else if (parsedCamera.type === "WebVRCamera") {
  18528. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  18529. }
  18530. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  18531. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  18532. }
  18533. else {
  18534. // Free Camera is the default value
  18535. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  18536. }
  18537. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  18538. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  18539. camera.lockedTarget = lockedTargetMesh;
  18540. }
  18541. camera.id = parsedCamera.id;
  18542. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  18543. // Parent
  18544. if (parsedCamera.parentId) {
  18545. camera._waitingParentId = parsedCamera.parentId;
  18546. }
  18547. // Target
  18548. if (parsedCamera.target) {
  18549. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18550. }
  18551. else {
  18552. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  18553. }
  18554. camera.fov = parsedCamera.fov;
  18555. camera.minZ = parsedCamera.minZ;
  18556. camera.maxZ = parsedCamera.maxZ;
  18557. camera.speed = parsedCamera.speed;
  18558. camera.inertia = parsedCamera.inertia;
  18559. camera.checkCollisions = parsedCamera.checkCollisions;
  18560. camera.applyGravity = parsedCamera.applyGravity;
  18561. if (parsedCamera.ellipsoid) {
  18562. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  18563. }
  18564. // Animations
  18565. if (parsedCamera.animations) {
  18566. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18567. var parsedAnimation = parsedCamera.animations[animationIndex];
  18568. camera.animations.push(parseAnimation(parsedAnimation));
  18569. }
  18570. }
  18571. if (parsedCamera.autoAnimate) {
  18572. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  18573. }
  18574. // Layer Mask
  18575. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  18576. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  18577. }
  18578. else {
  18579. camera.layerMask = 0xFFFFFFFF;
  18580. }
  18581. return camera;
  18582. };
  18583. var parseGeometry = function (parsedGeometry, scene) {
  18584. var id = parsedGeometry.id;
  18585. return scene.getGeometryByID(id);
  18586. };
  18587. var parseBox = function (parsedBox, scene) {
  18588. if (parseGeometry(parsedBox, scene)) {
  18589. return null; // null since geometry could be something else than a box...
  18590. }
  18591. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  18592. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  18593. scene.pushGeometry(box, true);
  18594. return box;
  18595. };
  18596. var parseSphere = function (parsedSphere, scene) {
  18597. if (parseGeometry(parsedSphere, scene)) {
  18598. return null; // null since geometry could be something else than a sphere...
  18599. }
  18600. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  18601. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  18602. scene.pushGeometry(sphere, true);
  18603. return sphere;
  18604. };
  18605. var parseCylinder = function (parsedCylinder, scene) {
  18606. if (parseGeometry(parsedCylinder, scene)) {
  18607. return null; // null since geometry could be something else than a cylinder...
  18608. }
  18609. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  18610. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  18611. scene.pushGeometry(cylinder, true);
  18612. return cylinder;
  18613. };
  18614. var parseTorus = function (parsedTorus, scene) {
  18615. if (parseGeometry(parsedTorus, scene)) {
  18616. return null; // null since geometry could be something else than a torus...
  18617. }
  18618. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  18619. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  18620. scene.pushGeometry(torus, true);
  18621. return torus;
  18622. };
  18623. var parseGround = function (parsedGround, scene) {
  18624. if (parseGeometry(parsedGround, scene)) {
  18625. return null; // null since geometry could be something else than a ground...
  18626. }
  18627. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  18628. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  18629. scene.pushGeometry(ground, true);
  18630. return ground;
  18631. };
  18632. var parsePlane = function (parsedPlane, scene) {
  18633. if (parseGeometry(parsedPlane, scene)) {
  18634. return null; // null since geometry could be something else than a plane...
  18635. }
  18636. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  18637. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  18638. scene.pushGeometry(plane, true);
  18639. return plane;
  18640. };
  18641. var parseTorusKnot = function (parsedTorusKnot, scene) {
  18642. if (parseGeometry(parsedTorusKnot, scene)) {
  18643. return null; // null since geometry could be something else than a torusKnot...
  18644. }
  18645. 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);
  18646. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  18647. scene.pushGeometry(torusKnot, true);
  18648. return torusKnot;
  18649. };
  18650. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  18651. if (parseGeometry(parsedVertexData, scene)) {
  18652. return null; // null since geometry could be a primitive
  18653. }
  18654. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  18655. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  18656. if (parsedVertexData.delayLoadingFile) {
  18657. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18658. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  18659. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  18660. geometry._delayInfo = [];
  18661. if (parsedVertexData.hasUVs) {
  18662. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18663. }
  18664. if (parsedVertexData.hasUVs2) {
  18665. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18666. }
  18667. if (parsedVertexData.hasColors) {
  18668. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18669. }
  18670. if (parsedVertexData.hasMatricesIndices) {
  18671. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18672. }
  18673. if (parsedVertexData.hasMatricesWeights) {
  18674. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18675. }
  18676. geometry._delayLoadingFunction = importVertexData;
  18677. }
  18678. else {
  18679. importVertexData(parsedVertexData, geometry);
  18680. }
  18681. scene.pushGeometry(geometry, true);
  18682. return geometry;
  18683. };
  18684. var parseMesh = function (parsedMesh, scene, rootUrl) {
  18685. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  18686. mesh.id = parsedMesh.id;
  18687. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18688. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18689. if (parsedMesh.rotationQuaternion) {
  18690. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18691. }
  18692. else if (parsedMesh.rotation) {
  18693. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18694. }
  18695. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18696. if (parsedMesh.localMatrix) {
  18697. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18698. }
  18699. else if (parsedMesh.pivotMatrix) {
  18700. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18701. }
  18702. mesh.setEnabled(parsedMesh.isEnabled);
  18703. mesh.isVisible = parsedMesh.isVisible;
  18704. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18705. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18706. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18707. if (parsedMesh.applyFog !== undefined) {
  18708. mesh.applyFog = parsedMesh.applyFog;
  18709. }
  18710. if (parsedMesh.pickable !== undefined) {
  18711. mesh.isPickable = parsedMesh.pickable;
  18712. }
  18713. if (parsedMesh.alphaIndex !== undefined) {
  18714. mesh.alphaIndex = parsedMesh.alphaIndex;
  18715. }
  18716. mesh.receiveShadows = parsedMesh.receiveShadows;
  18717. mesh.billboardMode = parsedMesh.billboardMode;
  18718. if (parsedMesh.visibility !== undefined) {
  18719. mesh.visibility = parsedMesh.visibility;
  18720. }
  18721. mesh.checkCollisions = parsedMesh.checkCollisions;
  18722. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18723. // Parent
  18724. if (parsedMesh.parentId) {
  18725. mesh._waitingParentId = parsedMesh.parentId;
  18726. }
  18727. // Actions
  18728. if (parsedMesh.actions !== undefined) {
  18729. mesh._waitingActions = parsedMesh.actions;
  18730. }
  18731. // Geometry
  18732. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18733. if (parsedMesh.delayLoadingFile) {
  18734. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18735. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18736. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18737. if (parsedMesh._binaryInfo) {
  18738. mesh._binaryInfo = parsedMesh._binaryInfo;
  18739. }
  18740. mesh._delayInfo = [];
  18741. if (parsedMesh.hasUVs) {
  18742. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18743. }
  18744. if (parsedMesh.hasUVs2) {
  18745. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18746. }
  18747. if (parsedMesh.hasColors) {
  18748. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18749. }
  18750. if (parsedMesh.hasMatricesIndices) {
  18751. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18752. }
  18753. if (parsedMesh.hasMatricesWeights) {
  18754. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18755. }
  18756. mesh._delayLoadingFunction = importGeometry;
  18757. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18758. mesh._checkDelayState();
  18759. }
  18760. }
  18761. else {
  18762. importGeometry(parsedMesh, mesh);
  18763. }
  18764. // Material
  18765. if (parsedMesh.materialId) {
  18766. mesh.setMaterialByID(parsedMesh.materialId);
  18767. }
  18768. else {
  18769. mesh.material = null;
  18770. }
  18771. // Skeleton
  18772. if (parsedMesh.skeletonId > -1) {
  18773. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18774. }
  18775. // Physics
  18776. if (parsedMesh.physicsImpostor) {
  18777. if (!scene.isPhysicsEnabled()) {
  18778. scene.enablePhysics();
  18779. }
  18780. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  18781. }
  18782. // Animations
  18783. if (parsedMesh.animations) {
  18784. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18785. var parsedAnimation = parsedMesh.animations[animationIndex];
  18786. mesh.animations.push(parseAnimation(parsedAnimation));
  18787. }
  18788. }
  18789. if (parsedMesh.autoAnimate) {
  18790. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  18791. }
  18792. // Layer Mask
  18793. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18794. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18795. }
  18796. else {
  18797. mesh.layerMask = 0xFFFFFFFF;
  18798. }
  18799. // Instances
  18800. if (parsedMesh.instances) {
  18801. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18802. var parsedInstance = parsedMesh.instances[index];
  18803. var instance = mesh.createInstance(parsedInstance.name);
  18804. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18805. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18806. if (parsedInstance.rotationQuaternion) {
  18807. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18808. }
  18809. else if (parsedInstance.rotation) {
  18810. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18811. }
  18812. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18813. instance.checkCollisions = mesh.checkCollisions;
  18814. if (parsedMesh.animations) {
  18815. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18816. parsedAnimation = parsedMesh.animations[animationIndex];
  18817. instance.animations.push(parseAnimation(parsedAnimation));
  18818. }
  18819. }
  18820. }
  18821. }
  18822. return mesh;
  18823. };
  18824. var parseActions = function (parsedActions, object, scene) {
  18825. var actionManager = new BABYLON.ActionManager(scene);
  18826. if (object === null)
  18827. scene.actionManager = actionManager;
  18828. else
  18829. object.actionManager = actionManager;
  18830. // instanciate a new object
  18831. var instanciate = function (name, params) {
  18832. var newInstance = Object.create(BABYLON[name].prototype);
  18833. newInstance.constructor.apply(newInstance, params);
  18834. return newInstance;
  18835. };
  18836. var parseParameter = function (name, value, target, propertyPath) {
  18837. if (propertyPath === null) {
  18838. // String, boolean or float
  18839. var floatValue = parseFloat(value);
  18840. if (value === "true" || value === "false")
  18841. return value === "true";
  18842. else
  18843. return isNaN(floatValue) ? value : floatValue;
  18844. }
  18845. var effectiveTarget = propertyPath.split(".");
  18846. var values = value.split(",");
  18847. for (var i = 0; i < effectiveTarget.length; i++) {
  18848. target = target[effectiveTarget[i]];
  18849. }
  18850. // Return appropriate value with its type
  18851. if (target instanceof Boolean)
  18852. return values[0] === "true";
  18853. if (target instanceof String)
  18854. return values[0];
  18855. // Parameters with multiple values such as Vector3 etc.
  18856. var split = new Array();
  18857. for (var i = 0; i < values.length; i++)
  18858. split.push(parseFloat(values[i]));
  18859. if (target instanceof BABYLON.Vector3)
  18860. return BABYLON.Vector3.FromArray(split);
  18861. if (target instanceof BABYLON.Vector4)
  18862. return BABYLON.Vector4.FromArray(split);
  18863. if (target instanceof BABYLON.Color3)
  18864. return BABYLON.Color3.FromArray(split);
  18865. if (target instanceof BABYLON.Color4)
  18866. return BABYLON.Color4.FromArray(split);
  18867. return parseFloat(values[0]);
  18868. };
  18869. // traverse graph per trigger
  18870. var traverse = function (parsedAction, trigger, condition, action) {
  18871. var parameters = new Array();
  18872. var target = null;
  18873. var propertyPath = null;
  18874. // Parameters
  18875. if (parsedAction.type === 2)
  18876. parameters.push(actionManager);
  18877. else
  18878. parameters.push(trigger);
  18879. for (var i = 0; i < parsedAction.properties.length; i++) {
  18880. var value = parsedAction.properties[i].value;
  18881. var name = parsedAction.properties[i].name;
  18882. if (name === "target")
  18883. value = target = scene.getNodeByName(value);
  18884. else if (name === "parent")
  18885. value = scene.getNodeByName(value);
  18886. else if (name === "sound")
  18887. value = scene.getSoundByName(value);
  18888. else if (name !== "propertyPath") {
  18889. if (parsedAction.type === 2 && name === "operator")
  18890. value = BABYLON.ValueCondition[value];
  18891. else
  18892. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  18893. }
  18894. else {
  18895. propertyPath = value;
  18896. }
  18897. parameters.push(value);
  18898. }
  18899. parameters.push(condition);
  18900. // If interpolate value action
  18901. if (parsedAction.name === "InterpolateValueAction") {
  18902. var param = parameters[parameters.length - 2];
  18903. parameters[parameters.length - 1] = param;
  18904. parameters[parameters.length - 2] = condition;
  18905. }
  18906. // Action or condition(s)
  18907. var newAction = instanciate(parsedAction.name, parameters);
  18908. if (newAction instanceof BABYLON.Condition) {
  18909. condition = newAction;
  18910. newAction = action;
  18911. }
  18912. else {
  18913. condition = null;
  18914. if (action)
  18915. action.then(newAction);
  18916. else
  18917. actionManager.registerAction(newAction);
  18918. }
  18919. for (var i = 0; i < parsedAction.children.length; i++)
  18920. traverse(parsedAction.children[i], trigger, condition, newAction);
  18921. };
  18922. for (var i = 0; i < parsedActions.children.length; i++) {
  18923. var triggerParams;
  18924. var trigger = parsedActions.children[i];
  18925. if (trigger.properties.length > 0) {
  18926. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  18927. }
  18928. else
  18929. triggerParams = BABYLON.ActionManager[trigger.name];
  18930. for (var j = 0; j < trigger.children.length; j++)
  18931. traverse(trigger.children[j], triggerParams, null, null);
  18932. }
  18933. };
  18934. var parseSound = function (parsedSound, scene, rootUrl) {
  18935. var soundName = parsedSound.name;
  18936. var soundUrl = rootUrl + soundName;
  18937. var options = {
  18938. autoplay: parsedSound.autoplay,
  18939. loop: parsedSound.loop,
  18940. volume: parsedSound.volume,
  18941. spatialSound: parsedSound.spatialSound,
  18942. maxDistance: parsedSound.maxDistance,
  18943. rolloffFactor: parsedSound.rolloffFactor,
  18944. refDistance: parsedSound.refDistance,
  18945. distanceModel: parsedSound.distanceModel,
  18946. panningModel: parsedSound.panningModel,
  18947. playbackRate: parsedSound.playbackRate
  18948. };
  18949. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  18950. scene._removePendingData(newSound);
  18951. }, options);
  18952. scene._addPendingData(newSound);
  18953. if (parsedSound.position) {
  18954. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  18955. newSound.setPosition(soundPosition);
  18956. }
  18957. if (parsedSound.isDirectional) {
  18958. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  18959. if (parsedSound.localDirectionToMesh) {
  18960. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  18961. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  18962. }
  18963. }
  18964. if (parsedSound.connectedMeshId) {
  18965. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  18966. if (connectedMesh) {
  18967. newSound.attachToMesh(connectedMesh);
  18968. }
  18969. }
  18970. };
  18971. var isDescendantOf = function (mesh, names, hierarchyIds) {
  18972. names = (names instanceof Array) ? names : [names];
  18973. for (var i in names) {
  18974. if (mesh.name === names[i]) {
  18975. hierarchyIds.push(mesh.id);
  18976. return true;
  18977. }
  18978. }
  18979. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  18980. hierarchyIds.push(mesh.id);
  18981. return true;
  18982. }
  18983. return false;
  18984. };
  18985. var importVertexData = function (parsedVertexData, geometry) {
  18986. var vertexData = new BABYLON.VertexData();
  18987. // positions
  18988. var positions = parsedVertexData.positions;
  18989. if (positions) {
  18990. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  18991. }
  18992. // normals
  18993. var normals = parsedVertexData.normals;
  18994. if (normals) {
  18995. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  18996. }
  18997. // uvs
  18998. var uvs = parsedVertexData.uvs;
  18999. if (uvs) {
  19000. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19001. }
  19002. // uv2s
  19003. var uv2s = parsedVertexData.uv2s;
  19004. if (uv2s) {
  19005. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19006. }
  19007. // colors
  19008. var colors = parsedVertexData.colors;
  19009. if (colors) {
  19010. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  19011. }
  19012. // matricesIndices
  19013. var matricesIndices = parsedVertexData.matricesIndices;
  19014. if (matricesIndices) {
  19015. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19016. }
  19017. // matricesWeights
  19018. var matricesWeights = parsedVertexData.matricesWeights;
  19019. if (matricesWeights) {
  19020. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19021. }
  19022. // indices
  19023. var indices = parsedVertexData.indices;
  19024. if (indices) {
  19025. vertexData.indices = indices;
  19026. }
  19027. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19028. };
  19029. var importGeometry = function (parsedGeometry, mesh) {
  19030. var scene = mesh.getScene();
  19031. // Geometry
  19032. var geometryId = parsedGeometry.geometryId;
  19033. if (geometryId) {
  19034. var geometry = scene.getGeometryByID(geometryId);
  19035. if (geometry) {
  19036. geometry.applyToMesh(mesh);
  19037. }
  19038. }
  19039. else if (parsedGeometry instanceof ArrayBuffer) {
  19040. var binaryInfo = mesh._binaryInfo;
  19041. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19042. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19043. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19044. }
  19045. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19046. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19047. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19048. }
  19049. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19050. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19051. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19052. }
  19053. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19054. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19055. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19056. }
  19057. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19058. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19059. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  19060. }
  19061. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19062. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19063. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19064. }
  19065. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19066. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19067. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19068. }
  19069. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19070. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19071. mesh.setIndices(indicesData);
  19072. }
  19073. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19074. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19075. mesh.subMeshes = [];
  19076. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19077. var materialIndex = subMeshesData[(i * 5) + 0];
  19078. var verticesStart = subMeshesData[(i * 5) + 1];
  19079. var verticesCount = subMeshesData[(i * 5) + 2];
  19080. var indexStart = subMeshesData[(i * 5) + 3];
  19081. var indexCount = subMeshesData[(i * 5) + 4];
  19082. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19083. }
  19084. }
  19085. }
  19086. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19087. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19088. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19089. if (parsedGeometry.uvs) {
  19090. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19091. }
  19092. if (parsedGeometry.uvs2) {
  19093. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19094. }
  19095. if (parsedGeometry.colors) {
  19096. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19097. }
  19098. if (parsedGeometry.matricesIndices) {
  19099. if (!parsedGeometry.matricesIndices._isExpanded) {
  19100. var floatIndices = [];
  19101. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19102. var matricesIndex = parsedGeometry.matricesIndices[i];
  19103. floatIndices.push(matricesIndex & 0x000000FF);
  19104. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19105. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19106. floatIndices.push(matricesIndex >> 24);
  19107. }
  19108. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19109. }
  19110. else {
  19111. delete parsedGeometry.matricesIndices._isExpanded;
  19112. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19113. }
  19114. }
  19115. if (parsedGeometry.matricesWeights) {
  19116. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19117. }
  19118. mesh.setIndices(parsedGeometry.indices);
  19119. // SubMeshes
  19120. if (parsedGeometry.subMeshes) {
  19121. mesh.subMeshes = [];
  19122. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19123. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19124. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19125. }
  19126. }
  19127. }
  19128. // Flat shading
  19129. if (mesh._shouldGenerateFlatShading) {
  19130. mesh.convertToFlatShadedMesh();
  19131. delete mesh._shouldGenerateFlatShading;
  19132. }
  19133. // Update
  19134. mesh.computeWorldMatrix(true);
  19135. // Octree
  19136. if (scene._selectionOctree) {
  19137. scene._selectionOctree.addMesh(mesh);
  19138. }
  19139. };
  19140. BABYLON.SceneLoader.RegisterPlugin({
  19141. extensions: ".babylon",
  19142. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19143. var parsedData = JSON.parse(data);
  19144. var loadedSkeletonsIds = [];
  19145. var loadedMaterialsIds = [];
  19146. var hierarchyIds = [];
  19147. for (var index = 0; index < parsedData.meshes.length; index++) {
  19148. var parsedMesh = parsedData.meshes[index];
  19149. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19150. if (meshesNames instanceof Array) {
  19151. // Remove found mesh name from list.
  19152. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19153. }
  19154. // Material ?
  19155. if (parsedMesh.materialId) {
  19156. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19157. if (!materialFound) {
  19158. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19159. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19160. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19161. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19162. var subMatId = parsedMultiMaterial.materials[matIndex];
  19163. loadedMaterialsIds.push(subMatId);
  19164. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19165. }
  19166. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19167. parseMultiMaterial(parsedMultiMaterial, scene);
  19168. materialFound = true;
  19169. break;
  19170. }
  19171. }
  19172. }
  19173. if (!materialFound) {
  19174. loadedMaterialsIds.push(parsedMesh.materialId);
  19175. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19176. }
  19177. }
  19178. // Skeleton ?
  19179. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19180. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19181. if (!skeletonAlreadyLoaded) {
  19182. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19183. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19184. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19185. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19186. loadedSkeletonsIds.push(parsedSkeleton.id);
  19187. }
  19188. }
  19189. }
  19190. }
  19191. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19192. meshes.push(mesh);
  19193. }
  19194. }
  19195. for (index = 0; index < scene.meshes.length; index++) {
  19196. var currentMesh = scene.meshes[index];
  19197. if (currentMesh._waitingParentId) {
  19198. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19199. currentMesh._waitingParentId = undefined;
  19200. }
  19201. }
  19202. // Particles
  19203. if (parsedData.particleSystems) {
  19204. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19205. var parsedParticleSystem = parsedData.particleSystems[index];
  19206. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19207. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19208. }
  19209. }
  19210. }
  19211. return true;
  19212. },
  19213. load: function (scene, data, rootUrl) {
  19214. var parsedData = JSON.parse(data);
  19215. // Scene
  19216. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19217. scene.autoClear = parsedData.autoClear;
  19218. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19219. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19220. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19221. // Fog
  19222. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19223. scene.fogMode = parsedData.fogMode;
  19224. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19225. scene.fogStart = parsedData.fogStart;
  19226. scene.fogEnd = parsedData.fogEnd;
  19227. scene.fogDensity = parsedData.fogDensity;
  19228. }
  19229. for (var index = 0; index < parsedData.lights.length; index++) {
  19230. var parsedLight = parsedData.lights[index];
  19231. parseLight(parsedLight, scene);
  19232. }
  19233. // Materials
  19234. if (parsedData.materials) {
  19235. for (index = 0; index < parsedData.materials.length; index++) {
  19236. var parsedMaterial = parsedData.materials[index];
  19237. parseMaterial(parsedMaterial, scene, rootUrl);
  19238. }
  19239. }
  19240. if (parsedData.multiMaterials) {
  19241. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19242. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19243. parseMultiMaterial(parsedMultiMaterial, scene);
  19244. }
  19245. }
  19246. // Skeletons
  19247. if (parsedData.skeletons) {
  19248. for (index = 0; index < parsedData.skeletons.length; index++) {
  19249. var parsedSkeleton = parsedData.skeletons[index];
  19250. parseSkeleton(parsedSkeleton, scene);
  19251. }
  19252. }
  19253. // Geometries
  19254. var geometries = parsedData.geometries;
  19255. if (geometries) {
  19256. // Boxes
  19257. var boxes = geometries.boxes;
  19258. if (boxes) {
  19259. for (index = 0; index < boxes.length; index++) {
  19260. var parsedBox = boxes[index];
  19261. parseBox(parsedBox, scene);
  19262. }
  19263. }
  19264. // Spheres
  19265. var spheres = geometries.spheres;
  19266. if (spheres) {
  19267. for (index = 0; index < spheres.length; index++) {
  19268. var parsedSphere = spheres[index];
  19269. parseSphere(parsedSphere, scene);
  19270. }
  19271. }
  19272. // Cylinders
  19273. var cylinders = geometries.cylinders;
  19274. if (cylinders) {
  19275. for (index = 0; index < cylinders.length; index++) {
  19276. var parsedCylinder = cylinders[index];
  19277. parseCylinder(parsedCylinder, scene);
  19278. }
  19279. }
  19280. // Toruses
  19281. var toruses = geometries.toruses;
  19282. if (toruses) {
  19283. for (index = 0; index < toruses.length; index++) {
  19284. var parsedTorus = toruses[index];
  19285. parseTorus(parsedTorus, scene);
  19286. }
  19287. }
  19288. // Grounds
  19289. var grounds = geometries.grounds;
  19290. if (grounds) {
  19291. for (index = 0; index < grounds.length; index++) {
  19292. var parsedGround = grounds[index];
  19293. parseGround(parsedGround, scene);
  19294. }
  19295. }
  19296. // Planes
  19297. var planes = geometries.planes;
  19298. if (planes) {
  19299. for (index = 0; index < planes.length; index++) {
  19300. var parsedPlane = planes[index];
  19301. parsePlane(parsedPlane, scene);
  19302. }
  19303. }
  19304. // TorusKnots
  19305. var torusKnots = geometries.torusKnots;
  19306. if (torusKnots) {
  19307. for (index = 0; index < torusKnots.length; index++) {
  19308. var parsedTorusKnot = torusKnots[index];
  19309. parseTorusKnot(parsedTorusKnot, scene);
  19310. }
  19311. }
  19312. // VertexData
  19313. var vertexData = geometries.vertexData;
  19314. if (vertexData) {
  19315. for (index = 0; index < vertexData.length; index++) {
  19316. var parsedVertexData = vertexData[index];
  19317. parseVertexData(parsedVertexData, scene, rootUrl);
  19318. }
  19319. }
  19320. }
  19321. for (index = 0; index < parsedData.meshes.length; index++) {
  19322. var parsedMesh = parsedData.meshes[index];
  19323. parseMesh(parsedMesh, scene, rootUrl);
  19324. }
  19325. for (index = 0; index < parsedData.cameras.length; index++) {
  19326. var parsedCamera = parsedData.cameras[index];
  19327. parseCamera(parsedCamera, scene);
  19328. }
  19329. if (parsedData.activeCameraID) {
  19330. scene.setActiveCameraByID(parsedData.activeCameraID);
  19331. }
  19332. for (index = 0; index < scene.cameras.length; index++) {
  19333. var camera = scene.cameras[index];
  19334. if (camera._waitingParentId) {
  19335. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19336. camera._waitingParentId = undefined;
  19337. }
  19338. }
  19339. for (index = 0; index < scene.lights.length; index++) {
  19340. var light = scene.lights[index];
  19341. if (light._waitingParentId) {
  19342. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19343. light._waitingParentId = undefined;
  19344. }
  19345. }
  19346. // Sounds
  19347. if (parsedData.sounds) {
  19348. for (index = 0; index < parsedData.sounds.length; index++) {
  19349. var parsedSound = parsedData.sounds[index];
  19350. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  19351. parseSound(parsedSound, scene, rootUrl);
  19352. }
  19353. else {
  19354. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  19355. }
  19356. }
  19357. }
  19358. for (index = 0; index < scene.meshes.length; index++) {
  19359. var mesh = scene.meshes[index];
  19360. if (mesh._waitingParentId) {
  19361. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  19362. mesh._waitingParentId = undefined;
  19363. }
  19364. if (mesh._waitingActions) {
  19365. parseActions(mesh._waitingActions, mesh, scene);
  19366. mesh._waitingActions = undefined;
  19367. }
  19368. }
  19369. // Particles Systems
  19370. if (parsedData.particleSystems) {
  19371. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19372. var parsedParticleSystem = parsedData.particleSystems[index];
  19373. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  19374. }
  19375. }
  19376. // Lens flares
  19377. if (parsedData.lensFlareSystems) {
  19378. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  19379. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  19380. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  19381. }
  19382. }
  19383. // Shadows
  19384. if (parsedData.shadowGenerators) {
  19385. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  19386. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  19387. parseShadowGenerator(parsedShadowGenerator, scene);
  19388. }
  19389. }
  19390. // Actions (scene)
  19391. if (parsedData.actions) {
  19392. parseActions(parsedData.actions, null, scene);
  19393. }
  19394. // Finish
  19395. return true;
  19396. }
  19397. });
  19398. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  19399. })(BABYLON || (BABYLON = {}));
  19400. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  19401. (function (BABYLON) {
  19402. // Unique ID when we import meshes from Babylon to CSG
  19403. var currentCSGMeshId = 0;
  19404. // # class Vertex
  19405. // Represents a vertex of a polygon. Use your own vertex class instead of this
  19406. // one to provide additional features like texture coordinates and vertex
  19407. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  19408. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  19409. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  19410. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  19411. // is not used anywhere else.
  19412. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  19413. var Vertex = (function () {
  19414. function Vertex(pos, normal, uv) {
  19415. this.pos = pos;
  19416. this.normal = normal;
  19417. this.uv = uv;
  19418. }
  19419. Vertex.prototype.clone = function () {
  19420. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  19421. };
  19422. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  19423. // orientation of a polygon is flipped.
  19424. Vertex.prototype.flip = function () {
  19425. this.normal = this.normal.scale(-1);
  19426. };
  19427. // Create a new vertex between this vertex and `other` by linearly
  19428. // interpolating all properties using a parameter of `t`. Subclasses should
  19429. // override this to interpolate additional properties.
  19430. Vertex.prototype.interpolate = function (other, t) {
  19431. 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));
  19432. };
  19433. return Vertex;
  19434. })();
  19435. // # class Plane
  19436. // Represents a plane in 3D space.
  19437. var Plane = (function () {
  19438. function Plane(normal, w) {
  19439. this.normal = normal;
  19440. this.w = w;
  19441. }
  19442. Plane.FromPoints = function (a, b, c) {
  19443. var v0 = c.subtract(a);
  19444. var v1 = b.subtract(a);
  19445. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  19446. return null;
  19447. }
  19448. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  19449. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  19450. };
  19451. Plane.prototype.clone = function () {
  19452. return new Plane(this.normal.clone(), this.w);
  19453. };
  19454. Plane.prototype.flip = function () {
  19455. this.normal.scaleInPlace(-1);
  19456. this.w = -this.w;
  19457. };
  19458. // Split `polygon` by this plane if needed, then put the polygon or polygon
  19459. // fragments in the appropriate lists. Coplanar polygons go into either
  19460. // `coplanarFront` or `coplanarBack` depending on their orientation with
  19461. // respect to this plane. Polygons in front or in back of this plane go into
  19462. // either `front` or `back`.
  19463. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  19464. var COPLANAR = 0;
  19465. var FRONT = 1;
  19466. var BACK = 2;
  19467. var SPANNING = 3;
  19468. // Classify each point as well as the entire polygon into one of the above
  19469. // four classes.
  19470. var polygonType = 0;
  19471. var types = [];
  19472. for (var i = 0; i < polygon.vertices.length; i++) {
  19473. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  19474. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  19475. polygonType |= type;
  19476. types.push(type);
  19477. }
  19478. switch (polygonType) {
  19479. case COPLANAR:
  19480. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  19481. break;
  19482. case FRONT:
  19483. front.push(polygon);
  19484. break;
  19485. case BACK:
  19486. back.push(polygon);
  19487. break;
  19488. case SPANNING:
  19489. var f = [], b = [];
  19490. for (i = 0; i < polygon.vertices.length; i++) {
  19491. var j = (i + 1) % polygon.vertices.length;
  19492. var ti = types[i], tj = types[j];
  19493. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  19494. if (ti != BACK)
  19495. f.push(vi);
  19496. if (ti != FRONT)
  19497. b.push(ti != BACK ? vi.clone() : vi);
  19498. if ((ti | tj) == SPANNING) {
  19499. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  19500. var v = vi.interpolate(vj, t);
  19501. f.push(v);
  19502. b.push(v.clone());
  19503. }
  19504. }
  19505. if (f.length >= 3) {
  19506. var poly = new Polygon(f, polygon.shared);
  19507. if (poly.plane)
  19508. front.push(poly);
  19509. }
  19510. if (b.length >= 3) {
  19511. poly = new Polygon(b, polygon.shared);
  19512. if (poly.plane)
  19513. back.push(poly);
  19514. }
  19515. break;
  19516. }
  19517. };
  19518. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  19519. // point is on the plane.
  19520. Plane.EPSILON = 1e-5;
  19521. return Plane;
  19522. })();
  19523. // # class Polygon
  19524. // Represents a convex polygon. The vertices used to initialize a polygon must
  19525. // be coplanar and form a convex loop.
  19526. //
  19527. // Each convex polygon has a `shared` property, which is shared between all
  19528. // polygons that are clones of each other or were split from the same polygon.
  19529. // This can be used to define per-polygon properties (such as surface color).
  19530. var Polygon = (function () {
  19531. function Polygon(vertices, shared) {
  19532. this.vertices = vertices;
  19533. this.shared = shared;
  19534. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  19535. }
  19536. Polygon.prototype.clone = function () {
  19537. var vertices = this.vertices.map(function (v) { return v.clone(); });
  19538. return new Polygon(vertices, this.shared);
  19539. };
  19540. Polygon.prototype.flip = function () {
  19541. this.vertices.reverse().map(function (v) {
  19542. v.flip();
  19543. });
  19544. this.plane.flip();
  19545. };
  19546. return Polygon;
  19547. })();
  19548. // # class Node
  19549. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  19550. // by picking a polygon to split along. That polygon (and all other coplanar
  19551. // polygons) are added directly to that node and the other polygons are added to
  19552. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  19553. // no distinction between internal and leaf nodes.
  19554. var Node = (function () {
  19555. function Node(polygons) {
  19556. this.plane = null;
  19557. this.front = null;
  19558. this.back = null;
  19559. this.polygons = [];
  19560. if (polygons) {
  19561. this.build(polygons);
  19562. }
  19563. }
  19564. Node.prototype.clone = function () {
  19565. var node = new Node();
  19566. node.plane = this.plane && this.plane.clone();
  19567. node.front = this.front && this.front.clone();
  19568. node.back = this.back && this.back.clone();
  19569. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  19570. return node;
  19571. };
  19572. // Convert solid space to empty space and empty space to solid space.
  19573. Node.prototype.invert = function () {
  19574. for (var i = 0; i < this.polygons.length; i++) {
  19575. this.polygons[i].flip();
  19576. }
  19577. if (this.plane) {
  19578. this.plane.flip();
  19579. }
  19580. if (this.front) {
  19581. this.front.invert();
  19582. }
  19583. if (this.back) {
  19584. this.back.invert();
  19585. }
  19586. var temp = this.front;
  19587. this.front = this.back;
  19588. this.back = temp;
  19589. };
  19590. // Recursively remove all polygons in `polygons` that are inside this BSP
  19591. // tree.
  19592. Node.prototype.clipPolygons = function (polygons) {
  19593. if (!this.plane)
  19594. return polygons.slice();
  19595. var front = [], back = [];
  19596. for (var i = 0; i < polygons.length; i++) {
  19597. this.plane.splitPolygon(polygons[i], front, back, front, back);
  19598. }
  19599. if (this.front) {
  19600. front = this.front.clipPolygons(front);
  19601. }
  19602. if (this.back) {
  19603. back = this.back.clipPolygons(back);
  19604. }
  19605. else {
  19606. back = [];
  19607. }
  19608. return front.concat(back);
  19609. };
  19610. // Remove all polygons in this BSP tree that are inside the other BSP tree
  19611. // `bsp`.
  19612. Node.prototype.clipTo = function (bsp) {
  19613. this.polygons = bsp.clipPolygons(this.polygons);
  19614. if (this.front)
  19615. this.front.clipTo(bsp);
  19616. if (this.back)
  19617. this.back.clipTo(bsp);
  19618. };
  19619. // Return a list of all polygons in this BSP tree.
  19620. Node.prototype.allPolygons = function () {
  19621. var polygons = this.polygons.slice();
  19622. if (this.front)
  19623. polygons = polygons.concat(this.front.allPolygons());
  19624. if (this.back)
  19625. polygons = polygons.concat(this.back.allPolygons());
  19626. return polygons;
  19627. };
  19628. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  19629. // new polygons are filtered down to the bottom of the tree and become new
  19630. // nodes there. Each set of polygons is partitioned using the first polygon
  19631. // (no heuristic is used to pick a good split).
  19632. Node.prototype.build = function (polygons) {
  19633. if (!polygons.length)
  19634. return;
  19635. if (!this.plane)
  19636. this.plane = polygons[0].plane.clone();
  19637. var front = [], back = [];
  19638. for (var i = 0; i < polygons.length; i++) {
  19639. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  19640. }
  19641. if (front.length) {
  19642. if (!this.front)
  19643. this.front = new Node();
  19644. this.front.build(front);
  19645. }
  19646. if (back.length) {
  19647. if (!this.back)
  19648. this.back = new Node();
  19649. this.back.build(back);
  19650. }
  19651. };
  19652. return Node;
  19653. })();
  19654. var CSG = (function () {
  19655. function CSG() {
  19656. this.polygons = new Array();
  19657. }
  19658. // Convert BABYLON.Mesh to BABYLON.CSG
  19659. CSG.FromMesh = function (mesh) {
  19660. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  19661. if (mesh instanceof BABYLON.Mesh) {
  19662. mesh.computeWorldMatrix(true);
  19663. var matrix = mesh.getWorldMatrix();
  19664. var meshPosition = mesh.position.clone();
  19665. var meshRotation = mesh.rotation.clone();
  19666. var meshScaling = mesh.scaling.clone();
  19667. }
  19668. else {
  19669. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  19670. }
  19671. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19672. var subMeshes = mesh.subMeshes;
  19673. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  19674. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  19675. vertices = [];
  19676. for (var j = 0; j < 3; j++) {
  19677. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  19678. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  19679. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  19680. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  19681. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  19682. vertex = new Vertex(position, normal, uv);
  19683. vertices.push(vertex);
  19684. }
  19685. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  19686. // To handle the case of degenerated triangle
  19687. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  19688. if (polygon.plane)
  19689. polygons.push(polygon);
  19690. }
  19691. }
  19692. var csg = CSG.FromPolygons(polygons);
  19693. csg.matrix = matrix;
  19694. csg.position = meshPosition;
  19695. csg.rotation = meshRotation;
  19696. csg.scaling = meshScaling;
  19697. currentCSGMeshId++;
  19698. return csg;
  19699. };
  19700. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  19701. CSG.FromPolygons = function (polygons) {
  19702. var csg = new BABYLON.CSG();
  19703. csg.polygons = polygons;
  19704. return csg;
  19705. };
  19706. CSG.prototype.clone = function () {
  19707. var csg = new BABYLON.CSG();
  19708. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  19709. csg.copyTransformAttributes(this);
  19710. return csg;
  19711. };
  19712. CSG.prototype.toPolygons = function () {
  19713. return this.polygons;
  19714. };
  19715. CSG.prototype.union = function (csg) {
  19716. var a = new Node(this.clone().polygons);
  19717. var b = new Node(csg.clone().polygons);
  19718. a.clipTo(b);
  19719. b.clipTo(a);
  19720. b.invert();
  19721. b.clipTo(a);
  19722. b.invert();
  19723. a.build(b.allPolygons());
  19724. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19725. };
  19726. CSG.prototype.unionInPlace = function (csg) {
  19727. var a = new Node(this.polygons);
  19728. var b = new Node(csg.polygons);
  19729. a.clipTo(b);
  19730. b.clipTo(a);
  19731. b.invert();
  19732. b.clipTo(a);
  19733. b.invert();
  19734. a.build(b.allPolygons());
  19735. this.polygons = a.allPolygons();
  19736. };
  19737. CSG.prototype.subtract = function (csg) {
  19738. var a = new Node(this.clone().polygons);
  19739. var b = new Node(csg.clone().polygons);
  19740. a.invert();
  19741. a.clipTo(b);
  19742. b.clipTo(a);
  19743. b.invert();
  19744. b.clipTo(a);
  19745. b.invert();
  19746. a.build(b.allPolygons());
  19747. a.invert();
  19748. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19749. };
  19750. CSG.prototype.subtractInPlace = function (csg) {
  19751. var a = new Node(this.polygons);
  19752. var b = new Node(csg.polygons);
  19753. a.invert();
  19754. a.clipTo(b);
  19755. b.clipTo(a);
  19756. b.invert();
  19757. b.clipTo(a);
  19758. b.invert();
  19759. a.build(b.allPolygons());
  19760. a.invert();
  19761. this.polygons = a.allPolygons();
  19762. };
  19763. CSG.prototype.intersect = function (csg) {
  19764. var a = new Node(this.clone().polygons);
  19765. var b = new Node(csg.clone().polygons);
  19766. a.invert();
  19767. b.clipTo(a);
  19768. b.invert();
  19769. a.clipTo(b);
  19770. b.clipTo(a);
  19771. a.build(b.allPolygons());
  19772. a.invert();
  19773. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19774. };
  19775. CSG.prototype.intersectInPlace = function (csg) {
  19776. var a = new Node(this.polygons);
  19777. var b = new Node(csg.polygons);
  19778. a.invert();
  19779. b.clipTo(a);
  19780. b.invert();
  19781. a.clipTo(b);
  19782. b.clipTo(a);
  19783. a.build(b.allPolygons());
  19784. a.invert();
  19785. this.polygons = a.allPolygons();
  19786. };
  19787. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  19788. // not modified.
  19789. CSG.prototype.inverse = function () {
  19790. var csg = this.clone();
  19791. csg.inverseInPlace();
  19792. return csg;
  19793. };
  19794. CSG.prototype.inverseInPlace = function () {
  19795. this.polygons.map(function (p) {
  19796. p.flip();
  19797. });
  19798. };
  19799. // This is used to keep meshes transformations so they can be restored
  19800. // when we build back a Babylon Mesh
  19801. // NB : All CSG operations are performed in world coordinates
  19802. CSG.prototype.copyTransformAttributes = function (csg) {
  19803. this.matrix = csg.matrix;
  19804. this.position = csg.position;
  19805. this.rotation = csg.rotation;
  19806. this.scaling = csg.scaling;
  19807. return this;
  19808. };
  19809. // Build Raw mesh from CSG
  19810. // Coordinates here are in world space
  19811. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  19812. var matrix = this.matrix.clone();
  19813. matrix.invert();
  19814. 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;
  19815. if (keepSubMeshes) {
  19816. // Sort Polygons, since subMeshes are indices range
  19817. polygons.sort(function (a, b) {
  19818. if (a.shared.meshId === b.shared.meshId) {
  19819. return a.shared.subMeshId - b.shared.subMeshId;
  19820. }
  19821. else {
  19822. return a.shared.meshId - b.shared.meshId;
  19823. }
  19824. });
  19825. }
  19826. for (var i = 0, il = polygons.length; i < il; i++) {
  19827. polygon = polygons[i];
  19828. // Building SubMeshes
  19829. if (!subMesh_dict[polygon.shared.meshId]) {
  19830. subMesh_dict[polygon.shared.meshId] = {};
  19831. }
  19832. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  19833. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  19834. indexStart: +Infinity,
  19835. indexEnd: -Infinity,
  19836. materialIndex: polygon.shared.materialIndex
  19837. };
  19838. }
  19839. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  19840. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  19841. polygonIndices[0] = 0;
  19842. polygonIndices[1] = j - 1;
  19843. polygonIndices[2] = j;
  19844. for (var k = 0; k < 3; k++) {
  19845. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  19846. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  19847. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  19848. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  19849. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  19850. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  19851. // Check if 2 points can be merged
  19852. 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)) {
  19853. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  19854. uvs.push(uv.x, uv.y);
  19855. normals.push(normal.x, normal.y, normal.z);
  19856. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  19857. }
  19858. indices.push(vertex_idx);
  19859. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  19860. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  19861. currentIndex++;
  19862. }
  19863. }
  19864. }
  19865. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  19866. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19867. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  19868. mesh.setIndices(indices);
  19869. if (keepSubMeshes) {
  19870. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  19871. var materialIndexOffset = 0, materialMaxIndex;
  19872. mesh.subMeshes.length = 0;
  19873. for (var m in subMesh_dict) {
  19874. materialMaxIndex = -1;
  19875. for (var sm in subMesh_dict[m]) {
  19876. subMesh_obj = subMesh_dict[m][sm];
  19877. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  19878. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  19879. }
  19880. materialIndexOffset += ++materialMaxIndex;
  19881. }
  19882. }
  19883. return mesh;
  19884. };
  19885. // Build Mesh from CSG taking material and transforms into account
  19886. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  19887. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  19888. mesh.material = material;
  19889. mesh.position.copyFrom(this.position);
  19890. mesh.rotation.copyFrom(this.rotation);
  19891. mesh.scaling.copyFrom(this.scaling);
  19892. mesh.computeWorldMatrix(true);
  19893. return mesh;
  19894. };
  19895. return CSG;
  19896. })();
  19897. BABYLON.CSG = CSG;
  19898. })(BABYLON || (BABYLON = {}));
  19899. //# sourceMappingURL=babylon.csg.js.map
  19900. var BABYLON;
  19901. (function (BABYLON) {
  19902. var OculusDistortionCorrectionPostProcess = (function (_super) {
  19903. __extends(OculusDistortionCorrectionPostProcess, _super);
  19904. //ANY
  19905. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  19906. var _this = this;
  19907. _super.call(this, name, "oculusDistortionCorrection", [
  19908. 'LensCenter',
  19909. 'Scale',
  19910. 'ScaleIn',
  19911. 'HmdWarpParam'
  19912. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  19913. this._isRightEye = isRightEye;
  19914. this._distortionFactors = cameraSettings.DistortionK;
  19915. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  19916. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  19917. this.onSizeChanged = function () {
  19918. _this.aspectRatio = _this.width * .5 / _this.height;
  19919. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  19920. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  19921. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  19922. };
  19923. this.onApply = function (effect) {
  19924. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  19925. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  19926. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  19927. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  19928. };
  19929. }
  19930. return OculusDistortionCorrectionPostProcess;
  19931. })(BABYLON.PostProcess);
  19932. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  19933. })(BABYLON || (BABYLON = {}));
  19934. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  19935. // 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
  19936. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  19937. var BABYLON;
  19938. (function (BABYLON) {
  19939. (function (JoystickAxis) {
  19940. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  19941. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  19942. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  19943. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  19944. var JoystickAxis = BABYLON.JoystickAxis;
  19945. var VirtualJoystick = (function () {
  19946. function VirtualJoystick(leftJoystick) {
  19947. var _this = this;
  19948. if (leftJoystick) {
  19949. this._leftJoystick = true;
  19950. }
  19951. else {
  19952. this._leftJoystick = false;
  19953. }
  19954. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  19955. VirtualJoystick._globalJoystickIndex++;
  19956. // By default left & right arrow keys are moving the X
  19957. // and up & down keys are moving the Y
  19958. this._axisTargetedByLeftAndRight = 0 /* X */;
  19959. this._axisTargetedByUpAndDown = 1 /* Y */;
  19960. this.reverseLeftRight = false;
  19961. this.reverseUpDown = false;
  19962. // collections of pointers
  19963. this._touches = new BABYLON.VirtualJoystick.Collection();
  19964. this.deltaPosition = BABYLON.Vector3.Zero();
  19965. this._joystickSensibility = 25;
  19966. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19967. this._rotationSpeed = 25;
  19968. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  19969. this._rotateOnAxisRelativeToMesh = false;
  19970. // injecting a canvas element on top of the canvas 3D game
  19971. if (!VirtualJoystick.vjCanvas) {
  19972. window.addEventListener("resize", function () {
  19973. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19974. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19975. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  19976. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  19977. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  19978. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  19979. }, false);
  19980. VirtualJoystick.vjCanvas = document.createElement("canvas");
  19981. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19982. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19983. VirtualJoystick.vjCanvas.width = window.innerWidth;
  19984. VirtualJoystick.vjCanvas.height = window.innerHeight;
  19985. VirtualJoystick.vjCanvas.style.width = "100%";
  19986. VirtualJoystick.vjCanvas.style.height = "100%";
  19987. VirtualJoystick.vjCanvas.style.position = "absolute";
  19988. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  19989. VirtualJoystick.vjCanvas.style.top = "0px";
  19990. VirtualJoystick.vjCanvas.style.left = "0px";
  19991. VirtualJoystick.vjCanvas.style.zIndex = "5";
  19992. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  19993. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  19994. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  19995. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19996. document.body.appendChild(VirtualJoystick.vjCanvas);
  19997. }
  19998. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  19999. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  20000. this.pressed = false;
  20001. // default joystick color
  20002. this._joystickColor = "cyan";
  20003. this._joystickPointerID = -1;
  20004. // current joystick position
  20005. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  20006. // origin joystick position
  20007. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  20008. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  20009. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  20010. _this._onPointerDown(evt);
  20011. }, false);
  20012. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  20013. _this._onPointerMove(evt);
  20014. }, false);
  20015. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  20016. _this._onPointerUp(evt);
  20017. }, false);
  20018. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  20019. _this._onPointerUp(evt);
  20020. }, false);
  20021. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  20022. evt.preventDefault(); // Disables system menu
  20023. }, false);
  20024. requestAnimationFrame(function () {
  20025. _this._drawVirtualJoystick();
  20026. });
  20027. }
  20028. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  20029. this._joystickSensibility = newJoystickSensibility;
  20030. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20031. };
  20032. VirtualJoystick.prototype._onPointerDown = function (e) {
  20033. var positionOnScreenCondition;
  20034. e.preventDefault();
  20035. if (this._leftJoystick === true) {
  20036. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  20037. }
  20038. else {
  20039. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  20040. }
  20041. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  20042. // First contact will be dedicated to the virtual joystick
  20043. this._joystickPointerID = e.pointerId;
  20044. this._joystickPointerStartPos.x = e.clientX;
  20045. this._joystickPointerStartPos.y = e.clientY;
  20046. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  20047. this._deltaJoystickVector.x = 0;
  20048. this._deltaJoystickVector.y = 0;
  20049. this.pressed = true;
  20050. this._touches.add(e.pointerId.toString(), e);
  20051. }
  20052. else {
  20053. // You can only trigger the action buttons with a joystick declared
  20054. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  20055. this._action();
  20056. this._touches.add(e.pointerId.toString(), e);
  20057. }
  20058. }
  20059. };
  20060. VirtualJoystick.prototype._onPointerMove = function (e) {
  20061. // If the current pointer is the one associated to the joystick (first touch contact)
  20062. if (this._joystickPointerID == e.pointerId) {
  20063. this._joystickPointerPos.x = e.clientX;
  20064. this._joystickPointerPos.y = e.clientY;
  20065. this._deltaJoystickVector = this._joystickPointerPos.clone();
  20066. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  20067. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  20068. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  20069. switch (this._axisTargetedByLeftAndRight) {
  20070. case 0 /* X */:
  20071. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  20072. break;
  20073. case 1 /* Y */:
  20074. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  20075. break;
  20076. case 2 /* Z */:
  20077. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  20078. break;
  20079. }
  20080. var directionUpDown = this.reverseUpDown ? 1 : -1;
  20081. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  20082. switch (this._axisTargetedByUpAndDown) {
  20083. case 0 /* X */:
  20084. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  20085. break;
  20086. case 1 /* Y */:
  20087. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  20088. break;
  20089. case 2 /* Z */:
  20090. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  20091. break;
  20092. }
  20093. }
  20094. else {
  20095. if (this._touches.item(e.pointerId.toString())) {
  20096. this._touches.item(e.pointerId.toString()).x = e.clientX;
  20097. this._touches.item(e.pointerId.toString()).y = e.clientY;
  20098. }
  20099. }
  20100. };
  20101. VirtualJoystick.prototype._onPointerUp = function (e) {
  20102. this._clearCanvas();
  20103. if (this._joystickPointerID == e.pointerId) {
  20104. this._joystickPointerID = -1;
  20105. this.pressed = false;
  20106. }
  20107. this._deltaJoystickVector.x = 0;
  20108. this._deltaJoystickVector.y = 0;
  20109. this._touches.remove(e.pointerId.toString());
  20110. };
  20111. /**
  20112. * Change the color of the virtual joystick
  20113. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  20114. */
  20115. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  20116. this._joystickColor = newColor;
  20117. };
  20118. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  20119. this._action = action;
  20120. };
  20121. // Define which axis you'd like to control for left & right
  20122. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  20123. switch (axis) {
  20124. case 0 /* X */:
  20125. case 1 /* Y */:
  20126. case 2 /* Z */:
  20127. this._axisTargetedByLeftAndRight = axis;
  20128. break;
  20129. default:
  20130. this._axisTargetedByLeftAndRight = 0 /* X */;
  20131. break;
  20132. }
  20133. };
  20134. // Define which axis you'd like to control for up & down
  20135. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  20136. switch (axis) {
  20137. case 0 /* X */:
  20138. case 1 /* Y */:
  20139. case 2 /* Z */:
  20140. this._axisTargetedByUpAndDown = axis;
  20141. break;
  20142. default:
  20143. this._axisTargetedByUpAndDown = 1 /* Y */;
  20144. break;
  20145. }
  20146. };
  20147. VirtualJoystick.prototype._clearCanvas = function () {
  20148. if (this._leftJoystick) {
  20149. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  20150. }
  20151. else {
  20152. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  20153. }
  20154. };
  20155. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  20156. var _this = this;
  20157. if (this.pressed) {
  20158. this._clearCanvas();
  20159. this._touches.forEach(function (touch) {
  20160. if (touch.pointerId === _this._joystickPointerID) {
  20161. VirtualJoystick.vjCanvasContext.beginPath();
  20162. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20163. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20164. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  20165. VirtualJoystick.vjCanvasContext.stroke();
  20166. VirtualJoystick.vjCanvasContext.beginPath();
  20167. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20168. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20169. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  20170. VirtualJoystick.vjCanvasContext.stroke();
  20171. VirtualJoystick.vjCanvasContext.beginPath();
  20172. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20173. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  20174. VirtualJoystick.vjCanvasContext.stroke();
  20175. }
  20176. else {
  20177. VirtualJoystick.vjCanvasContext.beginPath();
  20178. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  20179. VirtualJoystick.vjCanvasContext.beginPath();
  20180. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  20181. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20182. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  20183. VirtualJoystick.vjCanvasContext.stroke();
  20184. }
  20185. ;
  20186. });
  20187. }
  20188. requestAnimationFrame(function () {
  20189. _this._drawVirtualJoystick();
  20190. });
  20191. };
  20192. VirtualJoystick.prototype.releaseCanvas = function () {
  20193. if (VirtualJoystick.vjCanvas) {
  20194. document.body.removeChild(VirtualJoystick.vjCanvas);
  20195. VirtualJoystick.vjCanvas = null;
  20196. }
  20197. };
  20198. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  20199. VirtualJoystick._globalJoystickIndex = 0;
  20200. return VirtualJoystick;
  20201. })();
  20202. BABYLON.VirtualJoystick = VirtualJoystick;
  20203. })(BABYLON || (BABYLON = {}));
  20204. var BABYLON;
  20205. (function (BABYLON) {
  20206. var VirtualJoystick;
  20207. (function (VirtualJoystick) {
  20208. var Collection = (function () {
  20209. function Collection() {
  20210. this._count = 0;
  20211. this._collection = new Array();
  20212. }
  20213. Collection.prototype.Count = function () {
  20214. return this._count;
  20215. };
  20216. Collection.prototype.add = function (key, item) {
  20217. if (this._collection[key] != undefined) {
  20218. return undefined;
  20219. }
  20220. this._collection[key] = item;
  20221. return ++this._count;
  20222. };
  20223. Collection.prototype.remove = function (key) {
  20224. if (this._collection[key] == undefined) {
  20225. return undefined;
  20226. }
  20227. delete this._collection[key];
  20228. return --this._count;
  20229. };
  20230. Collection.prototype.item = function (key) {
  20231. return this._collection[key];
  20232. };
  20233. Collection.prototype.forEach = function (block) {
  20234. var key;
  20235. for (key in this._collection) {
  20236. if (this._collection.hasOwnProperty(key)) {
  20237. block(this._collection[key]);
  20238. }
  20239. }
  20240. };
  20241. return Collection;
  20242. })();
  20243. VirtualJoystick.Collection = Collection;
  20244. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  20245. })(BABYLON || (BABYLON = {}));
  20246. //# sourceMappingURL=babylon.virtualJoystick.js.map
  20247. var BABYLON;
  20248. (function (BABYLON) {
  20249. var OculusRiftDevKit2013_Metric = {
  20250. HResolution: 1280,
  20251. VResolution: 800,
  20252. HScreenSize: 0.149759993,
  20253. VScreenSize: 0.0935999975,
  20254. VScreenCenter: 0.0467999987,
  20255. EyeToScreenDistance: 0.0410000011,
  20256. LensSeparationDistance: 0.0635000020,
  20257. InterpupillaryDistance: 0.0640000030,
  20258. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20259. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20260. PostProcessScaleFactor: 1.714605507808412,
  20261. LensCenterOffset: 0.151976421
  20262. };
  20263. var _OculusInnerCamera = (function (_super) {
  20264. __extends(_OculusInnerCamera, _super);
  20265. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  20266. _super.call(this, name, position, scene);
  20267. this._workMatrix = new BABYLON.Matrix();
  20268. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20269. // Constants
  20270. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20271. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20272. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20273. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20274. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20275. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20276. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20277. // Postprocess
  20278. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20279. }
  20280. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  20281. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20282. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20283. return this._projectionMatrix;
  20284. };
  20285. _OculusInnerCamera.prototype._getViewMatrix = function () {
  20286. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20287. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20288. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20289. // Computing target and final matrix
  20290. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20291. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20292. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20293. return this._viewMatrix;
  20294. };
  20295. return _OculusInnerCamera;
  20296. })(BABYLON.FreeCamera);
  20297. var OculusCamera = (function (_super) {
  20298. __extends(OculusCamera, _super);
  20299. function OculusCamera(name, position, scene) {
  20300. _super.call(this, name, position, scene);
  20301. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  20302. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  20303. this.subCameras.push(this._leftCamera);
  20304. this.subCameras.push(this._rightCamera);
  20305. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20306. }
  20307. OculusCamera.prototype._update = function () {
  20308. this._leftCamera.position.copyFrom(this.position);
  20309. this._rightCamera.position.copyFrom(this.position);
  20310. this._updateCamera(this._leftCamera);
  20311. this._updateCamera(this._rightCamera);
  20312. _super.prototype._update.call(this);
  20313. };
  20314. OculusCamera.prototype._updateCamera = function (camera) {
  20315. camera.minZ = this.minZ;
  20316. camera.maxZ = this.maxZ;
  20317. camera.rotation.x = this.rotation.x;
  20318. camera.rotation.y = this.rotation.y;
  20319. camera.rotation.z = this.rotation.z;
  20320. };
  20321. // Oculus events
  20322. OculusCamera.prototype._onOrientationEvent = function (evt) {
  20323. var yaw = evt.alpha / 180 * Math.PI;
  20324. var pitch = evt.beta / 180 * Math.PI;
  20325. var roll = evt.gamma / 180 * Math.PI;
  20326. if (!this._offsetOrientation) {
  20327. this._offsetOrientation = {
  20328. yaw: yaw,
  20329. pitch: pitch,
  20330. roll: roll
  20331. };
  20332. return;
  20333. }
  20334. else {
  20335. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20336. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20337. this.rotation.z += this._offsetOrientation.roll - roll;
  20338. this._offsetOrientation.yaw = yaw;
  20339. this._offsetOrientation.pitch = pitch;
  20340. this._offsetOrientation.roll = roll;
  20341. }
  20342. };
  20343. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  20344. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20345. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20346. };
  20347. OculusCamera.prototype.detachControl = function (element) {
  20348. _super.prototype.detachControl.call(this, element);
  20349. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20350. };
  20351. return OculusCamera;
  20352. })(BABYLON.FreeCamera);
  20353. BABYLON.OculusCamera = OculusCamera;
  20354. })(BABYLON || (BABYLON = {}));
  20355. //# sourceMappingURL=babylon.oculusCamera.js.map
  20356. var BABYLON;
  20357. (function (BABYLON) {
  20358. var OculusRiftDevKit2013_Metric = {
  20359. HResolution: 1280,
  20360. VResolution: 800,
  20361. HScreenSize: 0.149759993,
  20362. VScreenSize: 0.0935999975,
  20363. VScreenCenter: 0.0467999987,
  20364. EyeToScreenDistance: 0.0410000011,
  20365. LensSeparationDistance: 0.0635000020,
  20366. InterpupillaryDistance: 0.0640000030,
  20367. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20368. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20369. PostProcessScaleFactor: 1.714605507808412,
  20370. LensCenterOffset: 0.151976421
  20371. };
  20372. var _OculusInnerGamepadCamera = (function (_super) {
  20373. __extends(_OculusInnerGamepadCamera, _super);
  20374. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  20375. _super.call(this, name, position, scene);
  20376. this._workMatrix = new BABYLON.Matrix();
  20377. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20378. // Constants
  20379. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20380. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20381. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20382. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20383. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20384. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20385. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20386. // Postprocess
  20387. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20388. }
  20389. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  20390. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20391. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20392. return this._projectionMatrix;
  20393. };
  20394. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  20395. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20396. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20397. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20398. // Computing target and final matrix
  20399. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20400. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20401. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20402. return this._viewMatrix;
  20403. };
  20404. return _OculusInnerGamepadCamera;
  20405. })(BABYLON.FreeCamera);
  20406. var OculusGamepadCamera = (function (_super) {
  20407. __extends(OculusGamepadCamera, _super);
  20408. function OculusGamepadCamera(name, position, scene) {
  20409. var _this = this;
  20410. _super.call(this, name, position, scene);
  20411. this.angularSensibility = 200;
  20412. this.moveSensibility = 75;
  20413. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  20414. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  20415. this.subCameras.push(this._leftCamera);
  20416. this.subCameras.push(this._rightCamera);
  20417. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20418. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  20419. _this._onNewGameConnected(gamepad);
  20420. });
  20421. }
  20422. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  20423. // Only the first gamepad can control the camera
  20424. if (gamepad.index === 0) {
  20425. this._gamepad = gamepad;
  20426. }
  20427. };
  20428. OculusGamepadCamera.prototype._update = function () {
  20429. this._leftCamera.position.copyFrom(this.position);
  20430. this._rightCamera.position.copyFrom(this.position);
  20431. this._updateCamera(this._leftCamera);
  20432. this._updateCamera(this._rightCamera);
  20433. _super.prototype._update.call(this);
  20434. };
  20435. OculusGamepadCamera.prototype._checkInputs = function () {
  20436. if (!this._gamepad) {
  20437. return;
  20438. }
  20439. var LSValues = this._gamepad.leftStick;
  20440. var normalizedLX = LSValues.x / this.moveSensibility;
  20441. var normalizedLY = LSValues.y / this.moveSensibility;
  20442. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  20443. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  20444. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20445. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  20446. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20447. };
  20448. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  20449. camera.minZ = this.minZ;
  20450. camera.maxZ = this.maxZ;
  20451. camera.rotation.x = this.rotation.x;
  20452. camera.rotation.y = this.rotation.y;
  20453. camera.rotation.z = this.rotation.z;
  20454. };
  20455. // Oculus events
  20456. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  20457. var yaw = evt.alpha / 180 * Math.PI;
  20458. var pitch = evt.beta / 180 * Math.PI;
  20459. var roll = evt.gamma / 180 * Math.PI;
  20460. if (!this._offsetOrientation) {
  20461. this._offsetOrientation = {
  20462. yaw: yaw,
  20463. pitch: pitch,
  20464. roll: roll
  20465. };
  20466. return;
  20467. }
  20468. else {
  20469. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20470. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20471. this.rotation.z += this._offsetOrientation.roll - roll;
  20472. this._offsetOrientation.yaw = yaw;
  20473. this._offsetOrientation.pitch = pitch;
  20474. this._offsetOrientation.roll = roll;
  20475. }
  20476. };
  20477. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  20478. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20479. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20480. };
  20481. OculusGamepadCamera.prototype.detachControl = function (element) {
  20482. _super.prototype.detachControl.call(this, element);
  20483. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20484. };
  20485. OculusGamepadCamera.prototype.dispose = function () {
  20486. this._gamepads.dispose();
  20487. _super.prototype.dispose.call(this);
  20488. };
  20489. return OculusGamepadCamera;
  20490. })(BABYLON.FreeCamera);
  20491. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  20492. })(BABYLON || (BABYLON = {}));
  20493. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  20494. var BABYLON;
  20495. (function (BABYLON) {
  20496. // We're mainly based on the logic defined into the FreeCamera code
  20497. var VirtualJoysticksCamera = (function (_super) {
  20498. __extends(VirtualJoysticksCamera, _super);
  20499. function VirtualJoysticksCamera(name, position, scene) {
  20500. _super.call(this, name, position, scene);
  20501. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  20502. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  20503. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  20504. this._leftjoystick.setJoystickSensibility(0.15);
  20505. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  20506. this._rightjoystick.setAxisForUpDown(0 /* X */);
  20507. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  20508. this._rightjoystick.reverseUpDown = true;
  20509. this._rightjoystick.setJoystickSensibility(0.05);
  20510. this._rightjoystick.setJoystickColor("yellow");
  20511. }
  20512. VirtualJoysticksCamera.prototype._checkInputs = function () {
  20513. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20514. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  20515. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20516. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  20517. if (!this._leftjoystick.pressed) {
  20518. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  20519. }
  20520. if (!this._rightjoystick.pressed) {
  20521. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  20522. }
  20523. };
  20524. VirtualJoysticksCamera.prototype.dispose = function () {
  20525. this._leftjoystick.releaseCanvas();
  20526. _super.prototype.dispose.call(this);
  20527. };
  20528. return VirtualJoysticksCamera;
  20529. })(BABYLON.FreeCamera);
  20530. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  20531. })(BABYLON || (BABYLON = {}));
  20532. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  20533. var BABYLON;
  20534. (function (BABYLON) {
  20535. var ShaderMaterial = (function (_super) {
  20536. __extends(ShaderMaterial, _super);
  20537. function ShaderMaterial(name, scene, shaderPath, options) {
  20538. _super.call(this, name, scene);
  20539. this._textures = new Array();
  20540. this._floats = new Array();
  20541. this._floatsArrays = {};
  20542. this._colors3 = new Array();
  20543. this._colors4 = new Array();
  20544. this._vectors2 = new Array();
  20545. this._vectors3 = new Array();
  20546. this._matrices = new Array();
  20547. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  20548. this._shaderPath = shaderPath;
  20549. options.needAlphaBlending = options.needAlphaBlending || false;
  20550. options.needAlphaTesting = options.needAlphaTesting || false;
  20551. options.attributes = options.attributes || ["position", "normal", "uv"];
  20552. options.uniforms = options.uniforms || ["worldViewProjection"];
  20553. options.samplers = options.samplers || [];
  20554. this._options = options;
  20555. }
  20556. ShaderMaterial.prototype.needAlphaBlending = function () {
  20557. return this._options.needAlphaBlending;
  20558. };
  20559. ShaderMaterial.prototype.needAlphaTesting = function () {
  20560. return this._options.needAlphaTesting;
  20561. };
  20562. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  20563. if (this._options.uniforms.indexOf(uniformName) === -1) {
  20564. this._options.uniforms.push(uniformName);
  20565. }
  20566. };
  20567. ShaderMaterial.prototype.setTexture = function (name, texture) {
  20568. if (this._options.samplers.indexOf(name) === -1) {
  20569. this._options.samplers.push(name);
  20570. }
  20571. this._textures[name] = texture;
  20572. return this;
  20573. };
  20574. ShaderMaterial.prototype.setFloat = function (name, value) {
  20575. this._checkUniform(name);
  20576. this._floats[name] = value;
  20577. return this;
  20578. };
  20579. ShaderMaterial.prototype.setFloats = function (name, value) {
  20580. this._checkUniform(name);
  20581. this._floatsArrays[name] = value;
  20582. return this;
  20583. };
  20584. ShaderMaterial.prototype.setColor3 = function (name, value) {
  20585. this._checkUniform(name);
  20586. this._colors3[name] = value;
  20587. return this;
  20588. };
  20589. ShaderMaterial.prototype.setColor4 = function (name, value) {
  20590. this._checkUniform(name);
  20591. this._colors4[name] = value;
  20592. return this;
  20593. };
  20594. ShaderMaterial.prototype.setVector2 = function (name, value) {
  20595. this._checkUniform(name);
  20596. this._vectors2[name] = value;
  20597. return this;
  20598. };
  20599. ShaderMaterial.prototype.setVector3 = function (name, value) {
  20600. this._checkUniform(name);
  20601. this._vectors3[name] = value;
  20602. return this;
  20603. };
  20604. ShaderMaterial.prototype.setMatrix = function (name, value) {
  20605. this._checkUniform(name);
  20606. this._matrices[name] = value;
  20607. return this;
  20608. };
  20609. ShaderMaterial.prototype.isReady = function () {
  20610. var scene = this.getScene();
  20611. var engine = scene.getEngine();
  20612. if (!this.checkReadyOnEveryCall) {
  20613. if (this._renderId === scene.getRenderId()) {
  20614. return true;
  20615. }
  20616. }
  20617. var previousEffect = this._effect;
  20618. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  20619. if (!this._effect.isReady()) {
  20620. return false;
  20621. }
  20622. if (previousEffect !== this._effect) {
  20623. scene.resetCachedMaterial();
  20624. }
  20625. this._renderId = scene.getRenderId();
  20626. return true;
  20627. };
  20628. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20629. var scene = this.getScene();
  20630. if (this._options.uniforms.indexOf("world") !== -1) {
  20631. this._effect.setMatrix("world", world);
  20632. }
  20633. if (this._options.uniforms.indexOf("worldView") !== -1) {
  20634. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  20635. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  20636. }
  20637. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  20638. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  20639. }
  20640. };
  20641. ShaderMaterial.prototype.bind = function (world) {
  20642. // Std values
  20643. this.bindOnlyWorldMatrix(world);
  20644. if (this.getScene().getCachedMaterial() !== this) {
  20645. if (this._options.uniforms.indexOf("view") !== -1) {
  20646. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  20647. }
  20648. if (this._options.uniforms.indexOf("projection") !== -1) {
  20649. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  20650. }
  20651. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  20652. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  20653. }
  20654. for (var name in this._textures) {
  20655. this._effect.setTexture(name, this._textures[name]);
  20656. }
  20657. for (name in this._floats) {
  20658. this._effect.setFloat(name, this._floats[name]);
  20659. }
  20660. for (name in this._floatsArrays) {
  20661. this._effect.setArray(name, this._floatsArrays[name]);
  20662. }
  20663. for (name in this._colors3) {
  20664. this._effect.setColor3(name, this._colors3[name]);
  20665. }
  20666. for (name in this._colors4) {
  20667. var color = this._colors4[name];
  20668. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  20669. }
  20670. for (name in this._vectors2) {
  20671. this._effect.setVector2(name, this._vectors2[name]);
  20672. }
  20673. for (name in this._vectors3) {
  20674. this._effect.setVector3(name, this._vectors3[name]);
  20675. }
  20676. for (name in this._matrices) {
  20677. this._effect.setMatrix(name, this._matrices[name]);
  20678. }
  20679. }
  20680. _super.prototype.bind.call(this, world, null);
  20681. };
  20682. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  20683. for (var name in this._textures) {
  20684. this._textures[name].dispose();
  20685. }
  20686. this._textures = [];
  20687. _super.prototype.dispose.call(this, forceDisposeEffect);
  20688. };
  20689. return ShaderMaterial;
  20690. })(BABYLON.Material);
  20691. BABYLON.ShaderMaterial = ShaderMaterial;
  20692. })(BABYLON || (BABYLON = {}));
  20693. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  20694. (function (BABYLON) {
  20695. var VertexData = (function () {
  20696. function VertexData() {
  20697. }
  20698. VertexData.prototype.set = function (data, kind) {
  20699. switch (kind) {
  20700. case BABYLON.VertexBuffer.PositionKind:
  20701. this.positions = data;
  20702. break;
  20703. case BABYLON.VertexBuffer.NormalKind:
  20704. this.normals = data;
  20705. break;
  20706. case BABYLON.VertexBuffer.UVKind:
  20707. this.uvs = data;
  20708. break;
  20709. case BABYLON.VertexBuffer.UV2Kind:
  20710. this.uv2s = data;
  20711. break;
  20712. case BABYLON.VertexBuffer.ColorKind:
  20713. this.colors = data;
  20714. break;
  20715. case BABYLON.VertexBuffer.MatricesIndicesKind:
  20716. this.matricesIndices = data;
  20717. break;
  20718. case BABYLON.VertexBuffer.MatricesWeightsKind:
  20719. this.matricesWeights = data;
  20720. break;
  20721. }
  20722. };
  20723. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  20724. this._applyTo(mesh, updatable);
  20725. };
  20726. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  20727. this._applyTo(geometry, updatable);
  20728. };
  20729. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  20730. this._update(mesh);
  20731. };
  20732. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  20733. this._update(geometry);
  20734. };
  20735. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  20736. if (this.positions) {
  20737. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  20738. }
  20739. if (this.normals) {
  20740. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  20741. }
  20742. if (this.uvs) {
  20743. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  20744. }
  20745. if (this.uv2s) {
  20746. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  20747. }
  20748. if (this.colors) {
  20749. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  20750. }
  20751. if (this.matricesIndices) {
  20752. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  20753. }
  20754. if (this.matricesWeights) {
  20755. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  20756. }
  20757. if (this.indices) {
  20758. meshOrGeometry.setIndices(this.indices);
  20759. }
  20760. };
  20761. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  20762. if (this.positions) {
  20763. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  20764. }
  20765. if (this.normals) {
  20766. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  20767. }
  20768. if (this.uvs) {
  20769. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  20770. }
  20771. if (this.uv2s) {
  20772. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  20773. }
  20774. if (this.colors) {
  20775. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  20776. }
  20777. if (this.matricesIndices) {
  20778. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  20779. }
  20780. if (this.matricesWeights) {
  20781. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  20782. }
  20783. if (this.indices) {
  20784. meshOrGeometry.setIndices(this.indices);
  20785. }
  20786. };
  20787. VertexData.prototype.transform = function (matrix) {
  20788. var transformed = BABYLON.Vector3.Zero();
  20789. if (this.positions) {
  20790. var position = BABYLON.Vector3.Zero();
  20791. for (var index = 0; index < this.positions.length; index += 3) {
  20792. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  20793. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  20794. this.positions[index] = transformed.x;
  20795. this.positions[index + 1] = transformed.y;
  20796. this.positions[index + 2] = transformed.z;
  20797. }
  20798. }
  20799. if (this.normals) {
  20800. var normal = BABYLON.Vector3.Zero();
  20801. for (index = 0; index < this.normals.length; index += 3) {
  20802. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  20803. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  20804. this.normals[index] = transformed.x;
  20805. this.normals[index + 1] = transformed.y;
  20806. this.normals[index + 2] = transformed.z;
  20807. }
  20808. }
  20809. };
  20810. VertexData.prototype.merge = function (other) {
  20811. if (other.indices) {
  20812. if (!this.indices) {
  20813. this.indices = [];
  20814. }
  20815. var offset = this.positions ? this.positions.length / 3 : 0;
  20816. for (var index = 0; index < other.indices.length; index++) {
  20817. this.indices.push(other.indices[index] + offset);
  20818. }
  20819. }
  20820. if (other.positions) {
  20821. if (!this.positions) {
  20822. this.positions = [];
  20823. }
  20824. for (index = 0; index < other.positions.length; index++) {
  20825. this.positions.push(other.positions[index]);
  20826. }
  20827. }
  20828. if (other.normals) {
  20829. if (!this.normals) {
  20830. this.normals = [];
  20831. }
  20832. for (index = 0; index < other.normals.length; index++) {
  20833. this.normals.push(other.normals[index]);
  20834. }
  20835. }
  20836. if (other.uvs) {
  20837. if (!this.uvs) {
  20838. this.uvs = [];
  20839. }
  20840. for (index = 0; index < other.uvs.length; index++) {
  20841. this.uvs.push(other.uvs[index]);
  20842. }
  20843. }
  20844. if (other.uv2s) {
  20845. if (!this.uv2s) {
  20846. this.uv2s = [];
  20847. }
  20848. for (index = 0; index < other.uv2s.length; index++) {
  20849. this.uv2s.push(other.uv2s[index]);
  20850. }
  20851. }
  20852. if (other.matricesIndices) {
  20853. if (!this.matricesIndices) {
  20854. this.matricesIndices = [];
  20855. }
  20856. for (index = 0; index < other.matricesIndices.length; index++) {
  20857. this.matricesIndices.push(other.matricesIndices[index]);
  20858. }
  20859. }
  20860. if (other.matricesWeights) {
  20861. if (!this.matricesWeights) {
  20862. this.matricesWeights = [];
  20863. }
  20864. for (index = 0; index < other.matricesWeights.length; index++) {
  20865. this.matricesWeights.push(other.matricesWeights[index]);
  20866. }
  20867. }
  20868. if (other.colors) {
  20869. if (!this.colors) {
  20870. this.colors = [];
  20871. }
  20872. for (index = 0; index < other.colors.length; index++) {
  20873. this.colors.push(other.colors[index]);
  20874. }
  20875. }
  20876. };
  20877. // Statics
  20878. VertexData.ExtractFromMesh = function (mesh) {
  20879. return VertexData._ExtractFrom(mesh);
  20880. };
  20881. VertexData.ExtractFromGeometry = function (geometry) {
  20882. return VertexData._ExtractFrom(geometry);
  20883. };
  20884. VertexData._ExtractFrom = function (meshOrGeometry) {
  20885. var result = new BABYLON.VertexData();
  20886. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20887. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20888. }
  20889. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20890. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20891. }
  20892. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20893. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20894. }
  20895. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20896. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  20897. }
  20898. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20899. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  20900. }
  20901. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20902. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20903. }
  20904. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20905. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20906. }
  20907. result.indices = meshOrGeometry.getIndices();
  20908. return result;
  20909. };
  20910. VertexData.CreateBox = function (size) {
  20911. var normalsSource = [
  20912. new BABYLON.Vector3(0, 0, 1),
  20913. new BABYLON.Vector3(0, 0, -1),
  20914. new BABYLON.Vector3(1, 0, 0),
  20915. new BABYLON.Vector3(-1, 0, 0),
  20916. new BABYLON.Vector3(0, 1, 0),
  20917. new BABYLON.Vector3(0, -1, 0)
  20918. ];
  20919. var indices = [];
  20920. var positions = [];
  20921. var normals = [];
  20922. var uvs = [];
  20923. size = size || 1;
  20924. for (var index = 0; index < normalsSource.length; index++) {
  20925. var normal = normalsSource[index];
  20926. // Get two vectors perpendicular to the face normal and to each other.
  20927. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  20928. var side2 = BABYLON.Vector3.Cross(normal, side1);
  20929. // Six indices (two triangles) per face.
  20930. var verticesLength = positions.length / 3;
  20931. indices.push(verticesLength);
  20932. indices.push(verticesLength + 1);
  20933. indices.push(verticesLength + 2);
  20934. indices.push(verticesLength);
  20935. indices.push(verticesLength + 2);
  20936. indices.push(verticesLength + 3);
  20937. // Four vertices per face.
  20938. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  20939. positions.push(vertex.x, vertex.y, vertex.z);
  20940. normals.push(normal.x, normal.y, normal.z);
  20941. uvs.push(1.0, 1.0);
  20942. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  20943. positions.push(vertex.x, vertex.y, vertex.z);
  20944. normals.push(normal.x, normal.y, normal.z);
  20945. uvs.push(0.0, 1.0);
  20946. vertex = normal.add(side1).add(side2).scale(size / 2);
  20947. positions.push(vertex.x, vertex.y, vertex.z);
  20948. normals.push(normal.x, normal.y, normal.z);
  20949. uvs.push(0.0, 0.0);
  20950. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  20951. positions.push(vertex.x, vertex.y, vertex.z);
  20952. normals.push(normal.x, normal.y, normal.z);
  20953. uvs.push(1.0, 0.0);
  20954. }
  20955. // Result
  20956. var vertexData = new BABYLON.VertexData();
  20957. vertexData.indices = indices;
  20958. vertexData.positions = positions;
  20959. vertexData.normals = normals;
  20960. vertexData.uvs = uvs;
  20961. return vertexData;
  20962. };
  20963. VertexData.CreateSphere = function (segments, diameter) {
  20964. segments = segments || 32;
  20965. diameter = diameter || 1;
  20966. var radius = diameter / 2;
  20967. var totalZRotationSteps = 2 + segments;
  20968. var totalYRotationSteps = 2 * totalZRotationSteps;
  20969. var indices = [];
  20970. var positions = [];
  20971. var normals = [];
  20972. var uvs = [];
  20973. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  20974. var normalizedZ = zRotationStep / totalZRotationSteps;
  20975. var angleZ = (normalizedZ * Math.PI);
  20976. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  20977. var normalizedY = yRotationStep / totalYRotationSteps;
  20978. var angleY = normalizedY * Math.PI * 2;
  20979. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  20980. var rotationY = BABYLON.Matrix.RotationY(angleY);
  20981. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  20982. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  20983. var vertex = complete.scale(radius);
  20984. var normal = BABYLON.Vector3.Normalize(vertex);
  20985. positions.push(vertex.x, vertex.y, vertex.z);
  20986. normals.push(normal.x, normal.y, normal.z);
  20987. uvs.push(normalizedZ, normalizedY);
  20988. }
  20989. if (zRotationStep > 0) {
  20990. var verticesCount = positions.length / 3;
  20991. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  20992. indices.push((firstIndex));
  20993. indices.push((firstIndex + 1));
  20994. indices.push(firstIndex + totalYRotationSteps + 1);
  20995. indices.push((firstIndex + totalYRotationSteps + 1));
  20996. indices.push((firstIndex + 1));
  20997. indices.push((firstIndex + totalYRotationSteps + 2));
  20998. }
  20999. }
  21000. }
  21001. // Result
  21002. var vertexData = new BABYLON.VertexData();
  21003. vertexData.indices = indices;
  21004. vertexData.positions = positions;
  21005. vertexData.normals = normals;
  21006. vertexData.uvs = uvs;
  21007. return vertexData;
  21008. };
  21009. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  21010. if (subdivisions === void 0) { subdivisions = 1; }
  21011. var radiusTop = diameterTop / 2;
  21012. var radiusBottom = diameterBottom / 2;
  21013. var indices = [];
  21014. var positions = [];
  21015. var normals = [];
  21016. var uvs = [];
  21017. height = height || 1;
  21018. diameterTop = diameterTop || 0.5;
  21019. diameterBottom = diameterBottom || 1;
  21020. tessellation = tessellation || 16;
  21021. subdivisions = subdivisions || 1;
  21022. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  21023. var getCircleVector = function (i) {
  21024. var angle = (i * 2.0 * Math.PI / tessellation);
  21025. var dx = Math.cos(angle);
  21026. var dz = Math.sin(angle);
  21027. return new BABYLON.Vector3(dx, 0, dz);
  21028. };
  21029. var createCylinderCap = function (isTop) {
  21030. var radius = isTop ? radiusTop : radiusBottom;
  21031. if (radius == 0) {
  21032. return;
  21033. }
  21034. var vbase = positions.length / 3;
  21035. var offset = new BABYLON.Vector3(0, height / 2, 0);
  21036. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  21037. if (!isTop) {
  21038. offset.scaleInPlace(-1);
  21039. textureScale.x = -textureScale.x;
  21040. }
  21041. for (i = 0; i < tessellation; i++) {
  21042. var circleVector = getCircleVector(i);
  21043. var position = circleVector.scale(radius).add(offset);
  21044. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  21045. positions.push(position.x, position.y, position.z);
  21046. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21047. }
  21048. for (var i = 0; i < tessellation - 2; i++) {
  21049. if (!isTop) {
  21050. indices.push(vbase);
  21051. indices.push(vbase + (i + 2) % tessellation);
  21052. indices.push(vbase + (i + 1) % tessellation);
  21053. }
  21054. else {
  21055. indices.push(vbase);
  21056. indices.push(vbase + (i + 1) % tessellation);
  21057. indices.push(vbase + (i + 2) % tessellation);
  21058. }
  21059. }
  21060. };
  21061. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  21062. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  21063. var stride = tessellation + 1;
  21064. for (var i = 0; i <= tessellation; i++) {
  21065. var circleVector = getCircleVector(i);
  21066. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  21067. var position, radius = radiusBottom;
  21068. for (var s = 0; s <= subdivisions; s++) {
  21069. // Update variables
  21070. position = circleVector.scale(radius);
  21071. position.addInPlace(base.add(offset.scale(s)));
  21072. textureCoordinate.y += 1 / subdivisions;
  21073. radius += (radiusTop - radiusBottom) / subdivisions;
  21074. // Push in arrays
  21075. positions.push(position.x, position.y, position.z);
  21076. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21077. }
  21078. }
  21079. subdivisions += 1;
  21080. for (var s = 0; s < subdivisions - 1; s++) {
  21081. for (var i = 0; i <= tessellation; i++) {
  21082. indices.push(i * subdivisions + s);
  21083. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21084. indices.push(i * subdivisions + (s + 1));
  21085. indices.push(i * subdivisions + (s + 1));
  21086. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21087. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  21088. }
  21089. }
  21090. // Create flat triangle fan caps to seal the top and bottom.
  21091. createCylinderCap(true);
  21092. createCylinderCap(false);
  21093. // Normals
  21094. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21095. // Result
  21096. var vertexData = new BABYLON.VertexData();
  21097. vertexData.indices = indices;
  21098. vertexData.positions = positions;
  21099. vertexData.normals = normals;
  21100. vertexData.uvs = uvs;
  21101. return vertexData;
  21102. };
  21103. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  21104. var indices = [];
  21105. var positions = [];
  21106. var normals = [];
  21107. var uvs = [];
  21108. diameter = diameter || 1;
  21109. thickness = thickness || 0.5;
  21110. tessellation = tessellation || 16;
  21111. var stride = tessellation + 1;
  21112. for (var i = 0; i <= tessellation; i++) {
  21113. var u = i / tessellation;
  21114. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  21115. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  21116. for (var j = 0; j <= tessellation; j++) {
  21117. var v = 1 - j / tessellation;
  21118. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  21119. var dx = Math.cos(innerAngle);
  21120. var dy = Math.sin(innerAngle);
  21121. // Create a vertex.
  21122. var normal = new BABYLON.Vector3(dx, dy, 0);
  21123. var position = normal.scale(thickness / 2);
  21124. var textureCoordinate = new BABYLON.Vector2(u, v);
  21125. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  21126. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  21127. positions.push(position.x, position.y, position.z);
  21128. normals.push(normal.x, normal.y, normal.z);
  21129. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21130. // And create indices for two triangles.
  21131. var nextI = (i + 1) % stride;
  21132. var nextJ = (j + 1) % stride;
  21133. indices.push(i * stride + j);
  21134. indices.push(i * stride + nextJ);
  21135. indices.push(nextI * stride + j);
  21136. indices.push(i * stride + nextJ);
  21137. indices.push(nextI * stride + nextJ);
  21138. indices.push(nextI * stride + j);
  21139. }
  21140. }
  21141. // Result
  21142. var vertexData = new BABYLON.VertexData();
  21143. vertexData.indices = indices;
  21144. vertexData.positions = positions;
  21145. vertexData.normals = normals;
  21146. vertexData.uvs = uvs;
  21147. return vertexData;
  21148. };
  21149. VertexData.CreateLines = function (points) {
  21150. var indices = [];
  21151. var positions = [];
  21152. for (var index = 0; index < points.length; index++) {
  21153. positions.push(points[index].x, points[index].y, points[index].z);
  21154. if (index > 0) {
  21155. indices.push(index - 1);
  21156. indices.push(index);
  21157. }
  21158. }
  21159. // Result
  21160. var vertexData = new BABYLON.VertexData();
  21161. vertexData.indices = indices;
  21162. vertexData.positions = positions;
  21163. return vertexData;
  21164. };
  21165. VertexData.CreateGround = function (width, height, subdivisions) {
  21166. var indices = [];
  21167. var positions = [];
  21168. var normals = [];
  21169. var uvs = [];
  21170. var row, col;
  21171. width = width || 1;
  21172. height = height || 1;
  21173. subdivisions = subdivisions || 1;
  21174. for (row = 0; row <= subdivisions; row++) {
  21175. for (col = 0; col <= subdivisions; col++) {
  21176. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21177. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21178. positions.push(position.x, position.y, position.z);
  21179. normals.push(normal.x, normal.y, normal.z);
  21180. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21181. }
  21182. }
  21183. for (row = 0; row < subdivisions; row++) {
  21184. for (col = 0; col < subdivisions; col++) {
  21185. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21186. indices.push(col + 1 + row * (subdivisions + 1));
  21187. indices.push(col + row * (subdivisions + 1));
  21188. indices.push(col + (row + 1) * (subdivisions + 1));
  21189. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21190. indices.push(col + row * (subdivisions + 1));
  21191. }
  21192. }
  21193. // Result
  21194. var vertexData = new BABYLON.VertexData();
  21195. vertexData.indices = indices;
  21196. vertexData.positions = positions;
  21197. vertexData.normals = normals;
  21198. vertexData.uvs = uvs;
  21199. return vertexData;
  21200. };
  21201. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  21202. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  21203. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  21204. var indices = [];
  21205. var positions = [];
  21206. var normals = [];
  21207. var uvs = [];
  21208. var row, col, tileRow, tileCol;
  21209. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  21210. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  21211. precision.w = (precision.w < 1) ? 1 : precision.w;
  21212. precision.h = (precision.h < 1) ? 1 : precision.h;
  21213. var tileSize = {
  21214. 'w': (xmax - xmin) / subdivisions.w,
  21215. 'h': (zmax - zmin) / subdivisions.h
  21216. };
  21217. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  21218. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  21219. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  21220. }
  21221. }
  21222. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  21223. // Indices
  21224. var base = positions.length / 3;
  21225. var rowLength = precision.w + 1;
  21226. for (row = 0; row < precision.h; row++) {
  21227. for (col = 0; col < precision.w; col++) {
  21228. var square = [
  21229. base + col + row * rowLength,
  21230. base + (col + 1) + row * rowLength,
  21231. base + (col + 1) + (row + 1) * rowLength,
  21232. base + col + (row + 1) * rowLength
  21233. ];
  21234. indices.push(square[1]);
  21235. indices.push(square[2]);
  21236. indices.push(square[3]);
  21237. indices.push(square[0]);
  21238. indices.push(square[1]);
  21239. indices.push(square[3]);
  21240. }
  21241. }
  21242. // Position, normals and uvs
  21243. var position = BABYLON.Vector3.Zero();
  21244. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21245. for (row = 0; row <= precision.h; row++) {
  21246. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  21247. for (col = 0; col <= precision.w; col++) {
  21248. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  21249. position.y = 0;
  21250. positions.push(position.x, position.y, position.z);
  21251. normals.push(normal.x, normal.y, normal.z);
  21252. uvs.push(col / precision.w, row / precision.h);
  21253. }
  21254. }
  21255. }
  21256. // Result
  21257. var vertexData = new BABYLON.VertexData();
  21258. vertexData.indices = indices;
  21259. vertexData.positions = positions;
  21260. vertexData.normals = normals;
  21261. vertexData.uvs = uvs;
  21262. return vertexData;
  21263. };
  21264. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  21265. var indices = [];
  21266. var positions = [];
  21267. var normals = [];
  21268. var uvs = [];
  21269. var row, col;
  21270. for (row = 0; row <= subdivisions; row++) {
  21271. for (col = 0; col <= subdivisions; col++) {
  21272. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21273. // Compute height
  21274. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  21275. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  21276. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  21277. var r = buffer[pos] / 255.0;
  21278. var g = buffer[pos + 1] / 255.0;
  21279. var b = buffer[pos + 2] / 255.0;
  21280. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21281. position.y = minHeight + (maxHeight - minHeight) * gradient;
  21282. // Add vertex
  21283. positions.push(position.x, position.y, position.z);
  21284. normals.push(0, 0, 0);
  21285. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21286. }
  21287. }
  21288. for (row = 0; row < subdivisions; row++) {
  21289. for (col = 0; col < subdivisions; col++) {
  21290. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21291. indices.push(col + 1 + row * (subdivisions + 1));
  21292. indices.push(col + row * (subdivisions + 1));
  21293. indices.push(col + (row + 1) * (subdivisions + 1));
  21294. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21295. indices.push(col + row * (subdivisions + 1));
  21296. }
  21297. }
  21298. // Normals
  21299. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21300. // Result
  21301. var vertexData = new BABYLON.VertexData();
  21302. vertexData.indices = indices;
  21303. vertexData.positions = positions;
  21304. vertexData.normals = normals;
  21305. vertexData.uvs = uvs;
  21306. return vertexData;
  21307. };
  21308. VertexData.CreatePlane = function (size) {
  21309. var indices = [];
  21310. var positions = [];
  21311. var normals = [];
  21312. var uvs = [];
  21313. size = size || 1;
  21314. // Vertices
  21315. var halfSize = size / 2.0;
  21316. positions.push(-halfSize, -halfSize, 0);
  21317. normals.push(0, 0, -1.0);
  21318. uvs.push(0.0, 0.0);
  21319. positions.push(halfSize, -halfSize, 0);
  21320. normals.push(0, 0, -1.0);
  21321. uvs.push(1.0, 0.0);
  21322. positions.push(halfSize, halfSize, 0);
  21323. normals.push(0, 0, -1.0);
  21324. uvs.push(1.0, 1.0);
  21325. positions.push(-halfSize, halfSize, 0);
  21326. normals.push(0, 0, -1.0);
  21327. uvs.push(0.0, 1.0);
  21328. // Indices
  21329. indices.push(0);
  21330. indices.push(1);
  21331. indices.push(2);
  21332. indices.push(0);
  21333. indices.push(2);
  21334. indices.push(3);
  21335. // Result
  21336. var vertexData = new BABYLON.VertexData();
  21337. vertexData.indices = indices;
  21338. vertexData.positions = positions;
  21339. vertexData.normals = normals;
  21340. vertexData.uvs = uvs;
  21341. return vertexData;
  21342. };
  21343. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  21344. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  21345. var indices = [];
  21346. var positions = [];
  21347. var normals = [];
  21348. var uvs = [];
  21349. radius = radius || 2;
  21350. tube = tube || 0.5;
  21351. radialSegments = radialSegments || 32;
  21352. tubularSegments = tubularSegments || 32;
  21353. p = p || 2;
  21354. q = q || 3;
  21355. // Helper
  21356. var getPos = function (angle) {
  21357. var cu = Math.cos(angle);
  21358. var su = Math.sin(angle);
  21359. var quOverP = q / p * angle;
  21360. var cs = Math.cos(quOverP);
  21361. var tx = radius * (2 + cs) * 0.5 * cu;
  21362. var ty = radius * (2 + cs) * su * 0.5;
  21363. var tz = radius * Math.sin(quOverP) * 0.5;
  21364. return new BABYLON.Vector3(tx, ty, tz);
  21365. };
  21366. for (var i = 0; i <= radialSegments; i++) {
  21367. var modI = i % radialSegments;
  21368. var u = modI / radialSegments * 2 * p * Math.PI;
  21369. var p1 = getPos(u);
  21370. var p2 = getPos(u + 0.01);
  21371. var tang = p2.subtract(p1);
  21372. var n = p2.add(p1);
  21373. var bitan = BABYLON.Vector3.Cross(tang, n);
  21374. n = BABYLON.Vector3.Cross(bitan, tang);
  21375. bitan.normalize();
  21376. n.normalize();
  21377. for (var j = 0; j < tubularSegments; j++) {
  21378. var modJ = j % tubularSegments;
  21379. var v = modJ / tubularSegments * 2 * Math.PI;
  21380. var cx = -tube * Math.cos(v);
  21381. var cy = tube * Math.sin(v);
  21382. positions.push(p1.x + cx * n.x + cy * bitan.x);
  21383. positions.push(p1.y + cx * n.y + cy * bitan.y);
  21384. positions.push(p1.z + cx * n.z + cy * bitan.z);
  21385. uvs.push(i / radialSegments);
  21386. uvs.push(j / tubularSegments);
  21387. }
  21388. }
  21389. for (i = 0; i < radialSegments; i++) {
  21390. for (j = 0; j < tubularSegments; j++) {
  21391. var jNext = (j + 1) % tubularSegments;
  21392. var a = i * tubularSegments + j;
  21393. var b = (i + 1) * tubularSegments + j;
  21394. var c = (i + 1) * tubularSegments + jNext;
  21395. var d = i * tubularSegments + jNext;
  21396. indices.push(d);
  21397. indices.push(b);
  21398. indices.push(a);
  21399. indices.push(d);
  21400. indices.push(c);
  21401. indices.push(b);
  21402. }
  21403. }
  21404. // Normals
  21405. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21406. // Result
  21407. var vertexData = new BABYLON.VertexData();
  21408. vertexData.indices = indices;
  21409. vertexData.positions = positions;
  21410. vertexData.normals = normals;
  21411. vertexData.uvs = uvs;
  21412. return vertexData;
  21413. };
  21414. // Tools
  21415. VertexData.ComputeNormals = function (positions, indices, normals) {
  21416. var positionVectors = [];
  21417. var facesOfVertices = [];
  21418. var index;
  21419. for (index = 0; index < positions.length; index += 3) {
  21420. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  21421. positionVectors.push(vector3);
  21422. facesOfVertices.push([]);
  21423. }
  21424. // Compute normals
  21425. var facesNormals = [];
  21426. for (index = 0; index < indices.length / 3; index++) {
  21427. var i1 = indices[index * 3];
  21428. var i2 = indices[index * 3 + 1];
  21429. var i3 = indices[index * 3 + 2];
  21430. var p1 = positionVectors[i1];
  21431. var p2 = positionVectors[i2];
  21432. var p3 = positionVectors[i3];
  21433. var p1p2 = p1.subtract(p2);
  21434. var p3p2 = p3.subtract(p2);
  21435. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21436. facesOfVertices[i1].push(index);
  21437. facesOfVertices[i2].push(index);
  21438. facesOfVertices[i3].push(index);
  21439. }
  21440. for (index = 0; index < positionVectors.length; index++) {
  21441. var faces = facesOfVertices[index];
  21442. var normal = BABYLON.Vector3.Zero();
  21443. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  21444. normal.addInPlace(facesNormals[faces[faceIndex]]);
  21445. }
  21446. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  21447. normals[index * 3] = normal.x;
  21448. normals[index * 3 + 1] = normal.y;
  21449. normals[index * 3 + 2] = normal.z;
  21450. }
  21451. };
  21452. return VertexData;
  21453. })();
  21454. BABYLON.VertexData = VertexData;
  21455. })(BABYLON || (BABYLON = {}));
  21456. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  21457. var BABYLON;
  21458. (function (BABYLON) {
  21459. var buildCamera = function (that, name) {
  21460. that._leftCamera.isIntermediate = true;
  21461. that.subCameras.push(that._leftCamera);
  21462. that.subCameras.push(that._rightCamera);
  21463. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  21464. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  21465. that._anaglyphPostProcess.onApply = function (effect) {
  21466. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  21467. };
  21468. that._update();
  21469. };
  21470. var AnaglyphArcRotateCamera = (function (_super) {
  21471. __extends(AnaglyphArcRotateCamera, _super);
  21472. // ANY
  21473. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  21474. _super.call(this, name, alpha, beta, radius, target, scene);
  21475. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21476. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  21477. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  21478. buildCamera(this, name);
  21479. }
  21480. AnaglyphArcRotateCamera.prototype._update = function () {
  21481. this._updateCamera(this._leftCamera);
  21482. this._updateCamera(this._rightCamera);
  21483. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  21484. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  21485. _super.prototype._update.call(this);
  21486. };
  21487. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  21488. camera.beta = this.beta;
  21489. camera.radius = this.radius;
  21490. camera.minZ = this.minZ;
  21491. camera.maxZ = this.maxZ;
  21492. camera.fov = this.fov;
  21493. camera.target = this.target;
  21494. };
  21495. return AnaglyphArcRotateCamera;
  21496. })(BABYLON.ArcRotateCamera);
  21497. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  21498. var AnaglyphFreeCamera = (function (_super) {
  21499. __extends(AnaglyphFreeCamera, _super);
  21500. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  21501. _super.call(this, name, position, scene);
  21502. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21503. this._transformMatrix = new BABYLON.Matrix();
  21504. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  21505. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  21506. buildCamera(this, name);
  21507. }
  21508. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  21509. var target = this.getTarget();
  21510. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  21511. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  21512. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  21513. };
  21514. AnaglyphFreeCamera.prototype._update = function () {
  21515. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  21516. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  21517. this._updateCamera(this._leftCamera);
  21518. this._updateCamera(this._rightCamera);
  21519. _super.prototype._update.call(this);
  21520. };
  21521. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  21522. camera.minZ = this.minZ;
  21523. camera.maxZ = this.maxZ;
  21524. camera.fov = this.fov;
  21525. camera.viewport = this.viewport;
  21526. camera.setTarget(this.getTarget());
  21527. };
  21528. return AnaglyphFreeCamera;
  21529. })(BABYLON.FreeCamera);
  21530. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  21531. })(BABYLON || (BABYLON = {}));
  21532. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  21533. var BABYLON;
  21534. (function (BABYLON) {
  21535. var AnaglyphPostProcess = (function (_super) {
  21536. __extends(AnaglyphPostProcess, _super);
  21537. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21538. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  21539. }
  21540. return AnaglyphPostProcess;
  21541. })(BABYLON.PostProcess);
  21542. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  21543. })(BABYLON || (BABYLON = {}));
  21544. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  21545. (function (BABYLON) {
  21546. var Tags = (function () {
  21547. function Tags() {
  21548. }
  21549. Tags.EnableFor = function (obj) {
  21550. obj._tags = obj._tags || {};
  21551. obj.hasTags = function () {
  21552. return Tags.HasTags(obj);
  21553. };
  21554. obj.addTags = function (tagsString) {
  21555. return Tags.AddTagsTo(obj, tagsString);
  21556. };
  21557. obj.removeTags = function (tagsString) {
  21558. return Tags.RemoveTagsFrom(obj, tagsString);
  21559. };
  21560. obj.matchesTagsQuery = function (tagsQuery) {
  21561. return Tags.MatchesQuery(obj, tagsQuery);
  21562. };
  21563. };
  21564. Tags.DisableFor = function (obj) {
  21565. delete obj._tags;
  21566. delete obj.hasTags;
  21567. delete obj.addTags;
  21568. delete obj.removeTags;
  21569. delete obj.matchesTagsQuery;
  21570. };
  21571. Tags.HasTags = function (obj) {
  21572. if (!obj._tags) {
  21573. return false;
  21574. }
  21575. return !BABYLON.Tools.IsEmpty(obj._tags);
  21576. };
  21577. Tags.GetTags = function (obj) {
  21578. if (!obj._tags) {
  21579. return null;
  21580. }
  21581. return obj._tags;
  21582. };
  21583. // the tags 'true' and 'false' are reserved and cannot be used as tags
  21584. // a tag cannot start with '||', '&&', and '!'
  21585. // it cannot contain whitespaces
  21586. Tags.AddTagsTo = function (obj, tagsString) {
  21587. if (!tagsString) {
  21588. return;
  21589. }
  21590. var tags = tagsString.split(" ");
  21591. for (var t in tags) {
  21592. Tags._AddTagTo(obj, tags[t]);
  21593. }
  21594. };
  21595. Tags._AddTagTo = function (obj, tag) {
  21596. tag = tag.trim();
  21597. if (tag === "" || tag === "true" || tag === "false") {
  21598. return;
  21599. }
  21600. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  21601. return;
  21602. }
  21603. Tags.EnableFor(obj);
  21604. obj._tags[tag] = true;
  21605. };
  21606. Tags.RemoveTagsFrom = function (obj, tagsString) {
  21607. if (!Tags.HasTags(obj)) {
  21608. return;
  21609. }
  21610. var tags = tagsString.split(" ");
  21611. for (var t in tags) {
  21612. Tags._RemoveTagFrom(obj, tags[t]);
  21613. }
  21614. };
  21615. Tags._RemoveTagFrom = function (obj, tag) {
  21616. delete obj._tags[tag];
  21617. };
  21618. Tags.MatchesQuery = function (obj, tagsQuery) {
  21619. if (tagsQuery === undefined) {
  21620. return true;
  21621. }
  21622. if (tagsQuery === "") {
  21623. return Tags.HasTags(obj);
  21624. }
  21625. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  21626. };
  21627. return Tags;
  21628. })();
  21629. BABYLON.Tags = Tags;
  21630. })(BABYLON || (BABYLON = {}));
  21631. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  21632. (function (BABYLON) {
  21633. var Internals;
  21634. (function (Internals) {
  21635. var AndOrNotEvaluator = (function () {
  21636. function AndOrNotEvaluator() {
  21637. }
  21638. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  21639. if (!query.match(/\([^\(\)]*\)/g)) {
  21640. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  21641. }
  21642. else {
  21643. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  21644. // remove parenthesis
  21645. r = r.slice(1, r.length - 1);
  21646. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  21647. });
  21648. }
  21649. if (query === "true") {
  21650. return true;
  21651. }
  21652. if (query === "false") {
  21653. return false;
  21654. }
  21655. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  21656. };
  21657. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  21658. evaluateCallback = evaluateCallback || (function (r) {
  21659. return r === "true" ? true : false;
  21660. });
  21661. var result;
  21662. var or = parenthesisContent.split("||");
  21663. for (var i in or) {
  21664. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  21665. var and = ori.split("&&");
  21666. if (and.length > 1) {
  21667. for (var j = 0; j < and.length; ++j) {
  21668. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  21669. if (andj !== "true" && andj !== "false") {
  21670. if (andj[0] === "!") {
  21671. result = !evaluateCallback(andj.substring(1));
  21672. }
  21673. else {
  21674. result = evaluateCallback(andj);
  21675. }
  21676. }
  21677. else {
  21678. result = andj === "true" ? true : false;
  21679. }
  21680. if (!result) {
  21681. ori = "false";
  21682. break;
  21683. }
  21684. }
  21685. }
  21686. if (result || ori === "true") {
  21687. result = true;
  21688. break;
  21689. }
  21690. // result equals false (or undefined)
  21691. if (ori !== "true" && ori !== "false") {
  21692. if (ori[0] === "!") {
  21693. result = !evaluateCallback(ori.substring(1));
  21694. }
  21695. else {
  21696. result = evaluateCallback(ori);
  21697. }
  21698. }
  21699. else {
  21700. result = ori === "true" ? true : false;
  21701. }
  21702. }
  21703. // the whole parenthesis scope is replaced by 'true' or 'false'
  21704. return result ? "true" : "false";
  21705. };
  21706. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  21707. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  21708. // remove whitespaces
  21709. r = r.replace(/[\s]/g, function () { return ""; });
  21710. return r.length % 2 ? "!" : "";
  21711. });
  21712. booleanString = booleanString.trim();
  21713. if (booleanString === "!true") {
  21714. booleanString = "false";
  21715. }
  21716. else if (booleanString === "!false") {
  21717. booleanString = "true";
  21718. }
  21719. return booleanString;
  21720. };
  21721. return AndOrNotEvaluator;
  21722. })();
  21723. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  21724. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21725. })(BABYLON || (BABYLON = {}));
  21726. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  21727. (function (BABYLON) {
  21728. var PostProcessRenderPass = (function () {
  21729. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  21730. this._enabled = true;
  21731. this._refCount = 0;
  21732. this._name = name;
  21733. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  21734. this.setRenderList(renderList);
  21735. this._renderTexture.onBeforeRender = beforeRender;
  21736. this._renderTexture.onAfterRender = afterRender;
  21737. this._scene = scene;
  21738. this._renderList = renderList;
  21739. }
  21740. // private
  21741. PostProcessRenderPass.prototype._incRefCount = function () {
  21742. if (this._refCount === 0) {
  21743. this._scene.customRenderTargets.push(this._renderTexture);
  21744. }
  21745. return ++this._refCount;
  21746. };
  21747. PostProcessRenderPass.prototype._decRefCount = function () {
  21748. this._refCount--;
  21749. if (this._refCount <= 0) {
  21750. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  21751. }
  21752. return this._refCount;
  21753. };
  21754. PostProcessRenderPass.prototype._update = function () {
  21755. this.setRenderList(this._renderList);
  21756. };
  21757. // public
  21758. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  21759. this._renderTexture.renderList = renderList;
  21760. };
  21761. PostProcessRenderPass.prototype.getRenderTexture = function () {
  21762. return this._renderTexture;
  21763. };
  21764. return PostProcessRenderPass;
  21765. })();
  21766. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  21767. })(BABYLON || (BABYLON = {}));
  21768. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  21769. (function (BABYLON) {
  21770. var PostProcessRenderEffect = (function () {
  21771. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  21772. this._engine = engine;
  21773. this._name = name;
  21774. this._singleInstance = singleInstance || true;
  21775. this._getPostProcess = getPostProcess;
  21776. this._cameras = [];
  21777. this._indicesForCamera = [];
  21778. this._postProcesses = {};
  21779. this._renderPasses = {};
  21780. this._renderEffectAsPasses = {};
  21781. }
  21782. PostProcessRenderEffect.prototype._update = function () {
  21783. for (var renderPassName in this._renderPasses) {
  21784. this._renderPasses[renderPassName]._update();
  21785. }
  21786. };
  21787. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  21788. this._renderPasses[renderPass._name] = renderPass;
  21789. this._linkParameters();
  21790. };
  21791. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  21792. delete this._renderPasses[renderPass._name];
  21793. this._linkParameters();
  21794. };
  21795. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  21796. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  21797. this._linkParameters();
  21798. };
  21799. PostProcessRenderEffect.prototype.getPass = function (passName) {
  21800. for (var renderPassName in this._renderPasses) {
  21801. if (renderPassName === passName) {
  21802. return this._renderPasses[passName];
  21803. }
  21804. }
  21805. };
  21806. PostProcessRenderEffect.prototype.emptyPasses = function () {
  21807. this._renderPasses = {};
  21808. this._linkParameters();
  21809. };
  21810. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  21811. var cameraKey;
  21812. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21813. for (var i = 0; i < _cam.length; i++) {
  21814. var camera = _cam[i];
  21815. var cameraName = camera.name;
  21816. if (this._singleInstance) {
  21817. cameraKey = 0;
  21818. }
  21819. else {
  21820. cameraKey = cameraName;
  21821. }
  21822. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  21823. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  21824. if (!this._indicesForCamera[cameraName]) {
  21825. this._indicesForCamera[cameraName] = [];
  21826. }
  21827. this._indicesForCamera[cameraName].push(index);
  21828. if (this._cameras.indexOf(camera) === -1) {
  21829. this._cameras[cameraName] = camera;
  21830. }
  21831. for (var passName in this._renderPasses) {
  21832. this._renderPasses[passName]._incRefCount();
  21833. }
  21834. }
  21835. this._linkParameters();
  21836. };
  21837. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  21838. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21839. for (var i = 0; i < _cam.length; i++) {
  21840. var camera = _cam[i];
  21841. var cameraName = camera.name;
  21842. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21843. var index = this._cameras.indexOf(cameraName);
  21844. this._indicesForCamera.splice(index, 1);
  21845. this._cameras.splice(index, 1);
  21846. for (var passName in this._renderPasses) {
  21847. this._renderPasses[passName]._decRefCount();
  21848. }
  21849. }
  21850. };
  21851. PostProcessRenderEffect.prototype._enable = function (cameras) {
  21852. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21853. for (var i = 0; i < _cam.length; i++) {
  21854. var camera = _cam[i];
  21855. var cameraName = camera.name;
  21856. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  21857. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  21858. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  21859. }
  21860. }
  21861. for (var passName in this._renderPasses) {
  21862. this._renderPasses[passName]._incRefCount();
  21863. }
  21864. }
  21865. };
  21866. PostProcessRenderEffect.prototype._disable = function (cameras) {
  21867. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21868. for (var i = 0; i < _cam.length; i++) {
  21869. var camera = _cam[i];
  21870. var cameraName = camera.Name;
  21871. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21872. for (var passName in this._renderPasses) {
  21873. this._renderPasses[passName]._decRefCount();
  21874. }
  21875. }
  21876. };
  21877. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  21878. if (this._singleInstance) {
  21879. return this._postProcesses[0];
  21880. }
  21881. else {
  21882. return this._postProcesses[camera.name];
  21883. }
  21884. };
  21885. PostProcessRenderEffect.prototype._linkParameters = function () {
  21886. var _this = this;
  21887. for (var index in this._postProcesses) {
  21888. if (this.applyParameters) {
  21889. this.applyParameters(this._postProcesses[index]);
  21890. }
  21891. this._postProcesses[index].onBeforeRender = function (effect) {
  21892. _this._linkTextures(effect);
  21893. };
  21894. }
  21895. };
  21896. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  21897. for (var renderPassName in this._renderPasses) {
  21898. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  21899. }
  21900. for (var renderEffectName in this._renderEffectAsPasses) {
  21901. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  21902. }
  21903. };
  21904. return PostProcessRenderEffect;
  21905. })();
  21906. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  21907. })(BABYLON || (BABYLON = {}));
  21908. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  21909. (function (BABYLON) {
  21910. var PostProcessRenderPipeline = (function () {
  21911. function PostProcessRenderPipeline(engine, name) {
  21912. this._engine = engine;
  21913. this._name = name;
  21914. this._renderEffects = {};
  21915. this._renderEffectsForIsolatedPass = {};
  21916. this._cameras = [];
  21917. }
  21918. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  21919. this._renderEffects[renderEffect._name] = renderEffect;
  21920. };
  21921. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  21922. var renderEffects = this._renderEffects[renderEffectName];
  21923. if (!renderEffects) {
  21924. return;
  21925. }
  21926. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21927. };
  21928. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  21929. var renderEffects = this._renderEffects[renderEffectName];
  21930. if (!renderEffects) {
  21931. return;
  21932. }
  21933. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21934. };
  21935. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  21936. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21937. var indicesToDelete = [];
  21938. for (var i = 0; i < _cam.length; i++) {
  21939. var camera = _cam[i];
  21940. var cameraName = camera.name;
  21941. if (this._cameras.indexOf(camera) === -1) {
  21942. this._cameras[cameraName] = camera;
  21943. }
  21944. else if (unique) {
  21945. indicesToDelete.push(i);
  21946. }
  21947. }
  21948. for (var i = 0; i < indicesToDelete.length; i++) {
  21949. cameras.splice(indicesToDelete[i], 1);
  21950. }
  21951. for (var renderEffectName in this._renderEffects) {
  21952. this._renderEffects[renderEffectName]._attachCameras(_cam);
  21953. }
  21954. };
  21955. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  21956. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21957. for (var renderEffectName in this._renderEffects) {
  21958. this._renderEffects[renderEffectName]._detachCameras(_cam);
  21959. }
  21960. for (var i = 0; i < _cam.length; i++) {
  21961. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  21962. }
  21963. };
  21964. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  21965. var _this = this;
  21966. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21967. var pass = null;
  21968. for (var renderEffectName in this._renderEffects) {
  21969. pass = this._renderEffects[renderEffectName].getPass(passName);
  21970. if (pass != null) {
  21971. break;
  21972. }
  21973. }
  21974. if (pass === null) {
  21975. return;
  21976. }
  21977. for (var renderEffectName in this._renderEffects) {
  21978. this._renderEffects[renderEffectName]._disable(_cam);
  21979. }
  21980. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  21981. for (var i = 0; i < _cam.length; i++) {
  21982. var camera = _cam[i];
  21983. var cameraName = camera.name;
  21984. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21985. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21986. });
  21987. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  21988. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  21989. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  21990. }
  21991. };
  21992. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  21993. var _this = this;
  21994. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21995. for (var i = 0; i < _cam.length; i++) {
  21996. var camera = _cam[i];
  21997. var cameraName = camera.name;
  21998. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21999. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22000. });
  22001. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  22002. }
  22003. for (var renderEffectName in this._renderEffects) {
  22004. this._renderEffects[renderEffectName]._enable(_cam);
  22005. }
  22006. };
  22007. PostProcessRenderPipeline.prototype._update = function () {
  22008. for (var renderEffectName in this._renderEffects) {
  22009. this._renderEffects[renderEffectName]._update();
  22010. }
  22011. for (var i = 0; i < this._cameras.length; i++) {
  22012. var cameraName = this._cameras[i].name;
  22013. if (this._renderEffectsForIsolatedPass[cameraName]) {
  22014. this._renderEffectsForIsolatedPass[cameraName]._update();
  22015. }
  22016. }
  22017. };
  22018. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  22019. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  22020. return PostProcessRenderPipeline;
  22021. })();
  22022. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  22023. })(BABYLON || (BABYLON = {}));
  22024. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  22025. (function (BABYLON) {
  22026. var PostProcessRenderPipelineManager = (function () {
  22027. function PostProcessRenderPipelineManager() {
  22028. this._renderPipelines = {};
  22029. }
  22030. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  22031. this._renderPipelines[renderPipeline._name] = renderPipeline;
  22032. };
  22033. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  22034. var renderPipeline = this._renderPipelines[renderPipelineName];
  22035. if (!renderPipeline) {
  22036. return;
  22037. }
  22038. renderPipeline._attachCameras(cameras, unique);
  22039. };
  22040. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  22041. var renderPipeline = this._renderPipelines[renderPipelineName];
  22042. if (!renderPipeline) {
  22043. return;
  22044. }
  22045. renderPipeline._detachCameras(cameras);
  22046. };
  22047. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22048. var renderPipeline = this._renderPipelines[renderPipelineName];
  22049. if (!renderPipeline) {
  22050. return;
  22051. }
  22052. renderPipeline._enableEffect(renderEffectName, cameras);
  22053. };
  22054. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22055. var renderPipeline = this._renderPipelines[renderPipelineName];
  22056. if (!renderPipeline) {
  22057. return;
  22058. }
  22059. renderPipeline._disableEffect(renderEffectName, cameras);
  22060. };
  22061. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  22062. var renderPipeline = this._renderPipelines[renderPipelineName];
  22063. if (!renderPipeline) {
  22064. return;
  22065. }
  22066. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  22067. };
  22068. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  22069. var renderPipeline = this._renderPipelines[renderPipelineName];
  22070. if (!renderPipeline) {
  22071. return;
  22072. }
  22073. renderPipeline._disableDisplayOnlyPass(cameras);
  22074. };
  22075. PostProcessRenderPipelineManager.prototype.update = function () {
  22076. for (var renderPipelineName in this._renderPipelines) {
  22077. this._renderPipelines[renderPipelineName]._update();
  22078. }
  22079. };
  22080. return PostProcessRenderPipelineManager;
  22081. })();
  22082. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  22083. })(BABYLON || (BABYLON = {}));
  22084. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  22085. var BABYLON;
  22086. (function (BABYLON) {
  22087. var DisplayPassPostProcess = (function (_super) {
  22088. __extends(DisplayPassPostProcess, _super);
  22089. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22090. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  22091. }
  22092. return DisplayPassPostProcess;
  22093. })(BABYLON.PostProcess);
  22094. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  22095. })(BABYLON || (BABYLON = {}));
  22096. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  22097. (function (BABYLON) {
  22098. var BoundingBoxRenderer = (function () {
  22099. function BoundingBoxRenderer(scene) {
  22100. this.frontColor = new BABYLON.Color3(1, 1, 1);
  22101. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  22102. this.showBackLines = true;
  22103. this.renderList = new BABYLON.SmartArray(32);
  22104. this._scene = scene;
  22105. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  22106. attributes: ["position"],
  22107. uniforms: ["worldViewProjection", "color"]
  22108. });
  22109. var engine = this._scene.getEngine();
  22110. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  22111. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  22112. 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]);
  22113. }
  22114. BoundingBoxRenderer.prototype.reset = function () {
  22115. this.renderList.reset();
  22116. };
  22117. BoundingBoxRenderer.prototype.render = function () {
  22118. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  22119. return;
  22120. }
  22121. var engine = this._scene.getEngine();
  22122. engine.setDepthWrite(false);
  22123. this._colorShader._preBind();
  22124. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  22125. var boundingBox = this.renderList.data[boundingBoxIndex];
  22126. var min = boundingBox.minimum;
  22127. var max = boundingBox.maximum;
  22128. var diff = max.subtract(min);
  22129. var median = min.add(diff.scale(0.5));
  22130. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  22131. // VBOs
  22132. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  22133. if (this.showBackLines) {
  22134. // Back
  22135. engine.setDepthFunctionToGreaterOrEqual();
  22136. this._scene.resetCachedMaterial();
  22137. this._colorShader.setColor4("color", this.backColor.toColor4());
  22138. this._colorShader.bind(worldMatrix);
  22139. // Draw order
  22140. engine.draw(false, 0, 24);
  22141. }
  22142. // Front
  22143. engine.setDepthFunctionToLess();
  22144. this._scene.resetCachedMaterial();
  22145. this._colorShader.setColor4("color", this.frontColor.toColor4());
  22146. this._colorShader.bind(worldMatrix);
  22147. // Draw order
  22148. engine.draw(false, 0, 24);
  22149. }
  22150. this._colorShader.unbind();
  22151. engine.setDepthFunctionToLessOrEqual();
  22152. engine.setDepthWrite(true);
  22153. };
  22154. BoundingBoxRenderer.prototype.dispose = function () {
  22155. this._colorShader.dispose();
  22156. this._vb.dispose();
  22157. this._scene.getEngine()._releaseBuffer(this._ib);
  22158. };
  22159. return BoundingBoxRenderer;
  22160. })();
  22161. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  22162. })(BABYLON || (BABYLON = {}));
  22163. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  22164. (function (BABYLON) {
  22165. var Internals;
  22166. (function (Internals) {
  22167. /*
  22168. * Based on jsTGALoader - Javascript loader for TGA file
  22169. * By Vincent Thibault
  22170. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  22171. */
  22172. var TGATools = (function () {
  22173. function TGATools() {
  22174. }
  22175. TGATools.GetTGAHeader = function (data) {
  22176. var offset = 0;
  22177. var header = {
  22178. id_length: data[offset++],
  22179. colormap_type: data[offset++],
  22180. image_type: data[offset++],
  22181. colormap_index: data[offset++] | data[offset++] << 8,
  22182. colormap_length: data[offset++] | data[offset++] << 8,
  22183. colormap_size: data[offset++],
  22184. origin: [
  22185. data[offset++] | data[offset++] << 8,
  22186. data[offset++] | data[offset++] << 8
  22187. ],
  22188. width: data[offset++] | data[offset++] << 8,
  22189. height: data[offset++] | data[offset++] << 8,
  22190. pixel_size: data[offset++],
  22191. flags: data[offset++]
  22192. };
  22193. return header;
  22194. };
  22195. TGATools.UploadContent = function (gl, data) {
  22196. // Not enough data to contain header ?
  22197. if (data.length < 19) {
  22198. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  22199. return;
  22200. }
  22201. // Read Header
  22202. var offset = 18;
  22203. var header = TGATools.GetTGAHeader(data);
  22204. // Assume it's a valid Targa file.
  22205. if (header.id_length + offset > data.length) {
  22206. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  22207. return;
  22208. }
  22209. // Skip not needed data
  22210. offset += header.id_length;
  22211. var use_rle = false;
  22212. var use_pal = false;
  22213. var use_rgb = false;
  22214. var use_grey = false;
  22215. switch (header.image_type) {
  22216. case TGATools._TYPE_RLE_INDEXED:
  22217. use_rle = true;
  22218. case TGATools._TYPE_INDEXED:
  22219. use_pal = true;
  22220. break;
  22221. case TGATools._TYPE_RLE_RGB:
  22222. use_rle = true;
  22223. case TGATools._TYPE_RGB:
  22224. use_rgb = true;
  22225. break;
  22226. case TGATools._TYPE_RLE_GREY:
  22227. use_rle = true;
  22228. case TGATools._TYPE_GREY:
  22229. use_grey = true;
  22230. break;
  22231. }
  22232. var pixel_data;
  22233. var numAlphaBits = header.flags & 0xf;
  22234. var pixel_size = header.pixel_size >> 3;
  22235. var pixel_total = header.width * header.height * pixel_size;
  22236. // Read palettes
  22237. var palettes;
  22238. if (use_pal) {
  22239. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  22240. }
  22241. // Read LRE
  22242. if (use_rle) {
  22243. pixel_data = new Uint8Array(pixel_total);
  22244. var c, count, i;
  22245. var localOffset = 0;
  22246. var pixels = new Uint8Array(pixel_size);
  22247. while (offset < pixel_total && localOffset < pixel_total) {
  22248. c = data[offset++];
  22249. count = (c & 0x7f) + 1;
  22250. // RLE pixels
  22251. if (c & 0x80) {
  22252. for (i = 0; i < pixel_size; ++i) {
  22253. pixels[i] = data[offset++];
  22254. }
  22255. for (i = 0; i < count; ++i) {
  22256. pixel_data.set(pixels, localOffset + i * pixel_size);
  22257. }
  22258. localOffset += pixel_size * count;
  22259. }
  22260. else {
  22261. count *= pixel_size;
  22262. for (i = 0; i < count; ++i) {
  22263. pixel_data[localOffset + i] = data[offset++];
  22264. }
  22265. localOffset += count;
  22266. }
  22267. }
  22268. }
  22269. else {
  22270. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  22271. }
  22272. // Load to texture
  22273. var x_start, y_start, x_step, y_step, y_end, x_end;
  22274. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  22275. default:
  22276. case TGATools._ORIGIN_UL:
  22277. x_start = 0;
  22278. x_step = 1;
  22279. x_end = header.width;
  22280. y_start = 0;
  22281. y_step = 1;
  22282. y_end = header.height;
  22283. break;
  22284. case TGATools._ORIGIN_BL:
  22285. x_start = 0;
  22286. x_step = 1;
  22287. x_end = header.width;
  22288. y_start = header.height - 1;
  22289. y_step = -1;
  22290. y_end = -1;
  22291. break;
  22292. case TGATools._ORIGIN_UR:
  22293. x_start = header.width - 1;
  22294. x_step = -1;
  22295. x_end = -1;
  22296. y_start = 0;
  22297. y_step = 1;
  22298. y_end = header.height;
  22299. break;
  22300. case TGATools._ORIGIN_BR:
  22301. x_start = header.width - 1;
  22302. x_step = -1;
  22303. x_end = -1;
  22304. y_start = header.height - 1;
  22305. y_step = -1;
  22306. y_end = -1;
  22307. break;
  22308. }
  22309. // Load the specify method
  22310. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  22311. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  22312. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  22313. };
  22314. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22315. var image = pixel_data, colormap = palettes;
  22316. var width = header.width, height = header.height;
  22317. var color, i = 0, x, y;
  22318. var imageData = new Uint8Array(width * height * 4);
  22319. for (y = y_start; y !== y_end; y += y_step) {
  22320. for (x = x_start; x !== x_end; x += x_step, i++) {
  22321. color = image[i];
  22322. imageData[(x + width * y) * 4 + 3] = 255;
  22323. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  22324. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  22325. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  22326. }
  22327. }
  22328. return imageData;
  22329. };
  22330. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22331. var image = pixel_data;
  22332. var width = header.width, height = header.height;
  22333. var color, i = 0, x, y;
  22334. var imageData = new Uint8Array(width * height * 4);
  22335. for (y = y_start; y !== y_end; y += y_step) {
  22336. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22337. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  22338. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  22339. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  22340. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  22341. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  22342. }
  22343. }
  22344. return imageData;
  22345. };
  22346. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22347. var image = pixel_data;
  22348. var width = header.width, height = header.height;
  22349. var i = 0, x, y;
  22350. var imageData = new Uint8Array(width * height * 4);
  22351. for (y = y_start; y !== y_end; y += y_step) {
  22352. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  22353. imageData[(x + width * y) * 4 + 3] = 255;
  22354. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22355. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22356. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22357. }
  22358. }
  22359. return imageData;
  22360. };
  22361. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22362. var image = pixel_data;
  22363. var width = header.width, height = header.height;
  22364. var i = 0, x, y;
  22365. var imageData = new Uint8Array(width * height * 4);
  22366. for (y = y_start; y !== y_end; y += y_step) {
  22367. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  22368. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22369. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22370. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22371. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  22372. }
  22373. }
  22374. return imageData;
  22375. };
  22376. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22377. var image = pixel_data;
  22378. var width = header.width, height = header.height;
  22379. var color, i = 0, x, y;
  22380. var imageData = new Uint8Array(width * height * 4);
  22381. for (y = y_start; y !== y_end; y += y_step) {
  22382. for (x = x_start; x !== x_end; x += x_step, i++) {
  22383. color = image[i];
  22384. imageData[(x + width * y) * 4 + 0] = color;
  22385. imageData[(x + width * y) * 4 + 1] = color;
  22386. imageData[(x + width * y) * 4 + 2] = color;
  22387. imageData[(x + width * y) * 4 + 3] = 255;
  22388. }
  22389. }
  22390. return imageData;
  22391. };
  22392. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22393. var image = pixel_data;
  22394. var width = header.width, height = header.height;
  22395. var i = 0, x, y;
  22396. var imageData = new Uint8Array(width * height * 4);
  22397. for (y = y_start; y !== y_end; y += y_step) {
  22398. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22399. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  22400. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  22401. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22402. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  22403. }
  22404. }
  22405. return imageData;
  22406. };
  22407. TGATools._TYPE_NO_DATA = 0;
  22408. TGATools._TYPE_INDEXED = 1;
  22409. TGATools._TYPE_RGB = 2;
  22410. TGATools._TYPE_GREY = 3;
  22411. TGATools._TYPE_RLE_INDEXED = 9;
  22412. TGATools._TYPE_RLE_RGB = 10;
  22413. TGATools._TYPE_RLE_GREY = 11;
  22414. TGATools._ORIGIN_MASK = 0x30;
  22415. TGATools._ORIGIN_SHIFT = 0x04;
  22416. TGATools._ORIGIN_BL = 0x00;
  22417. TGATools._ORIGIN_BR = 0x01;
  22418. TGATools._ORIGIN_UL = 0x02;
  22419. TGATools._ORIGIN_UR = 0x03;
  22420. return TGATools;
  22421. })();
  22422. Internals.TGATools = TGATools;
  22423. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22424. })(BABYLON || (BABYLON = {}));
  22425. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  22426. (function (BABYLON) {
  22427. var Internals;
  22428. (function (Internals) {
  22429. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  22430. // All values and structures referenced from:
  22431. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  22432. var DDS_MAGIC = 0x20534444;
  22433. 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;
  22434. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  22435. 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;
  22436. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  22437. function FourCCToInt32(value) {
  22438. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  22439. }
  22440. function Int32ToFourCC(value) {
  22441. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  22442. }
  22443. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  22444. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  22445. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  22446. var headerLengthInt = 31; // The header length in 32 bit ints
  22447. // Offsets into the header array
  22448. var off_magic = 0;
  22449. var off_size = 1;
  22450. var off_flags = 2;
  22451. var off_height = 3;
  22452. var off_width = 4;
  22453. var off_mipmapCount = 7;
  22454. var off_pfFlags = 20;
  22455. var off_pfFourCC = 21;
  22456. var off_RGBbpp = 22;
  22457. var off_RMask = 23;
  22458. var off_GMask = 24;
  22459. var off_BMask = 25;
  22460. var off_AMask = 26;
  22461. var off_caps1 = 27;
  22462. var off_caps2 = 28;
  22463. ;
  22464. var DDSTools = (function () {
  22465. function DDSTools() {
  22466. }
  22467. DDSTools.GetDDSInfo = function (arrayBuffer) {
  22468. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  22469. var mipmapCount = 1;
  22470. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  22471. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22472. }
  22473. return {
  22474. width: header[off_width],
  22475. height: header[off_height],
  22476. mipmapCount: mipmapCount,
  22477. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  22478. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  22479. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  22480. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  22481. };
  22482. };
  22483. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22484. var byteArray = new Uint8Array(dataLength);
  22485. var srcData = new Uint8Array(arrayBuffer);
  22486. var index = 0;
  22487. for (var y = height - 1; y >= 0; y--) {
  22488. for (var x = 0; x < width; x++) {
  22489. var srcPos = dataOffset + (x + y * width) * 4;
  22490. byteArray[index + 2] = srcData[srcPos];
  22491. byteArray[index + 1] = srcData[srcPos + 1];
  22492. byteArray[index] = srcData[srcPos + 2];
  22493. byteArray[index + 3] = srcData[srcPos + 3];
  22494. index += 4;
  22495. }
  22496. }
  22497. return byteArray;
  22498. };
  22499. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22500. var byteArray = new Uint8Array(dataLength);
  22501. var srcData = new Uint8Array(arrayBuffer);
  22502. var index = 0;
  22503. for (var y = height - 1; y >= 0; y--) {
  22504. for (var x = 0; x < width; x++) {
  22505. var srcPos = dataOffset + (x + y * width) * 3;
  22506. byteArray[index + 2] = srcData[srcPos];
  22507. byteArray[index + 1] = srcData[srcPos + 1];
  22508. byteArray[index] = srcData[srcPos + 2];
  22509. index += 3;
  22510. }
  22511. }
  22512. return byteArray;
  22513. };
  22514. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22515. var byteArray = new Uint8Array(dataLength);
  22516. var srcData = new Uint8Array(arrayBuffer);
  22517. var index = 0;
  22518. for (var y = height - 1; y >= 0; y--) {
  22519. for (var x = 0; x < width; x++) {
  22520. var srcPos = dataOffset + (x + y * width);
  22521. byteArray[index] = srcData[srcPos];
  22522. index++;
  22523. }
  22524. }
  22525. return byteArray;
  22526. };
  22527. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  22528. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  22529. if (header[off_magic] != DDS_MAGIC) {
  22530. BABYLON.Tools.Error("Invalid magic number in DDS header");
  22531. return;
  22532. }
  22533. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  22534. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  22535. return;
  22536. }
  22537. if (info.isFourCC) {
  22538. fourCC = header[off_pfFourCC];
  22539. switch (fourCC) {
  22540. case FOURCC_DXT1:
  22541. blockBytes = 8;
  22542. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  22543. break;
  22544. case FOURCC_DXT3:
  22545. blockBytes = 16;
  22546. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  22547. break;
  22548. case FOURCC_DXT5:
  22549. blockBytes = 16;
  22550. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  22551. break;
  22552. default:
  22553. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  22554. return;
  22555. }
  22556. }
  22557. mipmapCount = 1;
  22558. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  22559. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22560. }
  22561. var bpp = header[off_RGBbpp];
  22562. for (var face = 0; face < faces; face++) {
  22563. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  22564. width = header[off_width];
  22565. height = header[off_height];
  22566. dataOffset = header[off_size] + 4;
  22567. for (i = 0; i < mipmapCount; ++i) {
  22568. if (info.isRGB) {
  22569. if (bpp == 24) {
  22570. dataLength = width * height * 3;
  22571. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22572. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  22573. }
  22574. else {
  22575. dataLength = width * height * 4;
  22576. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22577. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  22578. }
  22579. }
  22580. else if (info.isLuminance) {
  22581. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  22582. var unpaddedRowSize = width;
  22583. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  22584. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  22585. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22586. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  22587. }
  22588. else {
  22589. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  22590. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  22591. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  22592. }
  22593. dataOffset += dataLength;
  22594. width *= 0.5;
  22595. height *= 0.5;
  22596. width = Math.max(1.0, width);
  22597. height = Math.max(1.0, height);
  22598. }
  22599. }
  22600. };
  22601. return DDSTools;
  22602. })();
  22603. Internals.DDSTools = DDSTools;
  22604. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22605. })(BABYLON || (BABYLON = {}));
  22606. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  22607. (function (BABYLON) {
  22608. var SmartArray = (function () {
  22609. function SmartArray(capacity) {
  22610. this.length = 0;
  22611. this._duplicateId = 0;
  22612. this.data = new Array(capacity);
  22613. this._id = SmartArray._GlobalId++;
  22614. }
  22615. SmartArray.prototype.push = function (value) {
  22616. this.data[this.length++] = value;
  22617. if (this.length > this.data.length) {
  22618. this.data.length *= 2;
  22619. }
  22620. if (!value.__smartArrayFlags) {
  22621. value.__smartArrayFlags = {};
  22622. }
  22623. value.__smartArrayFlags[this._id] = this._duplicateId;
  22624. };
  22625. SmartArray.prototype.pushNoDuplicate = function (value) {
  22626. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  22627. return;
  22628. }
  22629. this.push(value);
  22630. };
  22631. SmartArray.prototype.sort = function (compareFn) {
  22632. this.data.sort(compareFn);
  22633. };
  22634. SmartArray.prototype.reset = function () {
  22635. this.length = 0;
  22636. this._duplicateId++;
  22637. };
  22638. SmartArray.prototype.concat = function (array) {
  22639. if (array.length === 0) {
  22640. return;
  22641. }
  22642. if (this.length + array.length > this.data.length) {
  22643. this.data.length = (this.length + array.length) * 2;
  22644. }
  22645. for (var index = 0; index < array.length; index++) {
  22646. this.data[this.length++] = (array.data || array)[index];
  22647. }
  22648. };
  22649. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  22650. if (array.length === 0) {
  22651. return;
  22652. }
  22653. if (this.length + array.length > this.data.length) {
  22654. this.data.length = (this.length + array.length) * 2;
  22655. }
  22656. for (var index = 0; index < array.length; index++) {
  22657. var item = (array.data || array)[index];
  22658. this.pushNoDuplicate(item);
  22659. }
  22660. };
  22661. SmartArray.prototype.indexOf = function (value) {
  22662. var position = this.data.indexOf(value);
  22663. if (position >= this.length) {
  22664. return -1;
  22665. }
  22666. return position;
  22667. };
  22668. // Statics
  22669. SmartArray._GlobalId = 0;
  22670. return SmartArray;
  22671. })();
  22672. BABYLON.SmartArray = SmartArray;
  22673. })(BABYLON || (BABYLON = {}));
  22674. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  22675. (function (BABYLON) {
  22676. var CannonJSPlugin = (function () {
  22677. function CannonJSPlugin() {
  22678. this._registeredMeshes = [];
  22679. this._physicsMaterials = [];
  22680. this.updateBodyPosition = function (mesh) {
  22681. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22682. var registeredMesh = this._registeredMeshes[index];
  22683. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22684. var body = registeredMesh.body;
  22685. var center = mesh.getBoundingInfo().boundingBox.center;
  22686. body.position.set(center.x, center.z, center.y);
  22687. body.quaternion.x = mesh.rotationQuaternion.x;
  22688. body.quaternion.z = mesh.rotationQuaternion.y;
  22689. body.quaternion.y = mesh.rotationQuaternion.z;
  22690. body.quaternion.w = -mesh.rotationQuaternion.w;
  22691. return;
  22692. }
  22693. }
  22694. };
  22695. }
  22696. CannonJSPlugin.prototype.initialize = function (iterations) {
  22697. if (iterations === void 0) { iterations = 10; }
  22698. this._world = new CANNON.World();
  22699. this._world.broadphase = new CANNON.NaiveBroadphase();
  22700. this._world.solver.iterations = iterations;
  22701. };
  22702. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  22703. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22704. };
  22705. CannonJSPlugin.prototype.runOneStep = function (delta) {
  22706. this._world.step(delta);
  22707. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22708. var registeredMesh = this._registeredMeshes[index];
  22709. if (registeredMesh.isChild) {
  22710. continue;
  22711. }
  22712. // Body position
  22713. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  22714. var deltaPos = registeredMesh.delta;
  22715. if (deltaPos) {
  22716. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  22717. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  22718. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  22719. }
  22720. else {
  22721. registeredMesh.mesh.position.x = bodyX;
  22722. registeredMesh.mesh.position.y = bodyZ;
  22723. registeredMesh.mesh.position.z = bodyY;
  22724. }
  22725. if (!registeredMesh.mesh.rotationQuaternion) {
  22726. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22727. }
  22728. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  22729. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  22730. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  22731. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  22732. }
  22733. };
  22734. CannonJSPlugin.prototype.setGravity = function (gravity) {
  22735. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  22736. };
  22737. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22738. this.unregisterMesh(mesh);
  22739. mesh.computeWorldMatrix(true);
  22740. switch (impostor) {
  22741. case BABYLON.PhysicsEngine.SphereImpostor:
  22742. var bbox = mesh.getBoundingInfo().boundingBox;
  22743. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22744. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22745. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22746. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  22747. case BABYLON.PhysicsEngine.BoxImpostor:
  22748. bbox = mesh.getBoundingInfo().boundingBox;
  22749. var min = bbox.minimumWorld;
  22750. var max = bbox.maximumWorld;
  22751. var box = max.subtract(min).scale(0.5);
  22752. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  22753. case BABYLON.PhysicsEngine.PlaneImpostor:
  22754. return this._createPlane(mesh, options);
  22755. case BABYLON.PhysicsEngine.MeshImpostor:
  22756. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22757. var rawFaces = mesh.getIndices();
  22758. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  22759. }
  22760. return null;
  22761. };
  22762. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  22763. var shape = new CANNON.Sphere(radius);
  22764. if (!options) {
  22765. return shape;
  22766. }
  22767. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22768. };
  22769. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  22770. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  22771. if (!options) {
  22772. return shape;
  22773. }
  22774. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22775. };
  22776. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  22777. var shape = new CANNON.Plane();
  22778. if (!options) {
  22779. return shape;
  22780. }
  22781. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22782. };
  22783. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  22784. var verts = [], faces = [];
  22785. mesh.computeWorldMatrix(true);
  22786. for (var i = 0; i < rawVerts.length; i += 3) {
  22787. var transformed = BABYLON.Vector3.Zero();
  22788. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  22789. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  22790. }
  22791. for (var j = 0; j < rawFaces.length; j += 3) {
  22792. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  22793. }
  22794. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  22795. if (!options) {
  22796. return shape;
  22797. }
  22798. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22799. };
  22800. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  22801. var index;
  22802. var mat;
  22803. for (index = 0; index < this._physicsMaterials.length; index++) {
  22804. mat = this._physicsMaterials[index];
  22805. if (mat.friction === friction && mat.restitution === restitution) {
  22806. return mat;
  22807. }
  22808. }
  22809. var currentMat = new CANNON.Material();
  22810. currentMat.friction = friction;
  22811. currentMat.restitution = restitution;
  22812. this._physicsMaterials.push(currentMat);
  22813. for (index = 0; index < this._physicsMaterials.length; index++) {
  22814. mat = this._physicsMaterials[index];
  22815. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  22816. contactMaterial.contactEquationStiffness = 1e10;
  22817. contactMaterial.contactEquationRegularizationTime = 10;
  22818. this._world.addContactMaterial(contactMaterial);
  22819. }
  22820. return currentMat;
  22821. };
  22822. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  22823. var initialRotation = null;
  22824. if (mesh.rotationQuaternion) {
  22825. initialRotation = mesh.rotationQuaternion.clone();
  22826. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22827. }
  22828. // The delta between the mesh position and the mesh bounding box center
  22829. var bbox = mesh.getBoundingInfo().boundingBox;
  22830. var deltaPosition = mesh.position.subtract(bbox.center);
  22831. var material = this._addMaterial(friction, restitution);
  22832. var body = new CANNON.RigidBody(mass, shape, material);
  22833. if (initialRotation) {
  22834. body.quaternion.x = initialRotation.x;
  22835. body.quaternion.z = initialRotation.y;
  22836. body.quaternion.y = initialRotation.z;
  22837. body.quaternion.w = -initialRotation.w;
  22838. }
  22839. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  22840. this._world.add(body);
  22841. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  22842. return body;
  22843. };
  22844. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22845. var compoundShape = new CANNON.Compound();
  22846. for (var index = 0; index < parts.length; index++) {
  22847. var mesh = parts[index].mesh;
  22848. var shape = this.registerMesh(mesh, parts[index].impostor);
  22849. if (index == 0) {
  22850. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  22851. }
  22852. else {
  22853. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  22854. }
  22855. }
  22856. var initialMesh = parts[0].mesh;
  22857. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  22858. body.parts = parts;
  22859. return body;
  22860. };
  22861. CannonJSPlugin.prototype._unbindBody = function (body) {
  22862. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22863. var registeredMesh = this._registeredMeshes[index];
  22864. if (registeredMesh.body === body) {
  22865. registeredMesh.body = null;
  22866. registeredMesh.delta = 0;
  22867. }
  22868. }
  22869. };
  22870. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  22871. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22872. var registeredMesh = this._registeredMeshes[index];
  22873. if (registeredMesh.mesh === mesh) {
  22874. // Remove body
  22875. if (registeredMesh.body) {
  22876. this._world.remove(registeredMesh.body);
  22877. this._unbindBody(registeredMesh.body);
  22878. }
  22879. this._registeredMeshes.splice(index, 1);
  22880. return;
  22881. }
  22882. }
  22883. };
  22884. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22885. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  22886. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  22887. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22888. var registeredMesh = this._registeredMeshes[index];
  22889. if (registeredMesh.mesh === mesh) {
  22890. registeredMesh.body.applyImpulse(impulse, worldPoint);
  22891. return;
  22892. }
  22893. }
  22894. };
  22895. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  22896. var body1 = null, body2 = null;
  22897. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22898. var registeredMesh = this._registeredMeshes[index];
  22899. if (registeredMesh.mesh === mesh1) {
  22900. body1 = registeredMesh.body;
  22901. }
  22902. else if (registeredMesh.mesh === mesh2) {
  22903. body2 = registeredMesh.body;
  22904. }
  22905. }
  22906. if (!body1 || !body2) {
  22907. return false;
  22908. }
  22909. 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));
  22910. this._world.addConstraint(constraint);
  22911. return true;
  22912. };
  22913. CannonJSPlugin.prototype.dispose = function () {
  22914. while (this._registeredMeshes.length) {
  22915. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22916. }
  22917. };
  22918. CannonJSPlugin.prototype.isSupported = function () {
  22919. return window.CANNON !== undefined;
  22920. };
  22921. return CannonJSPlugin;
  22922. })();
  22923. BABYLON.CannonJSPlugin = CannonJSPlugin;
  22924. })(BABYLON || (BABYLON = {}));
  22925. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  22926. var BABYLON;
  22927. (function (BABYLON) {
  22928. var Condition = (function () {
  22929. function Condition(actionManager) {
  22930. this._actionManager = actionManager;
  22931. }
  22932. Condition.prototype.isValid = function () {
  22933. return true;
  22934. };
  22935. Condition.prototype._getProperty = function (propertyPath) {
  22936. return this._actionManager._getProperty(propertyPath);
  22937. };
  22938. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  22939. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22940. };
  22941. return Condition;
  22942. })();
  22943. BABYLON.Condition = Condition;
  22944. var ValueCondition = (function (_super) {
  22945. __extends(ValueCondition, _super);
  22946. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  22947. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  22948. _super.call(this, actionManager);
  22949. this.propertyPath = propertyPath;
  22950. this.value = value;
  22951. this.operator = operator;
  22952. this._target = this._getEffectiveTarget(target, this.propertyPath);
  22953. this._property = this._getProperty(this.propertyPath);
  22954. }
  22955. Object.defineProperty(ValueCondition, "IsEqual", {
  22956. get: function () {
  22957. return ValueCondition._IsEqual;
  22958. },
  22959. enumerable: true,
  22960. configurable: true
  22961. });
  22962. Object.defineProperty(ValueCondition, "IsDifferent", {
  22963. get: function () {
  22964. return ValueCondition._IsDifferent;
  22965. },
  22966. enumerable: true,
  22967. configurable: true
  22968. });
  22969. Object.defineProperty(ValueCondition, "IsGreater", {
  22970. get: function () {
  22971. return ValueCondition._IsGreater;
  22972. },
  22973. enumerable: true,
  22974. configurable: true
  22975. });
  22976. Object.defineProperty(ValueCondition, "IsLesser", {
  22977. get: function () {
  22978. return ValueCondition._IsLesser;
  22979. },
  22980. enumerable: true,
  22981. configurable: true
  22982. });
  22983. // Methods
  22984. ValueCondition.prototype.isValid = function () {
  22985. switch (this.operator) {
  22986. case ValueCondition.IsGreater:
  22987. return this._target[this._property] > this.value;
  22988. case ValueCondition.IsLesser:
  22989. return this._target[this._property] < this.value;
  22990. case ValueCondition.IsEqual:
  22991. case ValueCondition.IsDifferent:
  22992. var check;
  22993. if (this.value.equals) {
  22994. check = this.value.equals(this._target[this._property]);
  22995. }
  22996. else {
  22997. check = this.value === this._target[this._property];
  22998. }
  22999. return this.operator === ValueCondition.IsEqual ? check : !check;
  23000. }
  23001. return false;
  23002. };
  23003. // Statics
  23004. ValueCondition._IsEqual = 0;
  23005. ValueCondition._IsDifferent = 1;
  23006. ValueCondition._IsGreater = 2;
  23007. ValueCondition._IsLesser = 3;
  23008. return ValueCondition;
  23009. })(Condition);
  23010. BABYLON.ValueCondition = ValueCondition;
  23011. var PredicateCondition = (function (_super) {
  23012. __extends(PredicateCondition, _super);
  23013. function PredicateCondition(actionManager, predicate) {
  23014. _super.call(this, actionManager);
  23015. this.predicate = predicate;
  23016. }
  23017. PredicateCondition.prototype.isValid = function () {
  23018. return this.predicate();
  23019. };
  23020. return PredicateCondition;
  23021. })(Condition);
  23022. BABYLON.PredicateCondition = PredicateCondition;
  23023. var StateCondition = (function (_super) {
  23024. __extends(StateCondition, _super);
  23025. function StateCondition(actionManager, target, value) {
  23026. _super.call(this, actionManager);
  23027. this.value = value;
  23028. this._target = target;
  23029. }
  23030. // Methods
  23031. StateCondition.prototype.isValid = function () {
  23032. return this._target.state === this.value;
  23033. };
  23034. return StateCondition;
  23035. })(Condition);
  23036. BABYLON.StateCondition = StateCondition;
  23037. })(BABYLON || (BABYLON = {}));
  23038. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  23039. (function (BABYLON) {
  23040. var Action = (function () {
  23041. function Action(triggerOptions, condition) {
  23042. this.triggerOptions = triggerOptions;
  23043. if (triggerOptions.parameter) {
  23044. this.trigger = triggerOptions.trigger;
  23045. this._triggerParameter = triggerOptions.parameter;
  23046. }
  23047. else {
  23048. this.trigger = triggerOptions;
  23049. }
  23050. this._nextActiveAction = this;
  23051. this._condition = condition;
  23052. }
  23053. // Methods
  23054. Action.prototype._prepare = function () {
  23055. };
  23056. Action.prototype.getTriggerParameter = function () {
  23057. return this._triggerParameter;
  23058. };
  23059. Action.prototype._executeCurrent = function (evt) {
  23060. if (this._condition) {
  23061. var currentRenderId = this._actionManager.getScene().getRenderId();
  23062. // We cache the current evaluation for the current frame
  23063. if (this._condition._evaluationId === currentRenderId) {
  23064. if (!this._condition._currentResult) {
  23065. return;
  23066. }
  23067. }
  23068. else {
  23069. this._condition._evaluationId = currentRenderId;
  23070. if (!this._condition.isValid()) {
  23071. this._condition._currentResult = false;
  23072. return;
  23073. }
  23074. this._condition._currentResult = true;
  23075. }
  23076. }
  23077. this._nextActiveAction.execute(evt);
  23078. if (this._nextActiveAction._child) {
  23079. if (!this._nextActiveAction._child._actionManager) {
  23080. this._nextActiveAction._child._actionManager = this._actionManager;
  23081. }
  23082. this._nextActiveAction = this._nextActiveAction._child;
  23083. }
  23084. else {
  23085. this._nextActiveAction = this;
  23086. }
  23087. };
  23088. Action.prototype.execute = function (evt) {
  23089. };
  23090. Action.prototype.then = function (action) {
  23091. this._child = action;
  23092. action._actionManager = this._actionManager;
  23093. action._prepare();
  23094. return action;
  23095. };
  23096. Action.prototype._getProperty = function (propertyPath) {
  23097. return this._actionManager._getProperty(propertyPath);
  23098. };
  23099. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  23100. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23101. };
  23102. return Action;
  23103. })();
  23104. BABYLON.Action = Action;
  23105. })(BABYLON || (BABYLON = {}));
  23106. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  23107. (function (BABYLON) {
  23108. /**
  23109. * ActionEvent is the event beint sent when an action is triggered.
  23110. */
  23111. var ActionEvent = (function () {
  23112. /**
  23113. * @constructor
  23114. * @param source The mesh that triggered the action.
  23115. * @param pointerX the X mouse cursor position at the time of the event
  23116. * @param pointerY the Y mouse cursor position at the time of the event
  23117. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  23118. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  23119. */
  23120. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  23121. this.source = source;
  23122. this.pointerX = pointerX;
  23123. this.pointerY = pointerY;
  23124. this.meshUnderPointer = meshUnderPointer;
  23125. this.sourceEvent = sourceEvent;
  23126. }
  23127. /**
  23128. * Helper function to auto-create an ActionEvent from a source mesh.
  23129. * @param source the source mesh that triggered the event
  23130. * @param evt {Event} The original (browser) event
  23131. */
  23132. ActionEvent.CreateNew = function (source, evt) {
  23133. var scene = source.getScene();
  23134. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23135. };
  23136. /**
  23137. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  23138. * @param scene the scene where the event occurred
  23139. * @param evt {Event} The original (browser) event
  23140. */
  23141. ActionEvent.CreateNewFromScene = function (scene, evt) {
  23142. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23143. };
  23144. return ActionEvent;
  23145. })();
  23146. BABYLON.ActionEvent = ActionEvent;
  23147. /**
  23148. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  23149. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  23150. */
  23151. var ActionManager = (function () {
  23152. function ActionManager(scene) {
  23153. // Members
  23154. this.actions = new Array();
  23155. this._scene = scene;
  23156. scene._actionManagers.push(this);
  23157. }
  23158. Object.defineProperty(ActionManager, "NothingTrigger", {
  23159. get: function () {
  23160. return ActionManager._NothingTrigger;
  23161. },
  23162. enumerable: true,
  23163. configurable: true
  23164. });
  23165. Object.defineProperty(ActionManager, "OnPickTrigger", {
  23166. get: function () {
  23167. return ActionManager._OnPickTrigger;
  23168. },
  23169. enumerable: true,
  23170. configurable: true
  23171. });
  23172. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  23173. get: function () {
  23174. return ActionManager._OnLeftPickTrigger;
  23175. },
  23176. enumerable: true,
  23177. configurable: true
  23178. });
  23179. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  23180. get: function () {
  23181. return ActionManager._OnRightPickTrigger;
  23182. },
  23183. enumerable: true,
  23184. configurable: true
  23185. });
  23186. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  23187. get: function () {
  23188. return ActionManager._OnCenterPickTrigger;
  23189. },
  23190. enumerable: true,
  23191. configurable: true
  23192. });
  23193. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  23194. get: function () {
  23195. return ActionManager._OnPointerOverTrigger;
  23196. },
  23197. enumerable: true,
  23198. configurable: true
  23199. });
  23200. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  23201. get: function () {
  23202. return ActionManager._OnPointerOutTrigger;
  23203. },
  23204. enumerable: true,
  23205. configurable: true
  23206. });
  23207. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  23208. get: function () {
  23209. return ActionManager._OnEveryFrameTrigger;
  23210. },
  23211. enumerable: true,
  23212. configurable: true
  23213. });
  23214. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  23215. get: function () {
  23216. return ActionManager._OnIntersectionEnterTrigger;
  23217. },
  23218. enumerable: true,
  23219. configurable: true
  23220. });
  23221. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  23222. get: function () {
  23223. return ActionManager._OnIntersectionExitTrigger;
  23224. },
  23225. enumerable: true,
  23226. configurable: true
  23227. });
  23228. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  23229. get: function () {
  23230. return ActionManager._OnKeyDownTrigger;
  23231. },
  23232. enumerable: true,
  23233. configurable: true
  23234. });
  23235. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  23236. get: function () {
  23237. return ActionManager._OnKeyUpTrigger;
  23238. },
  23239. enumerable: true,
  23240. configurable: true
  23241. });
  23242. // Methods
  23243. ActionManager.prototype.dispose = function () {
  23244. var index = this._scene._actionManagers.indexOf(this);
  23245. if (index > -1) {
  23246. this._scene._actionManagers.splice(index, 1);
  23247. }
  23248. };
  23249. ActionManager.prototype.getScene = function () {
  23250. return this._scene;
  23251. };
  23252. /**
  23253. * Does this action manager handles actions of any of the given triggers
  23254. * @param {number[]} triggers - the triggers to be tested
  23255. * @return {boolean} whether one (or more) of the triggers is handeled
  23256. */
  23257. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  23258. for (var index = 0; index < this.actions.length; index++) {
  23259. var action = this.actions[index];
  23260. if (triggers.indexOf(action.trigger) > -1) {
  23261. return true;
  23262. }
  23263. }
  23264. return false;
  23265. };
  23266. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  23267. /**
  23268. * Does this action manager has pointer triggers
  23269. * @return {boolean} whether or not it has pointer triggers
  23270. */
  23271. get: function () {
  23272. for (var index = 0; index < this.actions.length; index++) {
  23273. var action = this.actions[index];
  23274. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  23275. return true;
  23276. }
  23277. }
  23278. return false;
  23279. },
  23280. enumerable: true,
  23281. configurable: true
  23282. });
  23283. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  23284. /**
  23285. * Does this action manager has pick triggers
  23286. * @return {boolean} whether or not it has pick triggers
  23287. */
  23288. get: function () {
  23289. for (var index = 0; index < this.actions.length; index++) {
  23290. var action = this.actions[index];
  23291. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  23292. return true;
  23293. }
  23294. }
  23295. return false;
  23296. },
  23297. enumerable: true,
  23298. configurable: true
  23299. });
  23300. /**
  23301. * Registers an action to this action manager
  23302. * @param {BABYLON.Action} action - the action to be registered
  23303. * @return {BABYLON.Action} the action amended (prepared) after registration
  23304. */
  23305. ActionManager.prototype.registerAction = function (action) {
  23306. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  23307. if (this.getScene().actionManager !== this) {
  23308. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  23309. return null;
  23310. }
  23311. }
  23312. this.actions.push(action);
  23313. action._actionManager = this;
  23314. action._prepare();
  23315. return action;
  23316. };
  23317. /**
  23318. * Process a specific trigger
  23319. * @param {number} trigger - the trigger to process
  23320. * @param evt {BABYLON.ActionEvent} the event details to be processed
  23321. */
  23322. ActionManager.prototype.processTrigger = function (trigger, evt) {
  23323. for (var index = 0; index < this.actions.length; index++) {
  23324. var action = this.actions[index];
  23325. if (action.trigger === trigger) {
  23326. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  23327. var parameter = action.getTriggerParameter();
  23328. if (parameter) {
  23329. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  23330. var actualkey = String.fromCharCode(unicode).toLowerCase();
  23331. if (actualkey !== parameter.toLowerCase()) {
  23332. continue;
  23333. }
  23334. }
  23335. }
  23336. action._executeCurrent(evt);
  23337. }
  23338. }
  23339. };
  23340. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  23341. var properties = propertyPath.split(".");
  23342. for (var index = 0; index < properties.length - 1; index++) {
  23343. target = target[properties[index]];
  23344. }
  23345. return target;
  23346. };
  23347. ActionManager.prototype._getProperty = function (propertyPath) {
  23348. var properties = propertyPath.split(".");
  23349. return properties[properties.length - 1];
  23350. };
  23351. // Statics
  23352. ActionManager._NothingTrigger = 0;
  23353. ActionManager._OnPickTrigger = 1;
  23354. ActionManager._OnLeftPickTrigger = 2;
  23355. ActionManager._OnRightPickTrigger = 3;
  23356. ActionManager._OnCenterPickTrigger = 4;
  23357. ActionManager._OnPointerOverTrigger = 5;
  23358. ActionManager._OnPointerOutTrigger = 6;
  23359. ActionManager._OnEveryFrameTrigger = 7;
  23360. ActionManager._OnIntersectionEnterTrigger = 8;
  23361. ActionManager._OnIntersectionExitTrigger = 9;
  23362. ActionManager._OnKeyDownTrigger = 10;
  23363. ActionManager._OnKeyUpTrigger = 11;
  23364. return ActionManager;
  23365. })();
  23366. BABYLON.ActionManager = ActionManager;
  23367. })(BABYLON || (BABYLON = {}));
  23368. //# sourceMappingURL=babylon.actionManager.js.map
  23369. var BABYLON;
  23370. (function (BABYLON) {
  23371. var InterpolateValueAction = (function (_super) {
  23372. __extends(InterpolateValueAction, _super);
  23373. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  23374. if (duration === void 0) { duration = 1000; }
  23375. _super.call(this, triggerOptions, condition);
  23376. this.propertyPath = propertyPath;
  23377. this.value = value;
  23378. this.duration = duration;
  23379. this.stopOtherAnimations = stopOtherAnimations;
  23380. this._target = target;
  23381. }
  23382. InterpolateValueAction.prototype._prepare = function () {
  23383. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23384. this._property = this._getProperty(this.propertyPath);
  23385. };
  23386. InterpolateValueAction.prototype.execute = function () {
  23387. var scene = this._actionManager.getScene();
  23388. var keys = [
  23389. {
  23390. frame: 0,
  23391. value: this._target[this._property]
  23392. },
  23393. {
  23394. frame: 100,
  23395. value: this.value
  23396. }
  23397. ];
  23398. var dataType;
  23399. if (typeof this.value === "number") {
  23400. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  23401. }
  23402. else if (this.value instanceof BABYLON.Color3) {
  23403. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  23404. }
  23405. else if (this.value instanceof BABYLON.Vector3) {
  23406. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  23407. }
  23408. else if (this.value instanceof BABYLON.Matrix) {
  23409. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  23410. }
  23411. else if (this.value instanceof BABYLON.Quaternion) {
  23412. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  23413. }
  23414. else {
  23415. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  23416. return;
  23417. }
  23418. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  23419. animation.setKeys(keys);
  23420. if (this.stopOtherAnimations) {
  23421. scene.stopAnimation(this._target);
  23422. }
  23423. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  23424. };
  23425. return InterpolateValueAction;
  23426. })(BABYLON.Action);
  23427. BABYLON.InterpolateValueAction = InterpolateValueAction;
  23428. })(BABYLON || (BABYLON = {}));
  23429. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  23430. var BABYLON;
  23431. (function (BABYLON) {
  23432. var SwitchBooleanAction = (function (_super) {
  23433. __extends(SwitchBooleanAction, _super);
  23434. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  23435. _super.call(this, triggerOptions, condition);
  23436. this.propertyPath = propertyPath;
  23437. this._target = target;
  23438. }
  23439. SwitchBooleanAction.prototype._prepare = function () {
  23440. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23441. this._property = this._getProperty(this.propertyPath);
  23442. };
  23443. SwitchBooleanAction.prototype.execute = function () {
  23444. this._target[this._property] = !this._target[this._property];
  23445. };
  23446. return SwitchBooleanAction;
  23447. })(BABYLON.Action);
  23448. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  23449. var SetStateAction = (function (_super) {
  23450. __extends(SetStateAction, _super);
  23451. function SetStateAction(triggerOptions, target, value, condition) {
  23452. _super.call(this, triggerOptions, condition);
  23453. this.value = value;
  23454. this._target = target;
  23455. }
  23456. SetStateAction.prototype.execute = function () {
  23457. this._target.state = this.value;
  23458. };
  23459. return SetStateAction;
  23460. })(BABYLON.Action);
  23461. BABYLON.SetStateAction = SetStateAction;
  23462. var SetValueAction = (function (_super) {
  23463. __extends(SetValueAction, _super);
  23464. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  23465. _super.call(this, triggerOptions, condition);
  23466. this.propertyPath = propertyPath;
  23467. this.value = value;
  23468. this._target = target;
  23469. }
  23470. SetValueAction.prototype._prepare = function () {
  23471. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23472. this._property = this._getProperty(this.propertyPath);
  23473. };
  23474. SetValueAction.prototype.execute = function () {
  23475. this._target[this._property] = this.value;
  23476. };
  23477. return SetValueAction;
  23478. })(BABYLON.Action);
  23479. BABYLON.SetValueAction = SetValueAction;
  23480. var IncrementValueAction = (function (_super) {
  23481. __extends(IncrementValueAction, _super);
  23482. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  23483. _super.call(this, triggerOptions, condition);
  23484. this.propertyPath = propertyPath;
  23485. this.value = value;
  23486. this._target = target;
  23487. }
  23488. IncrementValueAction.prototype._prepare = function () {
  23489. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23490. this._property = this._getProperty(this.propertyPath);
  23491. if (typeof this._target[this._property] !== "number") {
  23492. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  23493. }
  23494. };
  23495. IncrementValueAction.prototype.execute = function () {
  23496. this._target[this._property] += this.value;
  23497. };
  23498. return IncrementValueAction;
  23499. })(BABYLON.Action);
  23500. BABYLON.IncrementValueAction = IncrementValueAction;
  23501. var PlayAnimationAction = (function (_super) {
  23502. __extends(PlayAnimationAction, _super);
  23503. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  23504. _super.call(this, triggerOptions, condition);
  23505. this.from = from;
  23506. this.to = to;
  23507. this.loop = loop;
  23508. this._target = target;
  23509. }
  23510. PlayAnimationAction.prototype._prepare = function () {
  23511. };
  23512. PlayAnimationAction.prototype.execute = function () {
  23513. var scene = this._actionManager.getScene();
  23514. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  23515. };
  23516. return PlayAnimationAction;
  23517. })(BABYLON.Action);
  23518. BABYLON.PlayAnimationAction = PlayAnimationAction;
  23519. var StopAnimationAction = (function (_super) {
  23520. __extends(StopAnimationAction, _super);
  23521. function StopAnimationAction(triggerOptions, target, condition) {
  23522. _super.call(this, triggerOptions, condition);
  23523. this._target = target;
  23524. }
  23525. StopAnimationAction.prototype._prepare = function () {
  23526. };
  23527. StopAnimationAction.prototype.execute = function () {
  23528. var scene = this._actionManager.getScene();
  23529. scene.stopAnimation(this._target);
  23530. };
  23531. return StopAnimationAction;
  23532. })(BABYLON.Action);
  23533. BABYLON.StopAnimationAction = StopAnimationAction;
  23534. var DoNothingAction = (function (_super) {
  23535. __extends(DoNothingAction, _super);
  23536. function DoNothingAction(triggerOptions, condition) {
  23537. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  23538. _super.call(this, triggerOptions, condition);
  23539. }
  23540. DoNothingAction.prototype.execute = function () {
  23541. };
  23542. return DoNothingAction;
  23543. })(BABYLON.Action);
  23544. BABYLON.DoNothingAction = DoNothingAction;
  23545. var CombineAction = (function (_super) {
  23546. __extends(CombineAction, _super);
  23547. function CombineAction(triggerOptions, children, condition) {
  23548. _super.call(this, triggerOptions, condition);
  23549. this.children = children;
  23550. }
  23551. CombineAction.prototype._prepare = function () {
  23552. for (var index = 0; index < this.children.length; index++) {
  23553. this.children[index]._actionManager = this._actionManager;
  23554. this.children[index]._prepare();
  23555. }
  23556. };
  23557. CombineAction.prototype.execute = function (evt) {
  23558. for (var index = 0; index < this.children.length; index++) {
  23559. this.children[index].execute(evt);
  23560. }
  23561. };
  23562. return CombineAction;
  23563. })(BABYLON.Action);
  23564. BABYLON.CombineAction = CombineAction;
  23565. var ExecuteCodeAction = (function (_super) {
  23566. __extends(ExecuteCodeAction, _super);
  23567. function ExecuteCodeAction(triggerOptions, func, condition) {
  23568. _super.call(this, triggerOptions, condition);
  23569. this.func = func;
  23570. }
  23571. ExecuteCodeAction.prototype.execute = function (evt) {
  23572. this.func(evt);
  23573. };
  23574. return ExecuteCodeAction;
  23575. })(BABYLON.Action);
  23576. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  23577. var SetParentAction = (function (_super) {
  23578. __extends(SetParentAction, _super);
  23579. function SetParentAction(triggerOptions, target, parent, condition) {
  23580. _super.call(this, triggerOptions, condition);
  23581. this._target = target;
  23582. this._parent = parent;
  23583. }
  23584. SetParentAction.prototype._prepare = function () {
  23585. };
  23586. SetParentAction.prototype.execute = function () {
  23587. if (this._target.parent === this._parent) {
  23588. return;
  23589. }
  23590. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  23591. invertParentWorldMatrix.invert();
  23592. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  23593. this._target.parent = this._parent;
  23594. };
  23595. return SetParentAction;
  23596. })(BABYLON.Action);
  23597. BABYLON.SetParentAction = SetParentAction;
  23598. var PlaySoundAction = (function (_super) {
  23599. __extends(PlaySoundAction, _super);
  23600. function PlaySoundAction(triggerOptions, sound, condition) {
  23601. _super.call(this, triggerOptions, condition);
  23602. this._sound = sound;
  23603. }
  23604. PlaySoundAction.prototype._prepare = function () {
  23605. };
  23606. PlaySoundAction.prototype.execute = function () {
  23607. if (this._sound !== undefined)
  23608. this._sound.play();
  23609. };
  23610. return PlaySoundAction;
  23611. })(BABYLON.Action);
  23612. BABYLON.PlaySoundAction = PlaySoundAction;
  23613. var StopSoundAction = (function (_super) {
  23614. __extends(StopSoundAction, _super);
  23615. function StopSoundAction(triggerOptions, sound, condition) {
  23616. _super.call(this, triggerOptions, condition);
  23617. this._sound = sound;
  23618. }
  23619. StopSoundAction.prototype._prepare = function () {
  23620. };
  23621. StopSoundAction.prototype.execute = function () {
  23622. if (this._sound !== undefined)
  23623. this._sound.stop();
  23624. };
  23625. return StopSoundAction;
  23626. })(BABYLON.Action);
  23627. BABYLON.StopSoundAction = StopSoundAction;
  23628. })(BABYLON || (BABYLON = {}));
  23629. //# sourceMappingURL=babylon.directActions.js.map
  23630. var BABYLON;
  23631. (function (BABYLON) {
  23632. var Geometry = (function () {
  23633. function Geometry(id, scene, vertexData, updatable, mesh) {
  23634. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23635. this._totalVertices = 0;
  23636. this._indices = [];
  23637. this.id = id;
  23638. this._engine = scene.getEngine();
  23639. this._meshes = [];
  23640. this._scene = scene;
  23641. // vertexData
  23642. if (vertexData) {
  23643. this.setAllVerticesData(vertexData, updatable);
  23644. }
  23645. else {
  23646. this._totalVertices = 0;
  23647. this._indices = [];
  23648. }
  23649. // applyToMesh
  23650. if (mesh) {
  23651. this.applyToMesh(mesh);
  23652. mesh.computeWorldMatrix(true);
  23653. }
  23654. }
  23655. Geometry.prototype.getScene = function () {
  23656. return this._scene;
  23657. };
  23658. Geometry.prototype.getEngine = function () {
  23659. return this._engine;
  23660. };
  23661. Geometry.prototype.isReady = function () {
  23662. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  23663. };
  23664. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  23665. vertexData.applyToGeometry(this, updatable);
  23666. };
  23667. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23668. this._vertexBuffers = this._vertexBuffers || {};
  23669. if (this._vertexBuffers[kind]) {
  23670. this._vertexBuffers[kind].dispose();
  23671. }
  23672. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  23673. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23674. stride = this._vertexBuffers[kind].getStrideSize();
  23675. this._totalVertices = data.length / stride;
  23676. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  23677. var meshes = this._meshes;
  23678. var numOfMeshes = meshes.length;
  23679. for (var index = 0; index < numOfMeshes; index++) {
  23680. var mesh = meshes[index];
  23681. mesh._resetPointsArrayCache();
  23682. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23683. mesh._createGlobalSubMesh();
  23684. mesh.computeWorldMatrix(true);
  23685. }
  23686. }
  23687. };
  23688. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  23689. var vertexBuffer = this.getVertexBuffer(kind);
  23690. if (!vertexBuffer) {
  23691. return;
  23692. }
  23693. vertexBuffer.updateDirectly(data, offset);
  23694. };
  23695. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  23696. var vertexBuffer = this.getVertexBuffer(kind);
  23697. if (!vertexBuffer) {
  23698. return;
  23699. }
  23700. vertexBuffer.update(data);
  23701. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23702. var extend;
  23703. var stride = vertexBuffer.getStrideSize();
  23704. this._totalVertices = data.length / stride;
  23705. if (updateExtends) {
  23706. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  23707. }
  23708. var meshes = this._meshes;
  23709. var numOfMeshes = meshes.length;
  23710. for (var index = 0; index < numOfMeshes; index++) {
  23711. var mesh = meshes[index];
  23712. mesh._resetPointsArrayCache();
  23713. if (updateExtends) {
  23714. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23715. }
  23716. }
  23717. }
  23718. };
  23719. Geometry.prototype.getTotalVertices = function () {
  23720. if (!this.isReady()) {
  23721. return 0;
  23722. }
  23723. return this._totalVertices;
  23724. };
  23725. Geometry.prototype.getVerticesData = function (kind) {
  23726. var vertexBuffer = this.getVertexBuffer(kind);
  23727. if (!vertexBuffer) {
  23728. return null;
  23729. }
  23730. return vertexBuffer.getData();
  23731. };
  23732. Geometry.prototype.getVertexBuffer = function (kind) {
  23733. if (!this.isReady()) {
  23734. return null;
  23735. }
  23736. return this._vertexBuffers[kind];
  23737. };
  23738. Geometry.prototype.getVertexBuffers = function () {
  23739. if (!this.isReady()) {
  23740. return null;
  23741. }
  23742. return this._vertexBuffers;
  23743. };
  23744. Geometry.prototype.isVerticesDataPresent = function (kind) {
  23745. if (!this._vertexBuffers) {
  23746. if (this._delayInfo) {
  23747. return this._delayInfo.indexOf(kind) !== -1;
  23748. }
  23749. return false;
  23750. }
  23751. return this._vertexBuffers[kind] !== undefined;
  23752. };
  23753. Geometry.prototype.getVerticesDataKinds = function () {
  23754. var result = [];
  23755. if (!this._vertexBuffers && this._delayInfo) {
  23756. for (var kind in this._delayInfo) {
  23757. result.push(kind);
  23758. }
  23759. }
  23760. else {
  23761. for (kind in this._vertexBuffers) {
  23762. result.push(kind);
  23763. }
  23764. }
  23765. return result;
  23766. };
  23767. Geometry.prototype.setIndices = function (indices, totalVertices) {
  23768. if (this._indexBuffer) {
  23769. this._engine._releaseBuffer(this._indexBuffer);
  23770. }
  23771. this._indices = indices;
  23772. if (this._meshes.length !== 0 && this._indices) {
  23773. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23774. }
  23775. if (totalVertices !== undefined) {
  23776. this._totalVertices = totalVertices;
  23777. }
  23778. var meshes = this._meshes;
  23779. var numOfMeshes = meshes.length;
  23780. for (var index = 0; index < numOfMeshes; index++) {
  23781. meshes[index]._createGlobalSubMesh();
  23782. }
  23783. };
  23784. Geometry.prototype.getTotalIndices = function () {
  23785. if (!this.isReady()) {
  23786. return 0;
  23787. }
  23788. return this._indices.length;
  23789. };
  23790. Geometry.prototype.getIndices = function () {
  23791. if (!this.isReady()) {
  23792. return null;
  23793. }
  23794. return this._indices;
  23795. };
  23796. Geometry.prototype.getIndexBuffer = function () {
  23797. if (!this.isReady()) {
  23798. return null;
  23799. }
  23800. return this._indexBuffer;
  23801. };
  23802. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  23803. var meshes = this._meshes;
  23804. var index = meshes.indexOf(mesh);
  23805. if (index === -1) {
  23806. return;
  23807. }
  23808. for (var kind in this._vertexBuffers) {
  23809. this._vertexBuffers[kind].dispose();
  23810. }
  23811. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  23812. this._indexBuffer = null;
  23813. }
  23814. meshes.splice(index, 1);
  23815. mesh._geometry = null;
  23816. if (meshes.length === 0 && shouldDispose) {
  23817. this.dispose();
  23818. }
  23819. };
  23820. Geometry.prototype.applyToMesh = function (mesh) {
  23821. if (mesh._geometry === this) {
  23822. return;
  23823. }
  23824. var previousGeometry = mesh._geometry;
  23825. if (previousGeometry) {
  23826. previousGeometry.releaseForMesh(mesh);
  23827. }
  23828. var meshes = this._meshes;
  23829. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  23830. mesh._geometry = this;
  23831. this._scene.pushGeometry(this);
  23832. meshes.push(mesh);
  23833. if (this.isReady()) {
  23834. this._applyToMesh(mesh);
  23835. }
  23836. else {
  23837. mesh._boundingInfo = this._boundingInfo;
  23838. }
  23839. };
  23840. Geometry.prototype._applyToMesh = function (mesh) {
  23841. var numOfMeshes = this._meshes.length;
  23842. for (var kind in this._vertexBuffers) {
  23843. if (numOfMeshes === 1) {
  23844. this._vertexBuffers[kind].create();
  23845. }
  23846. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  23847. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23848. mesh._resetPointsArrayCache();
  23849. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  23850. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23851. mesh._createGlobalSubMesh();
  23852. //bounding info was just created again, world matrix should be applied again.
  23853. mesh._updateBoundingInfo();
  23854. }
  23855. }
  23856. // indexBuffer
  23857. if (numOfMeshes === 1 && this._indices) {
  23858. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23859. }
  23860. if (this._indexBuffer) {
  23861. this._indexBuffer.references = numOfMeshes;
  23862. }
  23863. };
  23864. Geometry.prototype.load = function (scene, onLoaded) {
  23865. var _this = this;
  23866. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23867. return;
  23868. }
  23869. if (this.isReady()) {
  23870. if (onLoaded) {
  23871. onLoaded();
  23872. }
  23873. return;
  23874. }
  23875. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23876. scene._addPendingData(this);
  23877. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23878. _this._delayLoadingFunction(JSON.parse(data), _this);
  23879. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23880. _this._delayInfo = [];
  23881. scene._removePendingData(_this);
  23882. var meshes = _this._meshes;
  23883. var numOfMeshes = meshes.length;
  23884. for (var index = 0; index < numOfMeshes; index++) {
  23885. _this._applyToMesh(meshes[index]);
  23886. }
  23887. if (onLoaded) {
  23888. onLoaded();
  23889. }
  23890. }, function () {
  23891. }, scene.database);
  23892. };
  23893. Geometry.prototype.dispose = function () {
  23894. var meshes = this._meshes;
  23895. var numOfMeshes = meshes.length;
  23896. var index;
  23897. for (index = 0; index < numOfMeshes; index++) {
  23898. this.releaseForMesh(meshes[index]);
  23899. }
  23900. this._meshes = [];
  23901. for (var kind in this._vertexBuffers) {
  23902. this._vertexBuffers[kind].dispose();
  23903. }
  23904. this._vertexBuffers = [];
  23905. this._totalVertices = 0;
  23906. if (this._indexBuffer) {
  23907. this._engine._releaseBuffer(this._indexBuffer);
  23908. }
  23909. this._indexBuffer = null;
  23910. this._indices = [];
  23911. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23912. this.delayLoadingFile = null;
  23913. this._delayLoadingFunction = null;
  23914. this._delayInfo = [];
  23915. this._boundingInfo = null; // todo: .dispose()
  23916. var geometries = this._scene.getGeometries();
  23917. index = geometries.indexOf(this);
  23918. if (index > -1) {
  23919. geometries.splice(index, 1);
  23920. }
  23921. };
  23922. Geometry.prototype.copy = function (id) {
  23923. var vertexData = new BABYLON.VertexData();
  23924. vertexData.indices = [];
  23925. var indices = this.getIndices();
  23926. for (var index = 0; index < indices.length; index++) {
  23927. vertexData.indices.push(indices[index]);
  23928. }
  23929. var updatable = false;
  23930. var stopChecking = false;
  23931. for (var kind in this._vertexBuffers) {
  23932. vertexData.set(this.getVerticesData(kind), kind);
  23933. if (!stopChecking) {
  23934. updatable = this.getVertexBuffer(kind).isUpdatable();
  23935. stopChecking = !updatable;
  23936. }
  23937. }
  23938. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  23939. geometry.delayLoadState = this.delayLoadState;
  23940. geometry.delayLoadingFile = this.delayLoadingFile;
  23941. geometry._delayLoadingFunction = this._delayLoadingFunction;
  23942. for (kind in this._delayInfo) {
  23943. geometry._delayInfo = geometry._delayInfo || [];
  23944. geometry._delayInfo.push(kind);
  23945. }
  23946. // Bounding info
  23947. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  23948. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23949. return geometry;
  23950. };
  23951. // Statics
  23952. Geometry.ExtractFromMesh = function (mesh, id) {
  23953. var geometry = mesh._geometry;
  23954. if (!geometry) {
  23955. return null;
  23956. }
  23957. return geometry.copy(id);
  23958. };
  23959. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  23960. // be aware Math.random() could cause collisions
  23961. Geometry.RandomId = function () {
  23962. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  23963. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  23964. return v.toString(16);
  23965. });
  23966. };
  23967. return Geometry;
  23968. })();
  23969. BABYLON.Geometry = Geometry;
  23970. /////// Primitives //////////////////////////////////////////////
  23971. var Geometry;
  23972. (function (Geometry) {
  23973. var Primitives;
  23974. (function (Primitives) {
  23975. /// Abstract class
  23976. var _Primitive = (function (_super) {
  23977. __extends(_Primitive, _super);
  23978. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  23979. this._beingRegenerated = true;
  23980. this._canBeRegenerated = canBeRegenerated;
  23981. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  23982. this._beingRegenerated = false;
  23983. }
  23984. _Primitive.prototype.canBeRegenerated = function () {
  23985. return this._canBeRegenerated;
  23986. };
  23987. _Primitive.prototype.regenerate = function () {
  23988. if (!this._canBeRegenerated) {
  23989. return;
  23990. }
  23991. this._beingRegenerated = true;
  23992. this.setAllVerticesData(this._regenerateVertexData(), false);
  23993. this._beingRegenerated = false;
  23994. };
  23995. _Primitive.prototype.asNewGeometry = function (id) {
  23996. return _super.prototype.copy.call(this, id);
  23997. };
  23998. // overrides
  23999. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  24000. if (!this._beingRegenerated) {
  24001. return;
  24002. }
  24003. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  24004. };
  24005. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  24006. if (!this._beingRegenerated) {
  24007. return;
  24008. }
  24009. _super.prototype.setVerticesData.call(this, kind, data, false);
  24010. };
  24011. // to override
  24012. // protected
  24013. _Primitive.prototype._regenerateVertexData = function () {
  24014. throw new Error("Abstract method");
  24015. };
  24016. _Primitive.prototype.copy = function (id) {
  24017. throw new Error("Must be overriden in sub-classes.");
  24018. };
  24019. return _Primitive;
  24020. })(Geometry);
  24021. Primitives._Primitive = _Primitive;
  24022. var Box = (function (_super) {
  24023. __extends(Box, _super);
  24024. function Box(id, scene, size, canBeRegenerated, mesh) {
  24025. this.size = size;
  24026. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24027. }
  24028. Box.prototype._regenerateVertexData = function () {
  24029. return BABYLON.VertexData.CreateBox(this.size);
  24030. };
  24031. Box.prototype.copy = function (id) {
  24032. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  24033. };
  24034. return Box;
  24035. })(_Primitive);
  24036. Primitives.Box = Box;
  24037. var Sphere = (function (_super) {
  24038. __extends(Sphere, _super);
  24039. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  24040. this.segments = segments;
  24041. this.diameter = diameter;
  24042. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24043. }
  24044. Sphere.prototype._regenerateVertexData = function () {
  24045. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  24046. };
  24047. Sphere.prototype.copy = function (id) {
  24048. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  24049. };
  24050. return Sphere;
  24051. })(_Primitive);
  24052. Primitives.Sphere = Sphere;
  24053. var Cylinder = (function (_super) {
  24054. __extends(Cylinder, _super);
  24055. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  24056. if (subdivisions === void 0) { subdivisions = 1; }
  24057. this.height = height;
  24058. this.diameterTop = diameterTop;
  24059. this.diameterBottom = diameterBottom;
  24060. this.tessellation = tessellation;
  24061. this.subdivisions = subdivisions;
  24062. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24063. }
  24064. Cylinder.prototype._regenerateVertexData = function () {
  24065. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  24066. };
  24067. Cylinder.prototype.copy = function (id) {
  24068. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  24069. };
  24070. return Cylinder;
  24071. })(_Primitive);
  24072. Primitives.Cylinder = Cylinder;
  24073. var Torus = (function (_super) {
  24074. __extends(Torus, _super);
  24075. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  24076. this.diameter = diameter;
  24077. this.thickness = thickness;
  24078. this.tessellation = tessellation;
  24079. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24080. }
  24081. Torus.prototype._regenerateVertexData = function () {
  24082. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  24083. };
  24084. Torus.prototype.copy = function (id) {
  24085. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  24086. };
  24087. return Torus;
  24088. })(_Primitive);
  24089. Primitives.Torus = Torus;
  24090. var Ground = (function (_super) {
  24091. __extends(Ground, _super);
  24092. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  24093. this.width = width;
  24094. this.height = height;
  24095. this.subdivisions = subdivisions;
  24096. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24097. }
  24098. Ground.prototype._regenerateVertexData = function () {
  24099. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  24100. };
  24101. Ground.prototype.copy = function (id) {
  24102. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  24103. };
  24104. return Ground;
  24105. })(_Primitive);
  24106. Primitives.Ground = Ground;
  24107. var TiledGround = (function (_super) {
  24108. __extends(TiledGround, _super);
  24109. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  24110. this.xmin = xmin;
  24111. this.zmin = zmin;
  24112. this.xmax = xmax;
  24113. this.zmax = zmax;
  24114. this.subdivisions = subdivisions;
  24115. this.precision = precision;
  24116. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24117. }
  24118. TiledGround.prototype._regenerateVertexData = function () {
  24119. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  24120. };
  24121. TiledGround.prototype.copy = function (id) {
  24122. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  24123. };
  24124. return TiledGround;
  24125. })(_Primitive);
  24126. Primitives.TiledGround = TiledGround;
  24127. var Plane = (function (_super) {
  24128. __extends(Plane, _super);
  24129. function Plane(id, scene, size, canBeRegenerated, mesh) {
  24130. this.size = size;
  24131. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24132. }
  24133. Plane.prototype._regenerateVertexData = function () {
  24134. return BABYLON.VertexData.CreatePlane(this.size);
  24135. };
  24136. Plane.prototype.copy = function (id) {
  24137. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  24138. };
  24139. return Plane;
  24140. })(_Primitive);
  24141. Primitives.Plane = Plane;
  24142. var TorusKnot = (function (_super) {
  24143. __extends(TorusKnot, _super);
  24144. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  24145. this.radius = radius;
  24146. this.tube = tube;
  24147. this.radialSegments = radialSegments;
  24148. this.tubularSegments = tubularSegments;
  24149. this.p = p;
  24150. this.q = q;
  24151. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24152. }
  24153. TorusKnot.prototype._regenerateVertexData = function () {
  24154. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  24155. };
  24156. TorusKnot.prototype.copy = function (id) {
  24157. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  24158. };
  24159. return TorusKnot;
  24160. })(_Primitive);
  24161. Primitives.TorusKnot = TorusKnot;
  24162. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  24163. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  24164. })(BABYLON || (BABYLON = {}));
  24165. //# sourceMappingURL=babylon.geometry.js.map
  24166. var BABYLON;
  24167. (function (BABYLON) {
  24168. var Gamepads = (function () {
  24169. function Gamepads(ongamedpadconnected) {
  24170. var _this = this;
  24171. this.babylonGamepads = [];
  24172. this.oneGamepadConnected = false;
  24173. this.isMonitoring = false;
  24174. this.gamepadEventSupported = 'GamepadEvent' in window;
  24175. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  24176. 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=";
  24177. this._callbackGamepadConnected = ongamedpadconnected;
  24178. if (this.gamepadSupportAvailable) {
  24179. // Checking if the gamepad connected event is supported (like in Firefox)
  24180. if (this.gamepadEventSupported) {
  24181. window.addEventListener('gamepadconnected', function (evt) {
  24182. _this._onGamepadConnected(evt);
  24183. }, false);
  24184. window.addEventListener('gamepaddisconnected', function (evt) {
  24185. _this._onGamepadDisconnected(evt);
  24186. }, false);
  24187. }
  24188. else {
  24189. this._startMonitoringGamepads();
  24190. }
  24191. if (!this.oneGamepadConnected) {
  24192. this._insertGamepadDOMInstructions();
  24193. }
  24194. }
  24195. else {
  24196. this._insertGamepadDOMNotSupported();
  24197. }
  24198. }
  24199. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  24200. Gamepads.gamepadDOMInfo = document.createElement("div");
  24201. var buttonAImage = document.createElement("img");
  24202. buttonAImage.src = this.buttonADataURL;
  24203. var spanMessage = document.createElement("span");
  24204. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  24205. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  24206. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24207. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24208. Gamepads.gamepadDOMInfo.style.width = "100%";
  24209. Gamepads.gamepadDOMInfo.style.height = "48px";
  24210. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24211. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24212. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24213. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24214. buttonAImage.style.position = "relative";
  24215. buttonAImage.style.bottom = "8px";
  24216. spanMessage.style.position = "relative";
  24217. spanMessage.style.fontSize = "32px";
  24218. spanMessage.style.bottom = "32px";
  24219. spanMessage.style.color = "green";
  24220. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24221. };
  24222. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  24223. Gamepads.gamepadDOMInfo = document.createElement("div");
  24224. var spanMessage = document.createElement("span");
  24225. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  24226. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24227. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24228. Gamepads.gamepadDOMInfo.style.width = "100%";
  24229. Gamepads.gamepadDOMInfo.style.height = "40px";
  24230. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24231. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24232. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24233. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24234. spanMessage.style.position = "relative";
  24235. spanMessage.style.fontSize = "32px";
  24236. spanMessage.style.color = "red";
  24237. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24238. };
  24239. Gamepads.prototype.dispose = function () {
  24240. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24241. };
  24242. Gamepads.prototype._onGamepadConnected = function (evt) {
  24243. var newGamepad = this._addNewGamepad(evt.gamepad);
  24244. if (this._callbackGamepadConnected)
  24245. this._callbackGamepadConnected(newGamepad);
  24246. this._startMonitoringGamepads();
  24247. };
  24248. Gamepads.prototype._addNewGamepad = function (gamepad) {
  24249. if (!this.oneGamepadConnected) {
  24250. this.oneGamepadConnected = true;
  24251. if (Gamepads.gamepadDOMInfo) {
  24252. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24253. Gamepads.gamepadDOMInfo = null;
  24254. }
  24255. }
  24256. var newGamepad;
  24257. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  24258. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  24259. }
  24260. else {
  24261. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  24262. }
  24263. this.babylonGamepads.push(newGamepad);
  24264. return newGamepad;
  24265. };
  24266. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  24267. for (var i in this.babylonGamepads) {
  24268. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  24269. this.babylonGamepads.splice(i, 1);
  24270. break;
  24271. }
  24272. }
  24273. // If no gamepads are left, stop the polling loop.
  24274. if (this.babylonGamepads.length == 0) {
  24275. this._stopMonitoringGamepads();
  24276. }
  24277. };
  24278. Gamepads.prototype._startMonitoringGamepads = function () {
  24279. if (!this.isMonitoring) {
  24280. this.isMonitoring = true;
  24281. this._checkGamepadsStatus();
  24282. }
  24283. };
  24284. Gamepads.prototype._stopMonitoringGamepads = function () {
  24285. this.isMonitoring = false;
  24286. };
  24287. Gamepads.prototype._checkGamepadsStatus = function () {
  24288. var _this = this;
  24289. // updating gamepad objects
  24290. this._updateGamepadObjects();
  24291. for (var i in this.babylonGamepads) {
  24292. this.babylonGamepads[i].update();
  24293. }
  24294. if (this.isMonitoring) {
  24295. if (window.requestAnimationFrame) {
  24296. window.requestAnimationFrame(function () {
  24297. _this._checkGamepadsStatus();
  24298. });
  24299. }
  24300. else if (window.mozRequestAnimationFrame) {
  24301. window.mozRequestAnimationFrame(function () {
  24302. _this._checkGamepadsStatus();
  24303. });
  24304. }
  24305. else if (window.webkitRequestAnimationFrame) {
  24306. window.webkitRequestAnimationFrame(function () {
  24307. _this._checkGamepadsStatus();
  24308. });
  24309. }
  24310. }
  24311. };
  24312. // This function is called only on Chrome, which does not yet support
  24313. // connection/disconnection events, but requires you to monitor
  24314. // an array for changes.
  24315. Gamepads.prototype._updateGamepadObjects = function () {
  24316. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  24317. for (var i = 0; i < gamepads.length; i++) {
  24318. if (gamepads[i]) {
  24319. if (!(gamepads[i].index in this.babylonGamepads)) {
  24320. var newGamepad = this._addNewGamepad(gamepads[i]);
  24321. if (this._callbackGamepadConnected) {
  24322. this._callbackGamepadConnected(newGamepad);
  24323. }
  24324. }
  24325. else {
  24326. this.babylonGamepads[i].browserGamepad = gamepads[i];
  24327. }
  24328. }
  24329. }
  24330. };
  24331. return Gamepads;
  24332. })();
  24333. BABYLON.Gamepads = Gamepads;
  24334. var StickValues = (function () {
  24335. function StickValues(x, y) {
  24336. this.x = x;
  24337. this.y = y;
  24338. }
  24339. return StickValues;
  24340. })();
  24341. BABYLON.StickValues = StickValues;
  24342. var Gamepad = (function () {
  24343. function Gamepad(id, index, browserGamepad) {
  24344. this.id = id;
  24345. this.index = index;
  24346. this.browserGamepad = browserGamepad;
  24347. if (this.browserGamepad.axes.length >= 2) {
  24348. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24349. }
  24350. if (this.browserGamepad.axes.length >= 4) {
  24351. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24352. }
  24353. }
  24354. Gamepad.prototype.onleftstickchanged = function (callback) {
  24355. this._onleftstickchanged = callback;
  24356. };
  24357. Gamepad.prototype.onrightstickchanged = function (callback) {
  24358. this._onrightstickchanged = callback;
  24359. };
  24360. Object.defineProperty(Gamepad.prototype, "leftStick", {
  24361. get: function () {
  24362. return this._leftStick;
  24363. },
  24364. set: function (newValues) {
  24365. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  24366. this._onleftstickchanged(newValues);
  24367. }
  24368. this._leftStick = newValues;
  24369. },
  24370. enumerable: true,
  24371. configurable: true
  24372. });
  24373. Object.defineProperty(Gamepad.prototype, "rightStick", {
  24374. get: function () {
  24375. return this._rightStick;
  24376. },
  24377. set: function (newValues) {
  24378. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  24379. this._onrightstickchanged(newValues);
  24380. }
  24381. this._rightStick = newValues;
  24382. },
  24383. enumerable: true,
  24384. configurable: true
  24385. });
  24386. Gamepad.prototype.update = function () {
  24387. if (this._leftStick) {
  24388. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24389. }
  24390. if (this._rightStick) {
  24391. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24392. }
  24393. };
  24394. return Gamepad;
  24395. })();
  24396. BABYLON.Gamepad = Gamepad;
  24397. var GenericPad = (function (_super) {
  24398. __extends(GenericPad, _super);
  24399. function GenericPad(id, index, gamepad) {
  24400. _super.call(this, id, index, gamepad);
  24401. this.id = id;
  24402. this.index = index;
  24403. this.gamepad = gamepad;
  24404. this._buttons = new Array(gamepad.buttons.length);
  24405. }
  24406. GenericPad.prototype.onbuttondown = function (callback) {
  24407. this._onbuttondown = callback;
  24408. };
  24409. GenericPad.prototype.onbuttonup = function (callback) {
  24410. this._onbuttonup = callback;
  24411. };
  24412. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  24413. if (newValue !== currentValue) {
  24414. if (this._onbuttondown && newValue === 1) {
  24415. this._onbuttondown(buttonIndex);
  24416. }
  24417. if (this._onbuttonup && newValue === 0) {
  24418. this._onbuttonup(buttonIndex);
  24419. }
  24420. }
  24421. return newValue;
  24422. };
  24423. GenericPad.prototype.update = function () {
  24424. _super.prototype.update.call(this);
  24425. for (var index = 0; index < this._buttons.length; index++) {
  24426. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  24427. }
  24428. };
  24429. return GenericPad;
  24430. })(Gamepad);
  24431. BABYLON.GenericPad = GenericPad;
  24432. (function (Xbox360Button) {
  24433. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  24434. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  24435. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  24436. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  24437. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  24438. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  24439. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  24440. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  24441. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  24442. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  24443. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  24444. var Xbox360Button = BABYLON.Xbox360Button;
  24445. (function (Xbox360Dpad) {
  24446. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  24447. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  24448. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  24449. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  24450. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  24451. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  24452. var Xbox360Pad = (function (_super) {
  24453. __extends(Xbox360Pad, _super);
  24454. function Xbox360Pad() {
  24455. _super.apply(this, arguments);
  24456. this._leftTrigger = 0;
  24457. this._rightTrigger = 0;
  24458. this._buttonA = 0;
  24459. this._buttonB = 0;
  24460. this._buttonX = 0;
  24461. this._buttonY = 0;
  24462. this._buttonBack = 0;
  24463. this._buttonStart = 0;
  24464. this._buttonLB = 0;
  24465. this._buttonRB = 0;
  24466. this._buttonLeftStick = 0;
  24467. this._buttonRightStick = 0;
  24468. this._dPadUp = 0;
  24469. this._dPadDown = 0;
  24470. this._dPadLeft = 0;
  24471. this._dPadRight = 0;
  24472. }
  24473. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  24474. this._onlefttriggerchanged = callback;
  24475. };
  24476. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  24477. this._onrighttriggerchanged = callback;
  24478. };
  24479. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  24480. get: function () {
  24481. return this._leftTrigger;
  24482. },
  24483. set: function (newValue) {
  24484. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  24485. this._onlefttriggerchanged(newValue);
  24486. }
  24487. this._leftTrigger = newValue;
  24488. },
  24489. enumerable: true,
  24490. configurable: true
  24491. });
  24492. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  24493. get: function () {
  24494. return this._rightTrigger;
  24495. },
  24496. set: function (newValue) {
  24497. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  24498. this._onrighttriggerchanged(newValue);
  24499. }
  24500. this._rightTrigger = newValue;
  24501. },
  24502. enumerable: true,
  24503. configurable: true
  24504. });
  24505. Xbox360Pad.prototype.onbuttondown = function (callback) {
  24506. this._onbuttondown = callback;
  24507. };
  24508. Xbox360Pad.prototype.onbuttonup = function (callback) {
  24509. this._onbuttonup = callback;
  24510. };
  24511. Xbox360Pad.prototype.ondpaddown = function (callback) {
  24512. this._ondpaddown = callback;
  24513. };
  24514. Xbox360Pad.prototype.ondpadup = function (callback) {
  24515. this._ondpadup = callback;
  24516. };
  24517. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  24518. if (newValue !== currentValue) {
  24519. if (this._onbuttondown && newValue === 1) {
  24520. this._onbuttondown(buttonType);
  24521. }
  24522. if (this._onbuttonup && newValue === 0) {
  24523. this._onbuttonup(buttonType);
  24524. }
  24525. }
  24526. return newValue;
  24527. };
  24528. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  24529. if (newValue !== currentValue) {
  24530. if (this._ondpaddown && newValue === 1) {
  24531. this._ondpaddown(buttonType);
  24532. }
  24533. if (this._ondpadup && newValue === 0) {
  24534. this._ondpadup(buttonType);
  24535. }
  24536. }
  24537. return newValue;
  24538. };
  24539. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  24540. get: function () {
  24541. return this._buttonA;
  24542. },
  24543. set: function (value) {
  24544. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  24545. },
  24546. enumerable: true,
  24547. configurable: true
  24548. });
  24549. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  24550. get: function () {
  24551. return this._buttonB;
  24552. },
  24553. set: function (value) {
  24554. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  24555. },
  24556. enumerable: true,
  24557. configurable: true
  24558. });
  24559. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  24560. get: function () {
  24561. return this._buttonX;
  24562. },
  24563. set: function (value) {
  24564. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  24565. },
  24566. enumerable: true,
  24567. configurable: true
  24568. });
  24569. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  24570. get: function () {
  24571. return this._buttonY;
  24572. },
  24573. set: function (value) {
  24574. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  24575. },
  24576. enumerable: true,
  24577. configurable: true
  24578. });
  24579. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  24580. get: function () {
  24581. return this._buttonStart;
  24582. },
  24583. set: function (value) {
  24584. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  24585. },
  24586. enumerable: true,
  24587. configurable: true
  24588. });
  24589. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  24590. get: function () {
  24591. return this._buttonBack;
  24592. },
  24593. set: function (value) {
  24594. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  24595. },
  24596. enumerable: true,
  24597. configurable: true
  24598. });
  24599. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  24600. get: function () {
  24601. return this._buttonLB;
  24602. },
  24603. set: function (value) {
  24604. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  24605. },
  24606. enumerable: true,
  24607. configurable: true
  24608. });
  24609. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  24610. get: function () {
  24611. return this._buttonRB;
  24612. },
  24613. set: function (value) {
  24614. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  24615. },
  24616. enumerable: true,
  24617. configurable: true
  24618. });
  24619. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  24620. get: function () {
  24621. return this._buttonLeftStick;
  24622. },
  24623. set: function (value) {
  24624. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  24625. },
  24626. enumerable: true,
  24627. configurable: true
  24628. });
  24629. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  24630. get: function () {
  24631. return this._buttonRightStick;
  24632. },
  24633. set: function (value) {
  24634. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  24635. },
  24636. enumerable: true,
  24637. configurable: true
  24638. });
  24639. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  24640. get: function () {
  24641. return this._dPadUp;
  24642. },
  24643. set: function (value) {
  24644. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  24645. },
  24646. enumerable: true,
  24647. configurable: true
  24648. });
  24649. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  24650. get: function () {
  24651. return this._dPadDown;
  24652. },
  24653. set: function (value) {
  24654. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  24655. },
  24656. enumerable: true,
  24657. configurable: true
  24658. });
  24659. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  24660. get: function () {
  24661. return this._dPadLeft;
  24662. },
  24663. set: function (value) {
  24664. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  24665. },
  24666. enumerable: true,
  24667. configurable: true
  24668. });
  24669. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  24670. get: function () {
  24671. return this._dPadRight;
  24672. },
  24673. set: function (value) {
  24674. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  24675. },
  24676. enumerable: true,
  24677. configurable: true
  24678. });
  24679. Xbox360Pad.prototype.update = function () {
  24680. _super.prototype.update.call(this);
  24681. this.buttonA = this.browserGamepad.buttons[0].value;
  24682. this.buttonB = this.browserGamepad.buttons[1].value;
  24683. this.buttonX = this.browserGamepad.buttons[2].value;
  24684. this.buttonY = this.browserGamepad.buttons[3].value;
  24685. this.buttonLB = this.browserGamepad.buttons[4].value;
  24686. this.buttonRB = this.browserGamepad.buttons[5].value;
  24687. this.leftTrigger = this.browserGamepad.buttons[6].value;
  24688. this.rightTrigger = this.browserGamepad.buttons[7].value;
  24689. this.buttonBack = this.browserGamepad.buttons[8].value;
  24690. this.buttonStart = this.browserGamepad.buttons[9].value;
  24691. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  24692. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  24693. this.dPadUp = this.browserGamepad.buttons[12].value;
  24694. this.dPadDown = this.browserGamepad.buttons[13].value;
  24695. this.dPadLeft = this.browserGamepad.buttons[14].value;
  24696. this.dPadRight = this.browserGamepad.buttons[15].value;
  24697. };
  24698. return Xbox360Pad;
  24699. })(Gamepad);
  24700. BABYLON.Xbox360Pad = Xbox360Pad;
  24701. })(BABYLON || (BABYLON = {}));
  24702. //# sourceMappingURL=babylon.gamepads.js.map
  24703. var BABYLON;
  24704. (function (BABYLON) {
  24705. // We're mainly based on the logic defined into the FreeCamera code
  24706. var GamepadCamera = (function (_super) {
  24707. __extends(GamepadCamera, _super);
  24708. function GamepadCamera(name, position, scene) {
  24709. var _this = this;
  24710. _super.call(this, name, position, scene);
  24711. this.angularSensibility = 200;
  24712. this.moveSensibility = 75;
  24713. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  24714. _this._onNewGameConnected(gamepad);
  24715. });
  24716. }
  24717. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  24718. // Only the first gamepad can control the camera
  24719. if (gamepad.index === 0) {
  24720. this._gamepad = gamepad;
  24721. }
  24722. };
  24723. GamepadCamera.prototype._checkInputs = function () {
  24724. if (!this._gamepad) {
  24725. return;
  24726. }
  24727. var LSValues = this._gamepad.leftStick;
  24728. var normalizedLX = LSValues.x / this.moveSensibility;
  24729. var normalizedLY = LSValues.y / this.moveSensibility;
  24730. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  24731. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  24732. var RSValues = this._gamepad.rightStick;
  24733. var normalizedRX = RSValues.x / this.angularSensibility;
  24734. var normalizedRY = RSValues.y / this.angularSensibility;
  24735. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  24736. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  24737. ;
  24738. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  24739. var speed = this._computeLocalCameraSpeed() * 50.0;
  24740. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  24741. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  24742. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  24743. };
  24744. GamepadCamera.prototype.dispose = function () {
  24745. this._gamepads.dispose();
  24746. _super.prototype.dispose.call(this);
  24747. };
  24748. return GamepadCamera;
  24749. })(BABYLON.FreeCamera);
  24750. BABYLON.GamepadCamera = GamepadCamera;
  24751. })(BABYLON || (BABYLON = {}));
  24752. //# sourceMappingURL=babylon.gamepadCamera.js.map
  24753. var BABYLON;
  24754. (function (BABYLON) {
  24755. var LinesMesh = (function (_super) {
  24756. __extends(LinesMesh, _super);
  24757. function LinesMesh(name, scene, updatable) {
  24758. if (updatable === void 0) { updatable = false; }
  24759. _super.call(this, name, scene);
  24760. this.color = new BABYLON.Color3(1, 1, 1);
  24761. this.alpha = 1;
  24762. this._indices = new Array();
  24763. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  24764. attributes: ["position"],
  24765. uniforms: ["worldViewProjection", "color"],
  24766. needAlphaBlending: true
  24767. });
  24768. }
  24769. Object.defineProperty(LinesMesh.prototype, "material", {
  24770. get: function () {
  24771. return this._colorShader;
  24772. },
  24773. enumerable: true,
  24774. configurable: true
  24775. });
  24776. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  24777. get: function () {
  24778. return false;
  24779. },
  24780. enumerable: true,
  24781. configurable: true
  24782. });
  24783. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  24784. get: function () {
  24785. return false;
  24786. },
  24787. enumerable: true,
  24788. configurable: true
  24789. });
  24790. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  24791. var engine = this.getScene().getEngine();
  24792. var indexToBind = this._geometry.getIndexBuffer();
  24793. // VBOs
  24794. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  24795. // Color
  24796. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  24797. };
  24798. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  24799. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24800. return;
  24801. }
  24802. var engine = this.getScene().getEngine();
  24803. // Draw order
  24804. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  24805. };
  24806. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  24807. return null;
  24808. };
  24809. LinesMesh.prototype.dispose = function (doNotRecurse) {
  24810. this._colorShader.dispose();
  24811. _super.prototype.dispose.call(this, doNotRecurse);
  24812. };
  24813. return LinesMesh;
  24814. })(BABYLON.Mesh);
  24815. BABYLON.LinesMesh = LinesMesh;
  24816. })(BABYLON || (BABYLON = {}));
  24817. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  24818. (function (BABYLON) {
  24819. var OutlineRenderer = (function () {
  24820. function OutlineRenderer(scene) {
  24821. this._scene = scene;
  24822. }
  24823. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  24824. var _this = this;
  24825. if (useOverlay === void 0) { useOverlay = false; }
  24826. var scene = this._scene;
  24827. var engine = this._scene.getEngine();
  24828. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24829. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  24830. return;
  24831. }
  24832. var mesh = subMesh.getRenderingMesh();
  24833. var material = subMesh.getMaterial();
  24834. engine.enableEffect(this._effect);
  24835. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  24836. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  24837. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  24838. // Bones
  24839. if (mesh.useBones) {
  24840. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  24841. }
  24842. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  24843. // Alpha test
  24844. if (material && material.needAlphaTesting()) {
  24845. var alphaTexture = material.getAlphaTestTexture();
  24846. this._effect.setTexture("diffuseSampler", alphaTexture);
  24847. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  24848. }
  24849. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  24850. _this._effect.setMatrix("world", world);
  24851. });
  24852. };
  24853. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  24854. var defines = [];
  24855. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  24856. var mesh = subMesh.getMesh();
  24857. var material = subMesh.getMaterial();
  24858. // Alpha test
  24859. if (material && material.needAlphaTesting()) {
  24860. defines.push("#define ALPHATEST");
  24861. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24862. attribs.push(BABYLON.VertexBuffer.UVKind);
  24863. defines.push("#define UV1");
  24864. }
  24865. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24866. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  24867. defines.push("#define UV2");
  24868. }
  24869. }
  24870. // Bones
  24871. if (mesh.useBones) {
  24872. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24873. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24874. defines.push("#define BONES");
  24875. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  24876. }
  24877. // Instances
  24878. if (useInstances) {
  24879. defines.push("#define INSTANCES");
  24880. attribs.push("world0");
  24881. attribs.push("world1");
  24882. attribs.push("world2");
  24883. attribs.push("world3");
  24884. }
  24885. // Get correct effect
  24886. var join = defines.join("\n");
  24887. if (this._cachedDefines !== join) {
  24888. this._cachedDefines = join;
  24889. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  24890. }
  24891. return this._effect.isReady();
  24892. };
  24893. return OutlineRenderer;
  24894. })();
  24895. BABYLON.OutlineRenderer = OutlineRenderer;
  24896. })(BABYLON || (BABYLON = {}));
  24897. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  24898. (function (BABYLON) {
  24899. var MeshAssetTask = (function () {
  24900. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  24901. this.name = name;
  24902. this.meshesNames = meshesNames;
  24903. this.rootUrl = rootUrl;
  24904. this.sceneFilename = sceneFilename;
  24905. this.isCompleted = false;
  24906. }
  24907. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24908. var _this = this;
  24909. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  24910. _this.loadedMeshes = meshes;
  24911. _this.loadedParticleSystems = particleSystems;
  24912. _this.loadedSkeletons = skeletons;
  24913. _this.isCompleted = true;
  24914. if (_this.onSuccess) {
  24915. _this.onSuccess(_this);
  24916. }
  24917. onSuccess();
  24918. }, null, function () {
  24919. if (_this.onError) {
  24920. _this.onError(_this);
  24921. }
  24922. onError();
  24923. });
  24924. };
  24925. return MeshAssetTask;
  24926. })();
  24927. BABYLON.MeshAssetTask = MeshAssetTask;
  24928. var TextFileAssetTask = (function () {
  24929. function TextFileAssetTask(name, url) {
  24930. this.name = name;
  24931. this.url = url;
  24932. this.isCompleted = false;
  24933. }
  24934. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24935. var _this = this;
  24936. BABYLON.Tools.LoadFile(this.url, function (data) {
  24937. _this.text = data;
  24938. _this.isCompleted = true;
  24939. if (_this.onSuccess) {
  24940. _this.onSuccess(_this);
  24941. }
  24942. onSuccess();
  24943. }, null, scene.database, false, function () {
  24944. if (_this.onError) {
  24945. _this.onError(_this);
  24946. }
  24947. onError();
  24948. });
  24949. };
  24950. return TextFileAssetTask;
  24951. })();
  24952. BABYLON.TextFileAssetTask = TextFileAssetTask;
  24953. var BinaryFileAssetTask = (function () {
  24954. function BinaryFileAssetTask(name, url) {
  24955. this.name = name;
  24956. this.url = url;
  24957. this.isCompleted = false;
  24958. }
  24959. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24960. var _this = this;
  24961. BABYLON.Tools.LoadFile(this.url, function (data) {
  24962. _this.data = data;
  24963. _this.isCompleted = true;
  24964. if (_this.onSuccess) {
  24965. _this.onSuccess(_this);
  24966. }
  24967. onSuccess();
  24968. }, null, scene.database, true, function () {
  24969. if (_this.onError) {
  24970. _this.onError(_this);
  24971. }
  24972. onError();
  24973. });
  24974. };
  24975. return BinaryFileAssetTask;
  24976. })();
  24977. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  24978. var ImageAssetTask = (function () {
  24979. function ImageAssetTask(name, url) {
  24980. this.name = name;
  24981. this.url = url;
  24982. this.isCompleted = false;
  24983. }
  24984. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24985. var _this = this;
  24986. var img = new Image();
  24987. img.onload = function () {
  24988. _this.image = img;
  24989. _this.isCompleted = true;
  24990. if (_this.onSuccess) {
  24991. _this.onSuccess(_this);
  24992. }
  24993. onSuccess();
  24994. };
  24995. img.onerror = function () {
  24996. if (_this.onError) {
  24997. _this.onError(_this);
  24998. }
  24999. onError();
  25000. };
  25001. img.src = this.url;
  25002. };
  25003. return ImageAssetTask;
  25004. })();
  25005. BABYLON.ImageAssetTask = ImageAssetTask;
  25006. var TextureAssetTask = (function () {
  25007. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  25008. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25009. this.name = name;
  25010. this.url = url;
  25011. this.noMipmap = noMipmap;
  25012. this.invertY = invertY;
  25013. this.samplingMode = samplingMode;
  25014. this.isCompleted = false;
  25015. }
  25016. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25017. var _this = this;
  25018. var onload = function () {
  25019. _this.isCompleted = true;
  25020. if (_this.onSuccess) {
  25021. _this.onSuccess(_this);
  25022. }
  25023. onSuccess();
  25024. };
  25025. var onerror = function () {
  25026. if (_this.onError) {
  25027. _this.onError(_this);
  25028. }
  25029. onError();
  25030. };
  25031. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  25032. };
  25033. return TextureAssetTask;
  25034. })();
  25035. BABYLON.TextureAssetTask = TextureAssetTask;
  25036. var AssetsManager = (function () {
  25037. function AssetsManager(scene) {
  25038. this._tasks = new Array();
  25039. this._waitingTasksCount = 0;
  25040. this.useDefaultLoadingScreen = true;
  25041. this._scene = scene;
  25042. }
  25043. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  25044. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  25045. this._tasks.push(task);
  25046. return task;
  25047. };
  25048. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  25049. var task = new TextFileAssetTask(taskName, url);
  25050. this._tasks.push(task);
  25051. return task;
  25052. };
  25053. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  25054. var task = new BinaryFileAssetTask(taskName, url);
  25055. this._tasks.push(task);
  25056. return task;
  25057. };
  25058. AssetsManager.prototype.addImageTask = function (taskName, url) {
  25059. var task = new ImageAssetTask(taskName, url);
  25060. this._tasks.push(task);
  25061. return task;
  25062. };
  25063. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  25064. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25065. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  25066. this._tasks.push(task);
  25067. return task;
  25068. };
  25069. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  25070. this._waitingTasksCount--;
  25071. if (this._waitingTasksCount === 0) {
  25072. if (this.onFinish) {
  25073. this.onFinish(this._tasks);
  25074. }
  25075. this._scene.getEngine().hideLoadingUI();
  25076. }
  25077. };
  25078. AssetsManager.prototype._runTask = function (task) {
  25079. var _this = this;
  25080. task.run(this._scene, function () {
  25081. if (_this.onTaskSuccess) {
  25082. _this.onTaskSuccess(task);
  25083. }
  25084. _this._decreaseWaitingTasksCount();
  25085. }, function () {
  25086. if (_this.onTaskError) {
  25087. _this.onTaskError(task);
  25088. }
  25089. _this._decreaseWaitingTasksCount();
  25090. });
  25091. };
  25092. AssetsManager.prototype.reset = function () {
  25093. this._tasks = new Array();
  25094. return this;
  25095. };
  25096. AssetsManager.prototype.load = function () {
  25097. this._waitingTasksCount = this._tasks.length;
  25098. if (this._waitingTasksCount === 0) {
  25099. if (this.onFinish) {
  25100. this.onFinish(this._tasks);
  25101. }
  25102. return this;
  25103. }
  25104. if (this.useDefaultLoadingScreen) {
  25105. this._scene.getEngine().displayLoadingUI();
  25106. }
  25107. for (var index = 0; index < this._tasks.length; index++) {
  25108. var task = this._tasks[index];
  25109. this._runTask(task);
  25110. }
  25111. return this;
  25112. };
  25113. return AssetsManager;
  25114. })();
  25115. BABYLON.AssetsManager = AssetsManager;
  25116. })(BABYLON || (BABYLON = {}));
  25117. //# sourceMappingURL=babylon.assetsManager.js.map
  25118. var BABYLON;
  25119. (function (BABYLON) {
  25120. var VRDeviceOrientationCamera = (function (_super) {
  25121. __extends(VRDeviceOrientationCamera, _super);
  25122. function VRDeviceOrientationCamera(name, position, scene) {
  25123. _super.call(this, name, position, scene);
  25124. this._alpha = 0;
  25125. this._beta = 0;
  25126. this._gamma = 0;
  25127. }
  25128. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  25129. this._alpha = +evt.alpha | 0;
  25130. this._beta = +evt.beta | 0;
  25131. this._gamma = +evt.gamma | 0;
  25132. if (this._gamma < 0) {
  25133. this._gamma = 90 + this._gamma;
  25134. }
  25135. else {
  25136. // Incline it in the correct angle.
  25137. this._gamma = 270 - this._gamma;
  25138. }
  25139. this.rotation.x = this._gamma / 180.0 * Math.PI;
  25140. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  25141. this.rotation.z = this._beta / 180.0 * Math.PI;
  25142. };
  25143. return VRDeviceOrientationCamera;
  25144. })(BABYLON.OculusCamera);
  25145. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  25146. })(BABYLON || (BABYLON = {}));
  25147. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  25148. var BABYLON;
  25149. (function (BABYLON) {
  25150. var WebVRCamera = (function (_super) {
  25151. __extends(WebVRCamera, _super);
  25152. function WebVRCamera(name, position, scene) {
  25153. _super.call(this, name, position, scene);
  25154. this._hmdDevice = null;
  25155. this._sensorDevice = null;
  25156. this._cacheState = null;
  25157. this._cacheQuaternion = new BABYLON.Quaternion();
  25158. this._cacheRotation = BABYLON.Vector3.Zero();
  25159. this._vrEnabled = false;
  25160. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  25161. }
  25162. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  25163. var size = devices.length;
  25164. var i = 0;
  25165. // Reset devices.
  25166. this._sensorDevice = null;
  25167. this._hmdDevice = null;
  25168. while (i < size && this._hmdDevice === null) {
  25169. if (devices[i] instanceof HMDVRDevice) {
  25170. this._hmdDevice = devices[i];
  25171. }
  25172. i++;
  25173. }
  25174. i = 0;
  25175. while (i < size && this._sensorDevice === null) {
  25176. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  25177. this._sensorDevice = devices[i];
  25178. }
  25179. i++;
  25180. }
  25181. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  25182. };
  25183. WebVRCamera.prototype._update = function () {
  25184. if (this._vrEnabled) {
  25185. this._cacheState = this._sensorDevice.getState();
  25186. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  25187. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  25188. this.rotation.x = -this._cacheRotation.z;
  25189. this.rotation.y = -this._cacheRotation.y;
  25190. this.rotation.z = this._cacheRotation.x;
  25191. }
  25192. _super.prototype._update.call(this);
  25193. };
  25194. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  25195. _super.prototype.attachControl.call(this, element, noPreventDefault);
  25196. if (navigator.getVRDevices) {
  25197. navigator.getVRDevices().then(this._getWebVRDevices);
  25198. }
  25199. else if (navigator.mozGetVRDevices) {
  25200. navigator.mozGetVRDevices(this._getWebVRDevices);
  25201. }
  25202. };
  25203. WebVRCamera.prototype.detachControl = function (element) {
  25204. _super.prototype.detachControl.call(this, element);
  25205. this._vrEnabled = false;
  25206. };
  25207. return WebVRCamera;
  25208. })(BABYLON.OculusCamera);
  25209. BABYLON.WebVRCamera = WebVRCamera;
  25210. })(BABYLON || (BABYLON = {}));
  25211. //# sourceMappingURL=babylon.webVRCamera.js.map
  25212. var BABYLON;
  25213. (function (BABYLON) {
  25214. // Standard optimizations
  25215. var SceneOptimization = (function () {
  25216. function SceneOptimization(priority) {
  25217. if (priority === void 0) { priority = 0; }
  25218. this.priority = priority;
  25219. this.apply = function (scene) {
  25220. return true; // Return true if everything that can be done was applied
  25221. };
  25222. }
  25223. return SceneOptimization;
  25224. })();
  25225. BABYLON.SceneOptimization = SceneOptimization;
  25226. var TextureOptimization = (function (_super) {
  25227. __extends(TextureOptimization, _super);
  25228. function TextureOptimization(priority, maximumSize) {
  25229. var _this = this;
  25230. if (priority === void 0) { priority = 0; }
  25231. if (maximumSize === void 0) { maximumSize = 1024; }
  25232. _super.call(this, priority);
  25233. this.priority = priority;
  25234. this.maximumSize = maximumSize;
  25235. this.apply = function (scene) {
  25236. var allDone = true;
  25237. for (var index = 0; index < scene.textures.length; index++) {
  25238. var texture = scene.textures[index];
  25239. if (!texture.canRescale) {
  25240. continue;
  25241. }
  25242. var currentSize = texture.getSize();
  25243. var maxDimension = Math.max(currentSize.width, currentSize.height);
  25244. if (maxDimension > _this.maximumSize) {
  25245. texture.scale(0.5);
  25246. allDone = false;
  25247. }
  25248. }
  25249. return allDone;
  25250. };
  25251. }
  25252. return TextureOptimization;
  25253. })(SceneOptimization);
  25254. BABYLON.TextureOptimization = TextureOptimization;
  25255. var HardwareScalingOptimization = (function (_super) {
  25256. __extends(HardwareScalingOptimization, _super);
  25257. function HardwareScalingOptimization(priority, maximumScale) {
  25258. var _this = this;
  25259. if (priority === void 0) { priority = 0; }
  25260. if (maximumScale === void 0) { maximumScale = 2; }
  25261. _super.call(this, priority);
  25262. this.priority = priority;
  25263. this.maximumScale = maximumScale;
  25264. this._currentScale = 1;
  25265. this.apply = function (scene) {
  25266. _this._currentScale++;
  25267. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  25268. return _this._currentScale >= _this.maximumScale;
  25269. };
  25270. }
  25271. return HardwareScalingOptimization;
  25272. })(SceneOptimization);
  25273. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  25274. var ShadowsOptimization = (function (_super) {
  25275. __extends(ShadowsOptimization, _super);
  25276. function ShadowsOptimization() {
  25277. _super.apply(this, arguments);
  25278. this.apply = function (scene) {
  25279. scene.shadowsEnabled = false;
  25280. return true;
  25281. };
  25282. }
  25283. return ShadowsOptimization;
  25284. })(SceneOptimization);
  25285. BABYLON.ShadowsOptimization = ShadowsOptimization;
  25286. var PostProcessesOptimization = (function (_super) {
  25287. __extends(PostProcessesOptimization, _super);
  25288. function PostProcessesOptimization() {
  25289. _super.apply(this, arguments);
  25290. this.apply = function (scene) {
  25291. scene.postProcessesEnabled = false;
  25292. return true;
  25293. };
  25294. }
  25295. return PostProcessesOptimization;
  25296. })(SceneOptimization);
  25297. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  25298. var LensFlaresOptimization = (function (_super) {
  25299. __extends(LensFlaresOptimization, _super);
  25300. function LensFlaresOptimization() {
  25301. _super.apply(this, arguments);
  25302. this.apply = function (scene) {
  25303. scene.lensFlaresEnabled = false;
  25304. return true;
  25305. };
  25306. }
  25307. return LensFlaresOptimization;
  25308. })(SceneOptimization);
  25309. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  25310. var ParticlesOptimization = (function (_super) {
  25311. __extends(ParticlesOptimization, _super);
  25312. function ParticlesOptimization() {
  25313. _super.apply(this, arguments);
  25314. this.apply = function (scene) {
  25315. scene.particlesEnabled = false;
  25316. return true;
  25317. };
  25318. }
  25319. return ParticlesOptimization;
  25320. })(SceneOptimization);
  25321. BABYLON.ParticlesOptimization = ParticlesOptimization;
  25322. var RenderTargetsOptimization = (function (_super) {
  25323. __extends(RenderTargetsOptimization, _super);
  25324. function RenderTargetsOptimization() {
  25325. _super.apply(this, arguments);
  25326. this.apply = function (scene) {
  25327. scene.renderTargetsEnabled = false;
  25328. return true;
  25329. };
  25330. }
  25331. return RenderTargetsOptimization;
  25332. })(SceneOptimization);
  25333. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  25334. var MergeMeshesOptimization = (function (_super) {
  25335. __extends(MergeMeshesOptimization, _super);
  25336. function MergeMeshesOptimization() {
  25337. var _this = this;
  25338. _super.apply(this, arguments);
  25339. this._canBeMerged = function (abstractMesh) {
  25340. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  25341. return false;
  25342. }
  25343. var mesh = abstractMesh;
  25344. if (!mesh.isVisible || !mesh.isEnabled()) {
  25345. return false;
  25346. }
  25347. if (mesh.instances.length > 0) {
  25348. return false;
  25349. }
  25350. if (mesh.skeleton || mesh.hasLODLevels) {
  25351. return false;
  25352. }
  25353. return true;
  25354. };
  25355. this.apply = function (scene) {
  25356. var globalPool = scene.meshes.slice(0);
  25357. var globalLength = globalPool.length;
  25358. for (var index = 0; index < globalLength; index++) {
  25359. var currentPool = new Array();
  25360. var current = globalPool[index];
  25361. // Checks
  25362. if (!_this._canBeMerged(current)) {
  25363. continue;
  25364. }
  25365. currentPool.push(current);
  25366. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  25367. var otherMesh = globalPool[subIndex];
  25368. if (!_this._canBeMerged(otherMesh)) {
  25369. continue;
  25370. }
  25371. if (otherMesh.material !== current.material) {
  25372. continue;
  25373. }
  25374. if (otherMesh.checkCollisions !== current.checkCollisions) {
  25375. continue;
  25376. }
  25377. currentPool.push(otherMesh);
  25378. globalLength--;
  25379. globalPool.splice(subIndex, 1);
  25380. subIndex--;
  25381. }
  25382. if (currentPool.length < 2) {
  25383. continue;
  25384. }
  25385. // Merge meshes
  25386. BABYLON.Mesh.MergeMeshes(currentPool);
  25387. }
  25388. return true;
  25389. };
  25390. }
  25391. return MergeMeshesOptimization;
  25392. })(SceneOptimization);
  25393. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  25394. // Options
  25395. var SceneOptimizerOptions = (function () {
  25396. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  25397. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  25398. if (trackerDuration === void 0) { trackerDuration = 2000; }
  25399. this.targetFrameRate = targetFrameRate;
  25400. this.trackerDuration = trackerDuration;
  25401. this.optimizations = new Array();
  25402. }
  25403. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  25404. var result = new SceneOptimizerOptions(targetFrameRate);
  25405. var priority = 0;
  25406. result.optimizations.push(new MergeMeshesOptimization(priority));
  25407. result.optimizations.push(new ShadowsOptimization(priority));
  25408. result.optimizations.push(new LensFlaresOptimization(priority));
  25409. // Next priority
  25410. priority++;
  25411. result.optimizations.push(new PostProcessesOptimization(priority));
  25412. result.optimizations.push(new ParticlesOptimization(priority));
  25413. // Next priority
  25414. priority++;
  25415. result.optimizations.push(new TextureOptimization(priority, 1024));
  25416. return result;
  25417. };
  25418. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  25419. var result = new SceneOptimizerOptions(targetFrameRate);
  25420. var priority = 0;
  25421. result.optimizations.push(new MergeMeshesOptimization(priority));
  25422. result.optimizations.push(new ShadowsOptimization(priority));
  25423. result.optimizations.push(new LensFlaresOptimization(priority));
  25424. // Next priority
  25425. priority++;
  25426. result.optimizations.push(new PostProcessesOptimization(priority));
  25427. result.optimizations.push(new ParticlesOptimization(priority));
  25428. // Next priority
  25429. priority++;
  25430. result.optimizations.push(new TextureOptimization(priority, 512));
  25431. // Next priority
  25432. priority++;
  25433. result.optimizations.push(new RenderTargetsOptimization(priority));
  25434. // Next priority
  25435. priority++;
  25436. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  25437. return result;
  25438. };
  25439. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  25440. var result = new SceneOptimizerOptions(targetFrameRate);
  25441. var priority = 0;
  25442. result.optimizations.push(new MergeMeshesOptimization(priority));
  25443. result.optimizations.push(new ShadowsOptimization(priority));
  25444. result.optimizations.push(new LensFlaresOptimization(priority));
  25445. // Next priority
  25446. priority++;
  25447. result.optimizations.push(new PostProcessesOptimization(priority));
  25448. result.optimizations.push(new ParticlesOptimization(priority));
  25449. // Next priority
  25450. priority++;
  25451. result.optimizations.push(new TextureOptimization(priority, 256));
  25452. // Next priority
  25453. priority++;
  25454. result.optimizations.push(new RenderTargetsOptimization(priority));
  25455. // Next priority
  25456. priority++;
  25457. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  25458. return result;
  25459. };
  25460. return SceneOptimizerOptions;
  25461. })();
  25462. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  25463. // Scene optimizer tool
  25464. var SceneOptimizer = (function () {
  25465. function SceneOptimizer() {
  25466. }
  25467. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  25468. // TODO: add an epsilon
  25469. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  25470. if (onSuccess) {
  25471. onSuccess();
  25472. }
  25473. return;
  25474. }
  25475. // Apply current level of optimizations
  25476. var allDone = true;
  25477. var noOptimizationApplied = true;
  25478. for (var index = 0; index < options.optimizations.length; index++) {
  25479. var optimization = options.optimizations[index];
  25480. if (optimization.priority === currentPriorityLevel) {
  25481. noOptimizationApplied = false;
  25482. allDone = allDone && optimization.apply(scene);
  25483. }
  25484. }
  25485. // If no optimization was applied, this is a failure :(
  25486. if (noOptimizationApplied) {
  25487. if (onFailure) {
  25488. onFailure();
  25489. }
  25490. return;
  25491. }
  25492. // If all optimizations were done, move to next level
  25493. if (allDone) {
  25494. currentPriorityLevel++;
  25495. }
  25496. // Let's the system running for a specific amount of time before checking FPS
  25497. scene.executeWhenReady(function () {
  25498. setTimeout(function () {
  25499. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  25500. }, options.trackerDuration);
  25501. });
  25502. };
  25503. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  25504. if (!options) {
  25505. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  25506. }
  25507. // Let's the system running for a specific amount of time before checking FPS
  25508. scene.executeWhenReady(function () {
  25509. setTimeout(function () {
  25510. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  25511. }, options.trackerDuration);
  25512. });
  25513. };
  25514. return SceneOptimizer;
  25515. })();
  25516. BABYLON.SceneOptimizer = SceneOptimizer;
  25517. })(BABYLON || (BABYLON = {}));
  25518. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  25519. (function (BABYLON) {
  25520. var Internals;
  25521. (function (Internals) {
  25522. var MeshLODLevel = (function () {
  25523. function MeshLODLevel(distance, mesh) {
  25524. this.distance = distance;
  25525. this.mesh = mesh;
  25526. }
  25527. return MeshLODLevel;
  25528. })();
  25529. Internals.MeshLODLevel = MeshLODLevel;
  25530. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25531. })(BABYLON || (BABYLON = {}));
  25532. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  25533. (function (BABYLON) {
  25534. var AudioEngine = (function () {
  25535. function AudioEngine() {
  25536. this.audioContext = null;
  25537. this.canUseWebAudio = false;
  25538. this.WarnedWebAudioUnsupported = false;
  25539. try {
  25540. if (typeof AudioContext !== 'undefined') {
  25541. this.audioContext = new AudioContext();
  25542. this.canUseWebAudio = true;
  25543. }
  25544. else if (typeof webkitAudioContext !== 'undefined') {
  25545. this.audioContext = new webkitAudioContext();
  25546. this.canUseWebAudio = true;
  25547. }
  25548. }
  25549. catch (e) {
  25550. this.canUseWebAudio = false;
  25551. BABYLON.Tools.Error("Web Audio: " + e.message);
  25552. }
  25553. // create a global volume gain node
  25554. if (this.canUseWebAudio) {
  25555. this.masterGain = this.audioContext.createGain();
  25556. this.masterGain.gain.value = 1;
  25557. this.masterGain.connect(this.audioContext.destination);
  25558. }
  25559. }
  25560. AudioEngine.prototype.dispose = function () {
  25561. if (this.canUseWebAudio) {
  25562. if (this._connectedAnalyser) {
  25563. this._connectedAnalyser.stopDebugCanvas();
  25564. this._connectedAnalyser.dispose();
  25565. this.masterGain.disconnect();
  25566. this.masterGain.connect(this.audioContext.destination);
  25567. this._connectedAnalyser = null;
  25568. }
  25569. this.masterGain.gain.value = 1;
  25570. }
  25571. this.WarnedWebAudioUnsupported = false;
  25572. };
  25573. AudioEngine.prototype.getGlobalVolume = function () {
  25574. if (this.canUseWebAudio) {
  25575. return this.masterGain.gain.value;
  25576. }
  25577. else {
  25578. return -1;
  25579. }
  25580. };
  25581. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  25582. if (this.canUseWebAudio) {
  25583. this.masterGain.gain.value = newVolume;
  25584. }
  25585. };
  25586. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  25587. if (this._connectedAnalyser) {
  25588. this._connectedAnalyser.stopDebugCanvas();
  25589. }
  25590. this._connectedAnalyser = analyser;
  25591. if (this.canUseWebAudio) {
  25592. this.masterGain.disconnect();
  25593. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  25594. }
  25595. };
  25596. return AudioEngine;
  25597. })();
  25598. BABYLON.AudioEngine = AudioEngine;
  25599. })(BABYLON || (BABYLON = {}));
  25600. //# sourceMappingURL=babylon.audioengine.js.mapvar BABYLON;
  25601. (function (BABYLON) {
  25602. var Sound = (function () {
  25603. /**
  25604. * Create a sound and attach it to a scene
  25605. * @param name Name of your sound
  25606. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  25607. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  25608. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  25609. */
  25610. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  25611. var _this = this;
  25612. this.autoplay = false;
  25613. this.loop = false;
  25614. this.useCustomAttenuation = false;
  25615. this.spatialSound = false;
  25616. this.refDistance = 1;
  25617. this.rolloffFactor = 1;
  25618. this.maxDistance = 100;
  25619. this.distanceModel = "linear";
  25620. this.panningModel = "HRTF";
  25621. this._playbackRate = 1;
  25622. this._startTime = 0;
  25623. this._startOffset = 0;
  25624. this._position = BABYLON.Vector3.Zero();
  25625. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  25626. this._volume = 1;
  25627. this._isLoaded = false;
  25628. this._isReadyToPlay = false;
  25629. this._isPlaying = false;
  25630. this._isDirectional = false;
  25631. // Used if you'd like to create a directional sound.
  25632. // If not set, the sound will be omnidirectional
  25633. this._coneInnerAngle = 360;
  25634. this._coneOuterAngle = 360;
  25635. this._coneOuterGain = 0;
  25636. this.name = name;
  25637. this._scene = scene;
  25638. this._readyToPlayCallback = readyToPlayCallback;
  25639. // Default custom attenuation function is a linear attenuation
  25640. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  25641. if (currentDistance < maxDistance) {
  25642. return currentVolume * (1 - currentDistance / maxDistance);
  25643. }
  25644. else {
  25645. return 0;
  25646. }
  25647. };
  25648. if (options) {
  25649. this.autoplay = options.autoplay || false;
  25650. this.loop = options.loop || false;
  25651. // if volume === 0, we need another way to check this option
  25652. if (options.volume !== undefined) {
  25653. this._volume = options.volume;
  25654. }
  25655. this.spatialSound = options.spatialSound || false;
  25656. this.maxDistance = options.maxDistance || 100;
  25657. this.useCustomAttenuation = options.useCustomAttenuation || false;
  25658. this.rolloffFactor = options.rolloffFactor || 1;
  25659. this.refDistance = options.refDistance || 1;
  25660. this.distanceModel = options.distanceModel || "linear";
  25661. this.panningModel = options.panningModel || "HRTF";
  25662. this._playbackRate = options.playbackRate || 1;
  25663. }
  25664. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25665. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  25666. this._soundGain.gain.value = this._volume;
  25667. this._inputAudioNode = this._soundGain;
  25668. this._ouputAudioNode = this._soundGain;
  25669. if (this.spatialSound) {
  25670. this._createSpatialParameters();
  25671. }
  25672. this._scene.mainSoundTrack.AddSound(this);
  25673. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  25674. if (urlOrArrayBuffer) {
  25675. // If it's an URL
  25676. if (typeof (urlOrArrayBuffer) === "string") {
  25677. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  25678. _this._soundLoaded(data);
  25679. }, null, null, true);
  25680. }
  25681. else {
  25682. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  25683. this._soundLoaded(urlOrArrayBuffer);
  25684. }
  25685. else {
  25686. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  25687. }
  25688. }
  25689. }
  25690. }
  25691. else {
  25692. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  25693. this._scene.mainSoundTrack.AddSound(this);
  25694. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  25695. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  25696. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  25697. }
  25698. }
  25699. }
  25700. Sound.prototype.dispose = function () {
  25701. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  25702. if (this._isPlaying) {
  25703. this.stop();
  25704. }
  25705. this._isReadyToPlay = false;
  25706. if (this.soundTrackId === -1) {
  25707. this._scene.mainSoundTrack.RemoveSound(this);
  25708. }
  25709. else {
  25710. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  25711. }
  25712. this._soundGain.disconnect();
  25713. this._soundSource.disconnect();
  25714. if (this._soundPanner) {
  25715. this._soundPanner.disconnect();
  25716. this._soundPanner = null;
  25717. }
  25718. this._audioBuffer = null;
  25719. this._soundGain = null;
  25720. this._soundSource = null;
  25721. if (this._connectedMesh) {
  25722. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  25723. this._connectedMesh = null;
  25724. }
  25725. }
  25726. };
  25727. Sound.prototype._soundLoaded = function (audioData) {
  25728. var _this = this;
  25729. this._isLoaded = true;
  25730. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  25731. _this._audioBuffer = buffer;
  25732. _this._isReadyToPlay = true;
  25733. if (_this.autoplay) {
  25734. _this.play();
  25735. }
  25736. if (_this._readyToPlayCallback) {
  25737. _this._readyToPlayCallback();
  25738. }
  25739. }, function (error) {
  25740. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  25741. });
  25742. };
  25743. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  25744. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25745. this._audioBuffer = audioBuffer;
  25746. this._isReadyToPlay = true;
  25747. }
  25748. };
  25749. Sound.prototype.updateOptions = function (options) {
  25750. if (options) {
  25751. this.loop = options.loop || this.loop;
  25752. this.maxDistance = options.maxDistance || this.maxDistance;
  25753. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  25754. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  25755. this.refDistance = options.refDistance || this.refDistance;
  25756. this.distanceModel = options.distanceModel || this.distanceModel;
  25757. this.panningModel = options.panningModel || this.panningModel;
  25758. this._playbackRate = options.playbackRate || this._playbackRate;
  25759. }
  25760. };
  25761. Sound.prototype._createSpatialParameters = function () {
  25762. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25763. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  25764. if (this.useCustomAttenuation) {
  25765. // Tricks to disable in a way embedded Web Audio attenuation
  25766. this._soundPanner.distanceModel = "linear";
  25767. this._soundPanner.maxDistance = Number.MAX_VALUE;
  25768. this._soundPanner.refDistance = 1;
  25769. this._soundPanner.rolloffFactor = 1;
  25770. this._soundPanner.panningModel = "HRTF";
  25771. }
  25772. else {
  25773. this._soundPanner.distanceModel = this.distanceModel;
  25774. this._soundPanner.maxDistance = this.maxDistance;
  25775. this._soundPanner.refDistance = this.refDistance;
  25776. this._soundPanner.rolloffFactor = this.rolloffFactor;
  25777. this._soundPanner.panningModel = this.panningModel;
  25778. }
  25779. this._soundPanner.connect(this._ouputAudioNode);
  25780. this._inputAudioNode = this._soundPanner;
  25781. }
  25782. };
  25783. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  25784. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25785. this._ouputAudioNode.disconnect();
  25786. this._ouputAudioNode.connect(soundTrackAudioNode);
  25787. }
  25788. };
  25789. /**
  25790. * Transform this sound into a directional source
  25791. * @param coneInnerAngle Size of the inner cone in degree
  25792. * @param coneOuterAngle Size of the outer cone in degree
  25793. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  25794. */
  25795. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25796. if (coneOuterAngle < coneInnerAngle) {
  25797. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  25798. return;
  25799. }
  25800. this._coneInnerAngle = coneInnerAngle;
  25801. this._coneOuterAngle = coneOuterAngle;
  25802. this._coneOuterGain = coneOuterGain;
  25803. this._isDirectional = true;
  25804. if (this._isPlaying && this.loop) {
  25805. this.stop();
  25806. this.play();
  25807. }
  25808. };
  25809. Sound.prototype.setPosition = function (newPosition) {
  25810. this._position = newPosition;
  25811. if (this._isPlaying && this.spatialSound) {
  25812. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25813. }
  25814. };
  25815. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  25816. this._localDirection = newLocalDirection;
  25817. if (this._connectedMesh && this._isPlaying) {
  25818. this._updateDirection();
  25819. }
  25820. };
  25821. Sound.prototype._updateDirection = function () {
  25822. var mat = this._connectedMesh.getWorldMatrix();
  25823. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  25824. direction.normalize();
  25825. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  25826. };
  25827. Sound.prototype.updateDistanceFromListener = function () {
  25828. if (this._connectedMesh && this.useCustomAttenuation) {
  25829. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  25830. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  25831. }
  25832. };
  25833. Sound.prototype.setAttenuationFunction = function (callback) {
  25834. this._customAttenuationFunction = callback;
  25835. };
  25836. /**
  25837. * Play the sound
  25838. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  25839. */
  25840. Sound.prototype.play = function (time) {
  25841. if (this._isReadyToPlay) {
  25842. try {
  25843. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : 0;
  25844. if (!this._soundSource) {
  25845. if (this.spatialSound) {
  25846. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25847. if (this._isDirectional) {
  25848. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  25849. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  25850. this._soundPanner.coneOuterGain = this._coneOuterGain;
  25851. if (this._connectedMesh) {
  25852. this._updateDirection();
  25853. }
  25854. else {
  25855. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  25856. }
  25857. }
  25858. }
  25859. }
  25860. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  25861. this._soundSource.buffer = this._audioBuffer;
  25862. this._soundSource.connect(this._inputAudioNode);
  25863. this._soundSource.loop = this.loop;
  25864. this._soundSource.playbackRate.value = this._playbackRate;
  25865. this._startTime = startTime;
  25866. if (this.onended) {
  25867. this._soundSource.onended = this.onended;
  25868. }
  25869. this._soundSource.start(startTime, this._startOffset % this._soundSource.buffer.duration);
  25870. this._isPlaying = true;
  25871. }
  25872. catch (ex) {
  25873. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  25874. }
  25875. }
  25876. };
  25877. /**
  25878. * Stop the sound
  25879. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  25880. */
  25881. Sound.prototype.stop = function (time) {
  25882. if (this._isPlaying) {
  25883. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : 0;
  25884. this._soundSource.stop(stopTime);
  25885. this._isPlaying = false;
  25886. }
  25887. };
  25888. Sound.prototype.pause = function () {
  25889. if (this._isPlaying) {
  25890. this._soundSource.stop(0);
  25891. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  25892. }
  25893. };
  25894. Sound.prototype.setVolume = function (newVolume, time) {
  25895. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25896. if (time) {
  25897. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  25898. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  25899. }
  25900. else {
  25901. this._soundGain.gain.value = newVolume;
  25902. }
  25903. }
  25904. this._volume = newVolume;
  25905. };
  25906. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  25907. this._playbackRate = newPlaybackRate;
  25908. if (this._isPlaying) {
  25909. this._soundSource.playbackRate.value = this._playbackRate;
  25910. }
  25911. };
  25912. Sound.prototype.getVolume = function () {
  25913. return this._volume;
  25914. };
  25915. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  25916. var _this = this;
  25917. this._connectedMesh = meshToConnectTo;
  25918. if (!this.spatialSound) {
  25919. this._createSpatialParameters();
  25920. this.spatialSound = true;
  25921. if (this._isPlaying && this.loop) {
  25922. this.stop();
  25923. this.play();
  25924. }
  25925. }
  25926. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  25927. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  25928. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  25929. };
  25930. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  25931. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  25932. if (this._isDirectional && this._isPlaying) {
  25933. this._updateDirection();
  25934. }
  25935. };
  25936. return Sound;
  25937. })();
  25938. BABYLON.Sound = Sound;
  25939. })(BABYLON || (BABYLON = {}));
  25940. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  25941. (function (BABYLON) {
  25942. var SoundTrack = (function () {
  25943. function SoundTrack(scene, options) {
  25944. this.id = -1;
  25945. this._isMainTrack = false;
  25946. this._scene = scene;
  25947. this._audioEngine = BABYLON.Engine.audioEngine;
  25948. this.soundCollection = new Array();
  25949. if (this._audioEngine.canUseWebAudio) {
  25950. this._trackGain = this._audioEngine.audioContext.createGain();
  25951. this._trackGain.connect(this._audioEngine.masterGain);
  25952. if (options) {
  25953. if (options.volume) {
  25954. this._trackGain.gain.value = options.volume;
  25955. }
  25956. if (options.mainTrack) {
  25957. this._isMainTrack = options.mainTrack;
  25958. }
  25959. }
  25960. }
  25961. if (!this._isMainTrack) {
  25962. this._scene.soundTracks.push(this);
  25963. this.id = this._scene.soundTracks.length - 1;
  25964. }
  25965. }
  25966. SoundTrack.prototype.dispose = function () {
  25967. if (this._audioEngine.canUseWebAudio) {
  25968. if (this._connectedAnalyser) {
  25969. this._connectedAnalyser.stopDebugCanvas();
  25970. }
  25971. while (this.soundCollection.length) {
  25972. this.soundCollection[0].dispose();
  25973. }
  25974. this._trackGain.disconnect();
  25975. this._trackGain = null;
  25976. }
  25977. };
  25978. SoundTrack.prototype.AddSound = function (sound) {
  25979. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25980. sound.connectToSoundTrackAudioNode(this._trackGain);
  25981. }
  25982. if (sound.soundTrackId) {
  25983. if (sound.soundTrackId === -1) {
  25984. this._scene.mainSoundTrack.RemoveSound(sound);
  25985. }
  25986. else {
  25987. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  25988. }
  25989. }
  25990. this.soundCollection.push(sound);
  25991. sound.soundTrackId = this.id;
  25992. };
  25993. SoundTrack.prototype.RemoveSound = function (sound) {
  25994. var index = this.soundCollection.indexOf(sound);
  25995. if (index !== -1) {
  25996. this.soundCollection.splice(index, 1);
  25997. }
  25998. };
  25999. SoundTrack.prototype.setVolume = function (newVolume) {
  26000. if (this._audioEngine.canUseWebAudio) {
  26001. this._trackGain.gain.value = newVolume;
  26002. }
  26003. };
  26004. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  26005. if (this._connectedAnalyser) {
  26006. this._connectedAnalyser.stopDebugCanvas();
  26007. }
  26008. this._connectedAnalyser = analyser;
  26009. if (this._audioEngine.canUseWebAudio) {
  26010. this._trackGain.disconnect();
  26011. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  26012. }
  26013. };
  26014. return SoundTrack;
  26015. })();
  26016. BABYLON.SoundTrack = SoundTrack;
  26017. })(BABYLON || (BABYLON = {}));
  26018. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  26019. (function (BABYLON) {
  26020. var DebugLayer = (function () {
  26021. function DebugLayer(scene) {
  26022. var _this = this;
  26023. this._enabled = false;
  26024. this._labelsEnabled = false;
  26025. this._displayStatistics = true;
  26026. this._displayTree = false;
  26027. this._displayLogs = false;
  26028. this._identityMatrix = BABYLON.Matrix.Identity();
  26029. this.axisRatio = 0.02;
  26030. this.accentColor = "orange";
  26031. this._scene = scene;
  26032. this._syncPositions = function () {
  26033. var engine = _this._scene.getEngine();
  26034. var canvasRect = engine.getRenderingCanvasClientRect();
  26035. if (_this._showUI) {
  26036. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26037. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26038. _this._statsDiv.style.width = "400px";
  26039. _this._statsDiv.style.height = "auto";
  26040. _this._statsSubsetDiv.style.maxHeight = "240px";
  26041. _this._optionsDiv.style.left = "0px";
  26042. _this._optionsDiv.style.top = "10px";
  26043. _this._optionsDiv.style.width = "200px";
  26044. _this._optionsDiv.style.height = "auto";
  26045. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26046. _this._logDiv.style.left = "0px";
  26047. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  26048. _this._logDiv.style.width = "600px";
  26049. _this._logDiv.style.height = "160px";
  26050. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  26051. _this._treeDiv.style.top = "10px";
  26052. _this._treeDiv.style.width = "300px";
  26053. _this._treeDiv.style.height = "auto";
  26054. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  26055. }
  26056. _this._globalDiv.style.left = canvasRect.left + "px";
  26057. _this._globalDiv.style.top = canvasRect.top + "px";
  26058. _this._drawingCanvas.style.left = "0px";
  26059. _this._drawingCanvas.style.top = "0px";
  26060. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  26061. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  26062. var devicePixelRatio = window.devicePixelRatio || 1;
  26063. var context = _this._drawingContext;
  26064. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  26065. _this._ratio = devicePixelRatio / backingStoreRatio;
  26066. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  26067. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  26068. };
  26069. this._onCanvasClick = function (evt) {
  26070. _this._clickPosition = {
  26071. x: evt.clientX * _this._ratio,
  26072. y: evt.clientY * _this._ratio
  26073. };
  26074. };
  26075. this._syncData = function () {
  26076. if (_this._showUI) {
  26077. if (_this._displayStatistics) {
  26078. _this._displayStats();
  26079. _this._statsDiv.style.display = "";
  26080. }
  26081. else {
  26082. _this._statsDiv.style.display = "none";
  26083. }
  26084. if (_this._displayLogs) {
  26085. _this._logDiv.style.display = "";
  26086. }
  26087. else {
  26088. _this._logDiv.style.display = "none";
  26089. }
  26090. if (_this._displayTree) {
  26091. _this._treeDiv.style.display = "";
  26092. if (_this._needToRefreshMeshesTree) {
  26093. _this._needToRefreshMeshesTree = false;
  26094. _this._refreshMeshesTreeContent();
  26095. }
  26096. }
  26097. else {
  26098. _this._treeDiv.style.display = "none";
  26099. }
  26100. }
  26101. if (_this._labelsEnabled || !_this._showUI) {
  26102. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  26103. var engine = _this._scene.getEngine();
  26104. var viewport = _this._scene.activeCamera.viewport;
  26105. var globalViewport = viewport.toGlobal(engine);
  26106. // Meshes
  26107. var meshes = _this._scene.getActiveMeshes();
  26108. for (var index = 0; index < meshes.length; index++) {
  26109. var mesh = meshes.data[index];
  26110. var position = mesh.getBoundingInfo().boundingSphere.center;
  26111. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  26112. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  26113. _this._renderAxis(projectedPosition, mesh, globalViewport);
  26114. }
  26115. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  26116. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  26117. mesh.renderOverlay = !mesh.renderOverlay;
  26118. }, function () {
  26119. return mesh.renderOverlay ? 'red' : 'black';
  26120. });
  26121. }
  26122. }
  26123. // Cameras
  26124. var cameras = _this._scene.cameras;
  26125. for (index = 0; index < cameras.length; index++) {
  26126. var camera = cameras[index];
  26127. if (camera === _this._scene.activeCamera) {
  26128. continue;
  26129. }
  26130. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  26131. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  26132. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  26133. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  26134. _this._scene.activeCamera = camera;
  26135. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  26136. }, function () {
  26137. return "purple";
  26138. });
  26139. }
  26140. }
  26141. // Lights
  26142. var lights = _this._scene.lights;
  26143. for (index = 0; index < lights.length; index++) {
  26144. var light = lights[index];
  26145. if (light.position) {
  26146. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  26147. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  26148. _this._renderLabel(light.name, projectedPosition, -20, function () {
  26149. light.setEnabled(!light.isEnabled());
  26150. }, function () {
  26151. return light.isEnabled() ? "orange" : "gray";
  26152. });
  26153. }
  26154. }
  26155. }
  26156. }
  26157. _this._clickPosition = undefined;
  26158. };
  26159. }
  26160. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  26161. while (this._treeSubsetDiv.hasChildNodes()) {
  26162. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  26163. }
  26164. // Add meshes
  26165. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  26166. sortedArray.sort(function (a, b) {
  26167. if (a.name === b.name) {
  26168. return 0;
  26169. }
  26170. return (a.name > b.name) ? 1 : -1;
  26171. });
  26172. for (var index = 0; index < sortedArray.length; index++) {
  26173. var mesh = sortedArray[index];
  26174. if (!mesh.isEnabled()) {
  26175. continue;
  26176. }
  26177. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  26178. m.isVisible = element.checked;
  26179. }, mesh);
  26180. }
  26181. };
  26182. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  26183. this._drawingContext.beginPath();
  26184. this._drawingContext.moveTo(zero.x, zero.y);
  26185. this._drawingContext.lineTo(unit.x, unit.y);
  26186. this._drawingContext.strokeStyle = color;
  26187. this._drawingContext.lineWidth = 4;
  26188. this._drawingContext.stroke();
  26189. this._drawingContext.font = "normal 14px Segoe UI";
  26190. this._drawingContext.fillStyle = color;
  26191. this._drawingContext.fillText(label, unitText.x, unitText.y);
  26192. };
  26193. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  26194. var position = mesh.getBoundingInfo().boundingSphere.center;
  26195. var worldMatrix = mesh.getWorldMatrix();
  26196. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._scene.getTransformMatrix());
  26197. var unit = (unprojectedVector.subtract(position)).length();
  26198. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26199. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26200. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  26201. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26202. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26203. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  26204. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26205. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26206. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  26207. };
  26208. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  26209. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  26210. this._drawingContext.font = "normal 12px Segoe UI";
  26211. var textMetrics = this._drawingContext.measureText(text);
  26212. var centerX = projectedPosition.x - textMetrics.width / 2;
  26213. var centerY = projectedPosition.y;
  26214. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  26215. onClick();
  26216. }
  26217. this._drawingContext.beginPath();
  26218. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  26219. this._drawingContext.fillStyle = getFillStyle();
  26220. this._drawingContext.globalAlpha = 0.5;
  26221. this._drawingContext.fill();
  26222. this._drawingContext.globalAlpha = 1.0;
  26223. this._drawingContext.strokeStyle = '#FFFFFF';
  26224. this._drawingContext.lineWidth = 1;
  26225. this._drawingContext.stroke();
  26226. this._drawingContext.fillStyle = "#FFFFFF";
  26227. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  26228. this._drawingContext.beginPath();
  26229. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  26230. this._drawingContext.fill();
  26231. }
  26232. };
  26233. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  26234. if (!this._clickPosition) {
  26235. return false;
  26236. }
  26237. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  26238. return false;
  26239. }
  26240. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  26241. return false;
  26242. }
  26243. return true;
  26244. };
  26245. DebugLayer.prototype.isVisible = function () {
  26246. return this._enabled;
  26247. };
  26248. DebugLayer.prototype.hide = function () {
  26249. if (!this._enabled) {
  26250. return;
  26251. }
  26252. this._enabled = false;
  26253. var engine = this._scene.getEngine();
  26254. this._scene.unregisterAfterRender(this._syncData);
  26255. document.body.removeChild(this._globalDiv);
  26256. window.removeEventListener("resize", this._syncPositions);
  26257. this._scene.forceShowBoundingBoxes = false;
  26258. this._scene.forceWireframe = false;
  26259. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  26260. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  26261. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  26262. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  26263. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  26264. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  26265. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  26266. this._scene.shadowsEnabled = true;
  26267. this._scene.particlesEnabled = true;
  26268. this._scene.postProcessesEnabled = true;
  26269. this._scene.collisionsEnabled = true;
  26270. this._scene.lightsEnabled = true;
  26271. this._scene.texturesEnabled = true;
  26272. this._scene.lensFlaresEnabled = true;
  26273. this._scene.proceduralTexturesEnabled = true;
  26274. this._scene.renderTargetsEnabled = true;
  26275. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  26276. };
  26277. DebugLayer.prototype.show = function (showUI) {
  26278. if (showUI === void 0) { showUI = true; }
  26279. if (this._enabled) {
  26280. return;
  26281. }
  26282. this._enabled = true;
  26283. this._showUI = showUI;
  26284. var engine = this._scene.getEngine();
  26285. this._globalDiv = document.createElement("div");
  26286. document.body.appendChild(this._globalDiv);
  26287. this._generateDOMelements();
  26288. window.addEventListener("resize", this._syncPositions);
  26289. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  26290. this._syncPositions();
  26291. this._scene.registerAfterRender(this._syncData);
  26292. };
  26293. DebugLayer.prototype._clearLabels = function () {
  26294. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  26295. for (var index = 0; index < this._scene.meshes.length; index++) {
  26296. var mesh = this._scene.meshes[index];
  26297. mesh.renderOverlay = false;
  26298. }
  26299. };
  26300. DebugLayer.prototype._generateheader = function (root, text) {
  26301. var header = document.createElement("div");
  26302. header.innerHTML = text + "&nbsp;";
  26303. header.style.textAlign = "right";
  26304. header.style.width = "100%";
  26305. header.style.color = "white";
  26306. header.style.backgroundColor = "Black";
  26307. header.style.padding = "5px 5px 4px 0px";
  26308. header.style.marginLeft = "-5px";
  26309. header.style.fontWeight = "bold";
  26310. root.appendChild(header);
  26311. };
  26312. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  26313. var label = document.createElement("label");
  26314. label.innerHTML = title;
  26315. label.style.color = color;
  26316. root.appendChild(label);
  26317. root.appendChild(document.createElement("br"));
  26318. };
  26319. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  26320. if (tag === void 0) { tag = null; }
  26321. var label = document.createElement("label");
  26322. var boundingBoxesCheckbox = document.createElement("input");
  26323. boundingBoxesCheckbox.type = "checkbox";
  26324. boundingBoxesCheckbox.checked = initialState;
  26325. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26326. task(evt.target, tag);
  26327. });
  26328. label.appendChild(boundingBoxesCheckbox);
  26329. var container = document.createElement("span");
  26330. var leftPart = document.createElement("span");
  26331. var rightPart = document.createElement("span");
  26332. rightPart.style.cssFloat = "right";
  26333. leftPart.innerHTML = leftTitle;
  26334. rightPart.innerHTML = rightTitle;
  26335. rightPart.style.fontSize = "12px";
  26336. rightPart.style.maxWidth = "200px";
  26337. container.appendChild(leftPart);
  26338. container.appendChild(rightPart);
  26339. label.appendChild(container);
  26340. root.appendChild(label);
  26341. root.appendChild(document.createElement("br"));
  26342. };
  26343. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  26344. if (tag === void 0) { tag = null; }
  26345. var label = document.createElement("label");
  26346. var boundingBoxesCheckbox = document.createElement("input");
  26347. boundingBoxesCheckbox.type = "checkbox";
  26348. boundingBoxesCheckbox.checked = initialState;
  26349. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26350. task(evt.target, tag);
  26351. });
  26352. label.appendChild(boundingBoxesCheckbox);
  26353. label.appendChild(document.createTextNode(title));
  26354. root.appendChild(label);
  26355. root.appendChild(document.createElement("br"));
  26356. };
  26357. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  26358. if (tag === void 0) { tag = null; }
  26359. var label = document.createElement("label");
  26360. var boundingBoxesRadio = document.createElement("input");
  26361. boundingBoxesRadio.type = "radio";
  26362. boundingBoxesRadio.name = name;
  26363. boundingBoxesRadio.checked = initialState;
  26364. boundingBoxesRadio.addEventListener("change", function (evt) {
  26365. task(evt.target, tag);
  26366. });
  26367. label.appendChild(boundingBoxesRadio);
  26368. label.appendChild(document.createTextNode(title));
  26369. root.appendChild(label);
  26370. root.appendChild(document.createElement("br"));
  26371. };
  26372. DebugLayer.prototype._generateDOMelements = function () {
  26373. var _this = this;
  26374. this._globalDiv.id = "DebugLayer";
  26375. this._globalDiv.style.position = "absolute";
  26376. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  26377. this._globalDiv.style.fontSize = "14px";
  26378. this._globalDiv.style.color = "white";
  26379. // Drawing canvas
  26380. this._drawingCanvas = document.createElement("canvas");
  26381. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  26382. this._drawingCanvas.style.position = "absolute";
  26383. this._drawingCanvas.style.pointerEvents = "none";
  26384. this._drawingContext = this._drawingCanvas.getContext("2d");
  26385. this._globalDiv.appendChild(this._drawingCanvas);
  26386. if (this._showUI) {
  26387. var background = "rgba(128, 128, 128, 0.4)";
  26388. var border = "rgb(180, 180, 180) solid 1px";
  26389. // Stats
  26390. this._statsDiv = document.createElement("div");
  26391. this._statsDiv.id = "DebugLayerStats";
  26392. this._statsDiv.style.border = border;
  26393. this._statsDiv.style.position = "absolute";
  26394. this._statsDiv.style.background = background;
  26395. this._statsDiv.style.padding = "0px 0px 0px 5px";
  26396. this._generateheader(this._statsDiv, "STATISTICS");
  26397. this._statsSubsetDiv = document.createElement("div");
  26398. this._statsSubsetDiv.style.paddingTop = "5px";
  26399. this._statsSubsetDiv.style.paddingBottom = "5px";
  26400. this._statsSubsetDiv.style.overflowY = "auto";
  26401. this._statsDiv.appendChild(this._statsSubsetDiv);
  26402. // Tree
  26403. this._treeDiv = document.createElement("div");
  26404. this._treeDiv.id = "DebugLayerTree";
  26405. this._treeDiv.style.border = border;
  26406. this._treeDiv.style.position = "absolute";
  26407. this._treeDiv.style.background = background;
  26408. this._treeDiv.style.padding = "0px 0px 0px 5px";
  26409. this._treeDiv.style.display = "none";
  26410. this._generateheader(this._treeDiv, "MESHES TREE");
  26411. this._treeSubsetDiv = document.createElement("div");
  26412. this._treeSubsetDiv.style.paddingTop = "5px";
  26413. this._treeSubsetDiv.style.paddingRight = "5px";
  26414. this._treeSubsetDiv.style.overflowY = "auto";
  26415. this._treeSubsetDiv.style.maxHeight = "300px";
  26416. this._treeDiv.appendChild(this._treeSubsetDiv);
  26417. this._needToRefreshMeshesTree = true;
  26418. // Logs
  26419. this._logDiv = document.createElement("div");
  26420. this._logDiv.style.border = border;
  26421. this._logDiv.id = "DebugLayerLogs";
  26422. this._logDiv.style.position = "absolute";
  26423. this._logDiv.style.background = background;
  26424. this._logDiv.style.padding = "0px 0px 0px 5px";
  26425. this._logDiv.style.display = "none";
  26426. this._generateheader(this._logDiv, "LOGS");
  26427. this._logSubsetDiv = document.createElement("div");
  26428. this._logSubsetDiv.style.height = "127px";
  26429. this._logSubsetDiv.style.paddingTop = "5px";
  26430. this._logSubsetDiv.style.overflowY = "auto";
  26431. this._logSubsetDiv.style.fontSize = "12px";
  26432. this._logSubsetDiv.style.fontFamily = "consolas";
  26433. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  26434. this._logDiv.appendChild(this._logSubsetDiv);
  26435. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  26436. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  26437. };
  26438. // Options
  26439. this._optionsDiv = document.createElement("div");
  26440. this._optionsDiv.id = "DebugLayerOptions";
  26441. this._optionsDiv.style.border = border;
  26442. this._optionsDiv.style.position = "absolute";
  26443. this._optionsDiv.style.background = background;
  26444. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  26445. this._optionsDiv.style.overflowY = "auto";
  26446. this._generateheader(this._optionsDiv, "OPTIONS");
  26447. this._optionsSubsetDiv = document.createElement("div");
  26448. this._optionsSubsetDiv.style.paddingTop = "5px";
  26449. this._optionsSubsetDiv.style.paddingBottom = "5px";
  26450. this._optionsSubsetDiv.style.overflowY = "auto";
  26451. this._optionsSubsetDiv.style.maxHeight = "200px";
  26452. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  26453. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  26454. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  26455. _this._displayStatistics = element.checked;
  26456. });
  26457. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  26458. _this._displayLogs = element.checked;
  26459. });
  26460. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  26461. _this._displayTree = element.checked;
  26462. _this._needToRefreshMeshesTree = true;
  26463. });
  26464. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26465. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  26466. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  26467. _this._scene.forceShowBoundingBoxes = element.checked;
  26468. });
  26469. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  26470. _this._labelsEnabled = element.checked;
  26471. if (!_this._labelsEnabled) {
  26472. _this._clearLabels();
  26473. }
  26474. });
  26475. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  26476. if (element.checked) {
  26477. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  26478. }
  26479. else {
  26480. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  26481. }
  26482. });
  26483. ;
  26484. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26485. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  26486. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  26487. if (element.checked) {
  26488. _this._scene.forceWireframe = false;
  26489. _this._scene.forcePointsCloud = false;
  26490. }
  26491. });
  26492. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  26493. if (element.checked) {
  26494. _this._scene.forceWireframe = true;
  26495. _this._scene.forcePointsCloud = false;
  26496. }
  26497. });
  26498. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  26499. if (element.checked) {
  26500. _this._scene.forceWireframe = false;
  26501. _this._scene.forcePointsCloud = true;
  26502. }
  26503. });
  26504. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26505. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  26506. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  26507. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  26508. });
  26509. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  26510. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  26511. });
  26512. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  26513. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  26514. });
  26515. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  26516. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  26517. });
  26518. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  26519. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  26520. });
  26521. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  26522. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  26523. });
  26524. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  26525. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  26526. });
  26527. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  26528. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  26529. });
  26530. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26531. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  26532. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  26533. _this._scene.animationsEnabled = element.checked;
  26534. });
  26535. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  26536. _this._scene.collisionsEnabled = element.checked;
  26537. });
  26538. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  26539. _this._scene.fogEnabled = element.checked;
  26540. });
  26541. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  26542. _this._scene.lensFlaresEnabled = element.checked;
  26543. });
  26544. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  26545. _this._scene.lightsEnabled = element.checked;
  26546. });
  26547. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  26548. _this._scene.particlesEnabled = element.checked;
  26549. });
  26550. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  26551. _this._scene.postProcessesEnabled = element.checked;
  26552. });
  26553. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  26554. _this._scene.proceduralTexturesEnabled = element.checked;
  26555. });
  26556. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  26557. _this._scene.renderTargetsEnabled = element.checked;
  26558. });
  26559. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  26560. _this._scene.shadowsEnabled = element.checked;
  26561. });
  26562. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  26563. _this._scene.skeletonsEnabled = element.checked;
  26564. });
  26565. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  26566. _this._scene.texturesEnabled = element.checked;
  26567. });
  26568. this._globalDiv.appendChild(this._statsDiv);
  26569. this._globalDiv.appendChild(this._logDiv);
  26570. this._globalDiv.appendChild(this._optionsDiv);
  26571. this._globalDiv.appendChild(this._treeDiv);
  26572. }
  26573. };
  26574. DebugLayer.prototype._displayStats = function () {
  26575. var scene = this._scene;
  26576. var engine = scene.getEngine();
  26577. var glInfo = engine.getGlInfo();
  26578. 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>";
  26579. if (this.customStatsFunction) {
  26580. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  26581. }
  26582. };
  26583. return DebugLayer;
  26584. })();
  26585. BABYLON.DebugLayer = DebugLayer;
  26586. })(BABYLON || (BABYLON = {}));
  26587. //# sourceMappingURL=babylon.debugLayer.js.map
  26588. var BABYLON;
  26589. (function (BABYLON) {
  26590. var RawTexture = (function (_super) {
  26591. __extends(RawTexture, _super);
  26592. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  26593. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26594. if (invertY === void 0) { invertY = false; }
  26595. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26596. _super.call(this, null, scene, !generateMipMaps, invertY);
  26597. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  26598. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26599. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26600. }
  26601. // Statics
  26602. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26603. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26604. if (invertY === void 0) { invertY = false; }
  26605. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26606. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  26607. };
  26608. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26609. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26610. if (invertY === void 0) { invertY = false; }
  26611. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26612. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26613. };
  26614. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26615. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26616. if (invertY === void 0) { invertY = false; }
  26617. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26618. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26619. };
  26620. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26621. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26622. if (invertY === void 0) { invertY = false; }
  26623. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26624. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  26625. };
  26626. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26627. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26628. if (invertY === void 0) { invertY = false; }
  26629. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26630. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  26631. };
  26632. return RawTexture;
  26633. })(BABYLON.Texture);
  26634. BABYLON.RawTexture = RawTexture;
  26635. })(BABYLON || (BABYLON = {}));
  26636. //# sourceMappingURL=babylon.rawTexture.js.map
  26637. var BABYLON;
  26638. (function (BABYLON) {
  26639. var IndexedVector2 = (function (_super) {
  26640. __extends(IndexedVector2, _super);
  26641. function IndexedVector2(original, index) {
  26642. _super.call(this, original.x, original.y);
  26643. this.index = index;
  26644. }
  26645. return IndexedVector2;
  26646. })(BABYLON.Vector2);
  26647. var PolygonPoints = (function () {
  26648. function PolygonPoints() {
  26649. this.elements = new Array();
  26650. }
  26651. PolygonPoints.prototype.add = function (originalPoints) {
  26652. var _this = this;
  26653. var result = new Array();
  26654. originalPoints.forEach(function (point) {
  26655. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  26656. var newPoint = new IndexedVector2(point, _this.elements.length);
  26657. result.push(newPoint);
  26658. _this.elements.push(newPoint);
  26659. }
  26660. });
  26661. return result;
  26662. };
  26663. PolygonPoints.prototype.computeBounds = function () {
  26664. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  26665. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  26666. this.elements.forEach(function (point) {
  26667. // x
  26668. if (point.x < lmin.x) {
  26669. lmin.x = point.x;
  26670. }
  26671. else if (point.x > lmax.x) {
  26672. lmax.x = point.x;
  26673. }
  26674. // y
  26675. if (point.y < lmin.y) {
  26676. lmin.y = point.y;
  26677. }
  26678. else if (point.y > lmax.y) {
  26679. lmax.y = point.y;
  26680. }
  26681. });
  26682. return {
  26683. min: lmin,
  26684. max: lmax,
  26685. width: lmax.x - lmin.x,
  26686. height: lmax.y - lmin.y
  26687. };
  26688. };
  26689. return PolygonPoints;
  26690. })();
  26691. var Polygon = (function () {
  26692. function Polygon() {
  26693. }
  26694. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  26695. return [
  26696. new BABYLON.Vector2(xmin, ymin),
  26697. new BABYLON.Vector2(xmax, ymin),
  26698. new BABYLON.Vector2(xmax, ymax),
  26699. new BABYLON.Vector2(xmin, ymax)
  26700. ];
  26701. };
  26702. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  26703. if (cx === void 0) { cx = 0; }
  26704. if (cy === void 0) { cy = 0; }
  26705. if (numberOfSides === void 0) { numberOfSides = 32; }
  26706. var result = new Array();
  26707. var angle = 0;
  26708. var increment = (Math.PI * 2) / numberOfSides;
  26709. for (var i = 0; i < numberOfSides; i++) {
  26710. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  26711. angle -= increment;
  26712. }
  26713. return result;
  26714. };
  26715. Polygon.Parse = function (input) {
  26716. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  26717. var i, result = [];
  26718. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  26719. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  26720. }
  26721. return result;
  26722. };
  26723. Polygon.StartingAt = function (x, y) {
  26724. return BABYLON.Path2.StartingAt(x, y);
  26725. };
  26726. return Polygon;
  26727. })();
  26728. BABYLON.Polygon = Polygon;
  26729. var PolygonMeshBuilder = (function () {
  26730. function PolygonMeshBuilder(name, contours, scene) {
  26731. this._points = new PolygonPoints();
  26732. if (!("poly2tri" in window)) {
  26733. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  26734. }
  26735. this._name = name;
  26736. this._scene = scene;
  26737. var points;
  26738. if (contours instanceof BABYLON.Path2) {
  26739. points = contours.getPoints();
  26740. }
  26741. else {
  26742. points = contours;
  26743. }
  26744. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  26745. }
  26746. PolygonMeshBuilder.prototype.addHole = function (hole) {
  26747. this._swctx.addHole(this._points.add(hole));
  26748. return this;
  26749. };
  26750. PolygonMeshBuilder.prototype.build = function (updatable) {
  26751. if (updatable === void 0) { updatable = false; }
  26752. var result = new BABYLON.Mesh(this._name, this._scene);
  26753. var normals = [];
  26754. var positions = [];
  26755. var uvs = [];
  26756. var bounds = this._points.computeBounds();
  26757. this._points.elements.forEach(function (p) {
  26758. normals.push(0, 1.0, 0);
  26759. positions.push(p.x, 0, p.y);
  26760. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  26761. });
  26762. var indices = [];
  26763. this._swctx.triangulate();
  26764. this._swctx.getTriangles().forEach(function (triangle) {
  26765. triangle.getPoints().forEach(function (point) {
  26766. indices.push(point.index);
  26767. });
  26768. });
  26769. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  26770. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  26771. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  26772. result.setIndices(indices);
  26773. return result;
  26774. };
  26775. return PolygonMeshBuilder;
  26776. })();
  26777. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  26778. })(BABYLON || (BABYLON = {}));
  26779. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  26780. (function (BABYLON) {
  26781. var SimplificationSettings = (function () {
  26782. function SimplificationSettings(quality, distance) {
  26783. this.quality = quality;
  26784. this.distance = distance;
  26785. }
  26786. return SimplificationSettings;
  26787. })();
  26788. BABYLON.SimplificationSettings = SimplificationSettings;
  26789. /**
  26790. * The implemented types of simplification.
  26791. * At the moment only Quadratic Error Decimation is implemented.
  26792. */
  26793. (function (SimplificationType) {
  26794. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  26795. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  26796. var SimplificationType = BABYLON.SimplificationType;
  26797. var DecimationTriangle = (function () {
  26798. function DecimationTriangle(vertices) {
  26799. this.vertices = vertices;
  26800. this.error = new Array(4);
  26801. this.deleted = false;
  26802. this.isDirty = false;
  26803. this.borderFactor = 0;
  26804. }
  26805. return DecimationTriangle;
  26806. })();
  26807. BABYLON.DecimationTriangle = DecimationTriangle;
  26808. var DecimationVertex = (function () {
  26809. function DecimationVertex(position, normal, uv, id) {
  26810. this.position = position;
  26811. this.normal = normal;
  26812. this.uv = uv;
  26813. this.id = id;
  26814. this.isBorder = true;
  26815. this.q = new QuadraticMatrix();
  26816. this.triangleCount = 0;
  26817. this.triangleStart = 0;
  26818. }
  26819. return DecimationVertex;
  26820. })();
  26821. BABYLON.DecimationVertex = DecimationVertex;
  26822. var QuadraticMatrix = (function () {
  26823. function QuadraticMatrix(data) {
  26824. this.data = new Array(10);
  26825. for (var i = 0; i < 10; ++i) {
  26826. if (data && data[i]) {
  26827. this.data[i] = data[i];
  26828. }
  26829. else {
  26830. this.data[i] = 0;
  26831. }
  26832. }
  26833. }
  26834. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  26835. 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];
  26836. return det;
  26837. };
  26838. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  26839. for (var i = 0; i < 10; ++i) {
  26840. this.data[i] += matrix.data[i];
  26841. }
  26842. };
  26843. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  26844. for (var i = 0; i < 10; ++i) {
  26845. this.data[i] += data[i];
  26846. }
  26847. };
  26848. QuadraticMatrix.prototype.add = function (matrix) {
  26849. var m = new QuadraticMatrix();
  26850. for (var i = 0; i < 10; ++i) {
  26851. m.data[i] = this.data[i] + matrix.data[i];
  26852. }
  26853. return m;
  26854. };
  26855. QuadraticMatrix.FromData = function (a, b, c, d) {
  26856. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  26857. };
  26858. //returning an array to avoid garbage collection
  26859. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  26860. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  26861. };
  26862. return QuadraticMatrix;
  26863. })();
  26864. BABYLON.QuadraticMatrix = QuadraticMatrix;
  26865. var Reference = (function () {
  26866. function Reference(vertexId, triangleId) {
  26867. this.vertexId = vertexId;
  26868. this.triangleId = triangleId;
  26869. }
  26870. return Reference;
  26871. })();
  26872. BABYLON.Reference = Reference;
  26873. /**
  26874. * An implementation of the Quadratic Error simplification algorithm.
  26875. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  26876. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  26877. * @author RaananW
  26878. */
  26879. var QuadraticErrorSimplification = (function () {
  26880. function QuadraticErrorSimplification(_mesh) {
  26881. this._mesh = _mesh;
  26882. this.initialised = false;
  26883. this.syncIterations = 5000;
  26884. this.aggressiveness = 7;
  26885. this.decimationIterations = 100;
  26886. }
  26887. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  26888. var _this = this;
  26889. this.initWithMesh(this._mesh, function () {
  26890. _this.runDecimation(settings, successCallback);
  26891. });
  26892. };
  26893. QuadraticErrorSimplification.prototype.runDecimation = function (settings, successCallback) {
  26894. var _this = this;
  26895. var targetCount = ~~(this.triangles.length * settings.quality);
  26896. var deletedTriangles = 0;
  26897. var triangleCount = this.triangles.length;
  26898. var iterationFunction = function (iteration, callback) {
  26899. setTimeout(function () {
  26900. if (iteration % 5 === 0) {
  26901. _this.updateMesh(iteration === 0);
  26902. }
  26903. for (var i = 0; i < _this.triangles.length; ++i) {
  26904. _this.triangles[i].isDirty = false;
  26905. }
  26906. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  26907. var trianglesIterator = function (i) {
  26908. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  26909. var t = _this.triangles[tIdx];
  26910. if (!t)
  26911. return;
  26912. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  26913. return;
  26914. }
  26915. for (var j = 0; j < 3; ++j) {
  26916. if (t.error[j] < threshold) {
  26917. var deleted0 = [];
  26918. var deleted1 = [];
  26919. var i0 = t.vertices[j];
  26920. var i1 = t.vertices[(j + 1) % 3];
  26921. var v0 = _this.vertices[i0];
  26922. var v1 = _this.vertices[i1];
  26923. if (v0.isBorder !== v1.isBorder)
  26924. continue;
  26925. var p = BABYLON.Vector3.Zero();
  26926. var n = BABYLON.Vector3.Zero();
  26927. var uv = BABYLON.Vector2.Zero();
  26928. var color = new BABYLON.Color4(0, 0, 0, 1);
  26929. _this.calculateError(v0, v1, p, n, uv, color);
  26930. var delTr = [];
  26931. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  26932. continue;
  26933. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  26934. continue;
  26935. if (delTr.length == 2 || delTr[0] === delTr[1]) {
  26936. continue;
  26937. }
  26938. v0.normal = n;
  26939. if (v0.uv)
  26940. v0.uv = uv;
  26941. else if (v0.color)
  26942. v0.color = color;
  26943. v0.q = v1.q.add(v0.q);
  26944. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  26945. continue;
  26946. if (p.equals(v0.position))
  26947. continue;
  26948. v0.position = p;
  26949. var tStart = _this.references.length;
  26950. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  26951. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  26952. var tCount = _this.references.length - tStart;
  26953. if (tCount <= v0.triangleCount) {
  26954. if (tCount) {
  26955. for (var c = 0; c < tCount; c++) {
  26956. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  26957. }
  26958. }
  26959. }
  26960. else {
  26961. v0.triangleStart = tStart;
  26962. }
  26963. v0.triangleCount = tCount;
  26964. break;
  26965. }
  26966. }
  26967. };
  26968. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  26969. return (triangleCount - deletedTriangles <= targetCount);
  26970. });
  26971. }, 0);
  26972. };
  26973. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  26974. if (triangleCount - deletedTriangles <= targetCount)
  26975. loop.breakLoop();
  26976. else {
  26977. iterationFunction(loop.index, function () {
  26978. loop.executeNext();
  26979. });
  26980. }
  26981. }, function () {
  26982. setTimeout(function () {
  26983. successCallback(_this.reconstructMesh());
  26984. }, 0);
  26985. });
  26986. };
  26987. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, callback) {
  26988. var _this = this;
  26989. if (!mesh)
  26990. return;
  26991. this.vertices = [];
  26992. this.triangles = [];
  26993. this._mesh = mesh;
  26994. //It is assumed that a mesh has positions, normals and either uvs or colors.
  26995. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26996. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26997. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26998. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26999. var indices = mesh.getIndices();
  27000. var vertexInit = function (i) {
  27001. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), null, i);
  27002. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27003. vertex.uv = BABYLON.Vector2.FromArray(uvs, i * 2);
  27004. }
  27005. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27006. vertex.color = BABYLON.Color4.FromArray(colorsData, i * 4);
  27007. }
  27008. _this.vertices.push(vertex);
  27009. };
  27010. var totalVertices = mesh.getTotalVertices();
  27011. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  27012. var indicesInit = function (i) {
  27013. var pos = i * 3;
  27014. var i0 = indices[pos + 0];
  27015. var i1 = indices[pos + 1];
  27016. var i2 = indices[pos + 2];
  27017. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  27018. _this.triangles.push(triangle);
  27019. };
  27020. BABYLON.AsyncLoop.SyncAsyncForLoop(indices.length / 3, _this.syncIterations, indicesInit, function () {
  27021. _this.init(callback);
  27022. });
  27023. });
  27024. };
  27025. QuadraticErrorSimplification.prototype.init = function (callback) {
  27026. var _this = this;
  27027. var triangleInit1 = function (i) {
  27028. var t = _this.triangles[i];
  27029. 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();
  27030. for (var j = 0; j < 3; j++) {
  27031. _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))));
  27032. }
  27033. };
  27034. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  27035. var triangleInit2 = function (i) {
  27036. var t = _this.triangles[i];
  27037. for (var j = 0; j < 3; ++j) {
  27038. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  27039. }
  27040. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  27041. };
  27042. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  27043. _this.initialised = true;
  27044. callback();
  27045. });
  27046. });
  27047. };
  27048. QuadraticErrorSimplification.prototype.reconstructMesh = function () {
  27049. var newTriangles = [];
  27050. var i;
  27051. for (i = 0; i < this.vertices.length; ++i) {
  27052. this.vertices[i].triangleCount = 0;
  27053. }
  27054. var t;
  27055. var j;
  27056. for (i = 0; i < this.triangles.length; ++i) {
  27057. if (!this.triangles[i].deleted) {
  27058. t = this.triangles[i];
  27059. for (j = 0; j < 3; ++j) {
  27060. this.vertices[t.vertices[j]].triangleCount = 1;
  27061. }
  27062. newTriangles.push(t);
  27063. }
  27064. }
  27065. var newVerticesOrder = [];
  27066. //compact vertices, get the IDs of the vertices used.
  27067. var dst = 0;
  27068. for (i = 0; i < this.vertices.length; ++i) {
  27069. if (this.vertices[i].triangleCount) {
  27070. this.vertices[i].triangleStart = dst;
  27071. this.vertices[dst].position = this.vertices[i].position;
  27072. this.vertices[dst].normal = this.vertices[i].normal;
  27073. this.vertices[dst].uv = this.vertices[i].uv;
  27074. this.vertices[dst].color = this.vertices[i].color;
  27075. newVerticesOrder.push(i);
  27076. dst++;
  27077. }
  27078. }
  27079. for (i = 0; i < newTriangles.length; ++i) {
  27080. t = newTriangles[i];
  27081. for (j = 0; j < 3; ++j) {
  27082. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  27083. }
  27084. }
  27085. this.vertices = this.vertices.slice(0, dst);
  27086. var newPositionData = [];
  27087. var newNormalData = [];
  27088. var newUVsData = [];
  27089. var newColorsData = [];
  27090. for (i = 0; i < newVerticesOrder.length; ++i) {
  27091. newPositionData.push(this.vertices[i].position.x);
  27092. newPositionData.push(this.vertices[i].position.y);
  27093. newPositionData.push(this.vertices[i].position.z);
  27094. newNormalData.push(this.vertices[i].normal.x);
  27095. newNormalData.push(this.vertices[i].normal.y);
  27096. newNormalData.push(this.vertices[i].normal.z);
  27097. if (this.vertices[i].uv) {
  27098. newUVsData.push(this.vertices[i].uv.x);
  27099. newUVsData.push(this.vertices[i].uv.y);
  27100. }
  27101. else if (this.vertices[i].color) {
  27102. newColorsData.push(this.vertices[i].color.r);
  27103. newColorsData.push(this.vertices[i].color.g);
  27104. newColorsData.push(this.vertices[i].color.b);
  27105. newColorsData.push(this.vertices[i].color.a);
  27106. }
  27107. }
  27108. var newIndicesArray = [];
  27109. for (i = 0; i < newTriangles.length; ++i) {
  27110. newIndicesArray.push(newTriangles[i].vertices[0]);
  27111. newIndicesArray.push(newTriangles[i].vertices[1]);
  27112. newIndicesArray.push(newTriangles[i].vertices[2]);
  27113. }
  27114. //not cloning, to avoid geometry problems. Creating a whole new mesh.
  27115. var newMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  27116. newMesh.material = this._mesh.material;
  27117. newMesh.parent = this._mesh.parent;
  27118. newMesh.setIndices(newIndicesArray);
  27119. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  27120. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  27121. if (newUVsData.length > 0)
  27122. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  27123. if (newColorsData.length > 0)
  27124. newMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  27125. //preparing the skeleton support
  27126. if (this._mesh.skeleton) {
  27127. }
  27128. return newMesh;
  27129. };
  27130. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  27131. for (var i = 0; i < vertex1.triangleCount; ++i) {
  27132. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  27133. if (t.deleted)
  27134. continue;
  27135. var s = this.references[vertex1.triangleStart + i].vertexId;
  27136. var id1 = t.vertices[(s + 1) % 3];
  27137. var id2 = t.vertices[(s + 2) % 3];
  27138. if ((id1 === index2 || id2 === index2) && borderFactor < 2) {
  27139. deletedArray[i] = true;
  27140. delTr.push(t);
  27141. continue;
  27142. }
  27143. var d1 = this.vertices[id1].position.subtract(point);
  27144. d1 = d1.normalize();
  27145. var d2 = this.vertices[id2].position.subtract(point);
  27146. d2 = d2.normalize();
  27147. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  27148. return true;
  27149. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  27150. deletedArray[i] = false;
  27151. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  27152. return true;
  27153. }
  27154. return false;
  27155. };
  27156. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  27157. var newDeleted = deletedTriangles;
  27158. for (var i = 0; i < vertex.triangleCount; ++i) {
  27159. var ref = this.references[vertex.triangleStart + i];
  27160. var t = this.triangles[ref.triangleId];
  27161. if (t.deleted)
  27162. continue;
  27163. if (deletedArray[i]) {
  27164. t.deleted = true;
  27165. newDeleted++;
  27166. continue;
  27167. }
  27168. t.vertices[ref.vertexId] = vertexId;
  27169. t.isDirty = true;
  27170. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  27171. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  27172. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  27173. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  27174. this.references.push(ref);
  27175. }
  27176. return newDeleted;
  27177. };
  27178. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  27179. for (var i = 0; i < this.vertices.length; ++i) {
  27180. var vCount = [];
  27181. var vId = [];
  27182. var v = this.vertices[i];
  27183. var j;
  27184. for (j = 0; j < v.triangleCount; ++j) {
  27185. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  27186. for (var ii = 0; ii < 3; ii++) {
  27187. var ofs = 0;
  27188. var id = triangle.vertices[ii];
  27189. while (ofs < vCount.length) {
  27190. if (vId[ofs] === id)
  27191. break;
  27192. ++ofs;
  27193. }
  27194. if (ofs === vCount.length) {
  27195. vCount.push(1);
  27196. vId.push(id);
  27197. }
  27198. else {
  27199. vCount[ofs]++;
  27200. }
  27201. }
  27202. }
  27203. for (j = 0; j < vCount.length; ++j) {
  27204. if (vCount[j] === 1) {
  27205. this.vertices[vId[j]].isBorder = true;
  27206. }
  27207. else {
  27208. this.vertices[vId[j]].isBorder = false;
  27209. }
  27210. }
  27211. }
  27212. };
  27213. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  27214. if (identifyBorders === void 0) { identifyBorders = false; }
  27215. var i;
  27216. if (!identifyBorders) {
  27217. var newTrianglesVector = [];
  27218. for (i = 0; i < this.triangles.length; ++i) {
  27219. if (!this.triangles[i].deleted) {
  27220. newTrianglesVector.push(this.triangles[i]);
  27221. }
  27222. }
  27223. this.triangles = newTrianglesVector;
  27224. }
  27225. for (i = 0; i < this.vertices.length; ++i) {
  27226. this.vertices[i].triangleCount = 0;
  27227. this.vertices[i].triangleStart = 0;
  27228. }
  27229. var t;
  27230. var j;
  27231. var v;
  27232. for (i = 0; i < this.triangles.length; ++i) {
  27233. t = this.triangles[i];
  27234. for (j = 0; j < 3; ++j) {
  27235. v = this.vertices[t.vertices[j]];
  27236. v.triangleCount++;
  27237. }
  27238. }
  27239. var tStart = 0;
  27240. for (i = 0; i < this.vertices.length; ++i) {
  27241. this.vertices[i].triangleStart = tStart;
  27242. tStart += this.vertices[i].triangleCount;
  27243. this.vertices[i].triangleCount = 0;
  27244. }
  27245. var newReferences = new Array(this.triangles.length * 3);
  27246. for (i = 0; i < this.triangles.length; ++i) {
  27247. t = this.triangles[i];
  27248. for (j = 0; j < 3; ++j) {
  27249. v = this.vertices[t.vertices[j]];
  27250. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  27251. v.triangleCount++;
  27252. }
  27253. }
  27254. this.references = newReferences;
  27255. if (identifyBorders) {
  27256. this.identifyBorder();
  27257. }
  27258. };
  27259. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  27260. var x = point.x;
  27261. var y = point.y;
  27262. var z = point.z;
  27263. 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];
  27264. };
  27265. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  27266. var q = vertex1.q.add(vertex2.q);
  27267. var border = vertex1.isBorder && vertex2.isBorder;
  27268. var error = 0;
  27269. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  27270. if (qDet !== 0 && !border) {
  27271. if (!pointResult) {
  27272. pointResult = BABYLON.Vector3.Zero();
  27273. }
  27274. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  27275. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  27276. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  27277. error = this.vertexError(q, pointResult);
  27278. //TODO this should be correctly calculated
  27279. if (normalResult) {
  27280. normalResult.copyFrom(vertex1.normal);
  27281. if (vertex1.uv)
  27282. uvResult.copyFrom(vertex1.uv);
  27283. else if (vertex1.color)
  27284. colorResult.copyFrom(vertex1.color);
  27285. }
  27286. }
  27287. else {
  27288. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  27289. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  27290. var error1 = this.vertexError(q, vertex1.position);
  27291. var error2 = this.vertexError(q, vertex2.position);
  27292. var error3 = this.vertexError(q, p3);
  27293. error = Math.min(error1, error2, error3);
  27294. if (error === error1) {
  27295. if (pointResult) {
  27296. pointResult.copyFrom(vertex1.position);
  27297. normalResult.copyFrom(vertex1.normal);
  27298. if (vertex1.uv)
  27299. uvResult.copyFrom(vertex1.uv);
  27300. else if (vertex1.color)
  27301. colorResult.copyFrom(vertex1.color);
  27302. }
  27303. }
  27304. else if (error === error2) {
  27305. if (pointResult) {
  27306. pointResult.copyFrom(vertex2.position);
  27307. normalResult.copyFrom(vertex2.normal);
  27308. if (vertex2.uv)
  27309. uvResult.copyFrom(vertex2.uv);
  27310. else if (vertex2.color)
  27311. colorResult.copyFrom(vertex2.color);
  27312. }
  27313. }
  27314. else {
  27315. if (pointResult) {
  27316. pointResult.copyFrom(p3);
  27317. normalResult.copyFrom(vertex1.normal);
  27318. if (vertex1.uv)
  27319. uvResult.copyFrom(vertex1.uv);
  27320. else if (vertex1.color)
  27321. colorResult.copyFrom(vertex1.color);
  27322. }
  27323. }
  27324. }
  27325. return error;
  27326. };
  27327. return QuadraticErrorSimplification;
  27328. })();
  27329. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  27330. })(BABYLON || (BABYLON = {}));
  27331. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  27332. (function (BABYLON) {
  27333. var Analyser = (function () {
  27334. function Analyser(scene) {
  27335. this.SMOOTHING = 0.75;
  27336. this.FFT_SIZE = 512;
  27337. this.BARGRAPHAMPLITUDE = 256;
  27338. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  27339. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  27340. this._scene = scene;
  27341. this._audioEngine = BABYLON.Engine.audioEngine;
  27342. if (this._audioEngine.canUseWebAudio) {
  27343. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  27344. this._webAudioAnalyser.minDecibels = -140;
  27345. this._webAudioAnalyser.maxDecibels = 0;
  27346. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27347. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27348. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  27349. }
  27350. }
  27351. Analyser.prototype.getFrequencyBinCount = function () {
  27352. if (this._audioEngine.canUseWebAudio) {
  27353. return this._webAudioAnalyser.frequencyBinCount;
  27354. }
  27355. else {
  27356. return 0;
  27357. }
  27358. };
  27359. Analyser.prototype.getByteFrequencyData = function () {
  27360. if (this._audioEngine.canUseWebAudio) {
  27361. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27362. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27363. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  27364. }
  27365. return this._byteFreqs;
  27366. };
  27367. Analyser.prototype.getByteTimeDomainData = function () {
  27368. if (this._audioEngine.canUseWebAudio) {
  27369. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27370. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27371. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  27372. }
  27373. return this._byteTime;
  27374. };
  27375. Analyser.prototype.getFloatFrequencyData = function () {
  27376. if (this._audioEngine.canUseWebAudio) {
  27377. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27378. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27379. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  27380. }
  27381. return this._floatFreqs;
  27382. };
  27383. Analyser.prototype.drawDebugCanvas = function () {
  27384. var _this = this;
  27385. if (this._audioEngine.canUseWebAudio) {
  27386. if (!this._debugCanvas) {
  27387. this._debugCanvas = document.createElement("canvas");
  27388. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  27389. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  27390. this._debugCanvas.style.position = "absolute";
  27391. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  27392. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  27393. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  27394. document.body.appendChild(this._debugCanvas);
  27395. this._registerFunc = function () {
  27396. _this.drawDebugCanvas();
  27397. };
  27398. this._scene.registerBeforeRender(this._registerFunc);
  27399. }
  27400. if (this._registerFunc) {
  27401. var workingArray = this.getByteFrequencyData();
  27402. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  27403. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  27404. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  27405. var value = workingArray[i];
  27406. var percent = value / this.BARGRAPHAMPLITUDE;
  27407. var height = this.DEBUGCANVASSIZE.height * percent;
  27408. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  27409. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  27410. var hue = i / this.getFrequencyBinCount() * 360;
  27411. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  27412. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  27413. }
  27414. }
  27415. }
  27416. };
  27417. Analyser.prototype.stopDebugCanvas = function () {
  27418. if (this._debugCanvas) {
  27419. this._scene.unregisterBeforeRender(this._registerFunc);
  27420. this._registerFunc = null;
  27421. document.body.removeChild(this._debugCanvas);
  27422. this._debugCanvas = null;
  27423. this._debugCanvasContext = null;
  27424. }
  27425. };
  27426. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  27427. if (this._audioEngine.canUseWebAudio) {
  27428. inputAudioNode.connect(this._webAudioAnalyser);
  27429. this._webAudioAnalyser.connect(outputAudioNode);
  27430. }
  27431. };
  27432. Analyser.prototype.dispose = function () {
  27433. if (this._audioEngine.canUseWebAudio) {
  27434. this._webAudioAnalyser.disconnect();
  27435. }
  27436. };
  27437. return Analyser;
  27438. })();
  27439. BABYLON.Analyser = Analyser;
  27440. })(BABYLON || (BABYLON = {}));
  27441. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  27442. (function (BABYLON) {
  27443. var DepthRenderer = (function () {
  27444. function DepthRenderer(scene, type) {
  27445. var _this = this;
  27446. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  27447. this._viewMatrix = BABYLON.Matrix.Zero();
  27448. this._projectionMatrix = BABYLON.Matrix.Zero();
  27449. this._transformMatrix = BABYLON.Matrix.Zero();
  27450. this._worldViewProjection = BABYLON.Matrix.Zero();
  27451. this._scene = scene;
  27452. var engine = scene.getEngine();
  27453. // Render target
  27454. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  27455. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27456. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27457. this._depthMap.refreshRate = 1;
  27458. this._depthMap.renderParticles = false;
  27459. this._depthMap.renderList = null;
  27460. // Custom render function
  27461. var renderSubMesh = function (subMesh) {
  27462. var mesh = subMesh.getRenderingMesh();
  27463. var scene = _this._scene;
  27464. var engine = scene.getEngine();
  27465. // Culling
  27466. engine.setState(subMesh.getMaterial().backFaceCulling);
  27467. // Managing instances
  27468. var batch = mesh._getInstancesRenderList(subMesh._id);
  27469. if (batch.mustReturn) {
  27470. return;
  27471. }
  27472. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  27473. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  27474. engine.enableEffect(_this._effect);
  27475. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  27476. var material = subMesh.getMaterial();
  27477. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27478. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  27479. // Alpha test
  27480. if (material && material.needAlphaTesting()) {
  27481. var alphaTexture = material.getAlphaTestTexture();
  27482. _this._effect.setTexture("diffuseSampler", alphaTexture);
  27483. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27484. }
  27485. // Bones
  27486. if (mesh.useBones) {
  27487. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27488. }
  27489. // Draw
  27490. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  27491. }
  27492. };
  27493. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  27494. var index;
  27495. for (index = 0; index < opaqueSubMeshes.length; index++) {
  27496. renderSubMesh(opaqueSubMeshes.data[index]);
  27497. }
  27498. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  27499. renderSubMesh(alphaTestSubMeshes.data[index]);
  27500. }
  27501. };
  27502. }
  27503. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  27504. var defines = [];
  27505. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27506. var mesh = subMesh.getMesh();
  27507. var scene = mesh.getScene();
  27508. var material = subMesh.getMaterial();
  27509. // Alpha test
  27510. if (material && material.needAlphaTesting()) {
  27511. defines.push("#define ALPHATEST");
  27512. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27513. attribs.push(BABYLON.VertexBuffer.UVKind);
  27514. defines.push("#define UV1");
  27515. }
  27516. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27517. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27518. defines.push("#define UV2");
  27519. }
  27520. }
  27521. // Bones
  27522. if (mesh.useBones) {
  27523. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27524. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27525. defines.push("#define BONES");
  27526. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27527. }
  27528. // Instances
  27529. if (useInstances) {
  27530. defines.push("#define INSTANCES");
  27531. attribs.push("world0");
  27532. attribs.push("world1");
  27533. attribs.push("world2");
  27534. attribs.push("world3");
  27535. }
  27536. // Get correct effect
  27537. var join = defines.join("\n");
  27538. if (this._cachedDefines !== join) {
  27539. this._cachedDefines = join;
  27540. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  27541. }
  27542. return this._effect.isReady();
  27543. };
  27544. DepthRenderer.prototype.getDepthMap = function () {
  27545. return this._depthMap;
  27546. };
  27547. // Methods
  27548. DepthRenderer.prototype.dispose = function () {
  27549. this._depthMap.dispose();
  27550. };
  27551. return DepthRenderer;
  27552. })();
  27553. BABYLON.DepthRenderer = DepthRenderer;
  27554. })(BABYLON || (BABYLON = {}));
  27555. //# sourceMappingURL=babylon.depthRenderer.js.map
  27556. var BABYLON;
  27557. (function (BABYLON) {
  27558. var SSAORenderingPipeline = (function (_super) {
  27559. __extends(SSAORenderingPipeline, _super);
  27560. /**
  27561. * @constructor
  27562. * @param {string} name - The rendering pipeline name
  27563. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  27564. * @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)
  27565. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  27566. */
  27567. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  27568. var _this = this;
  27569. if (ratio === void 0) { ratio = 1.0; }
  27570. _super.call(this, scene.getEngine(), name);
  27571. // Members
  27572. /**
  27573. * The PassPostProcess id in the pipeline that contains the original scene color
  27574. * @type {string}
  27575. */
  27576. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  27577. /**
  27578. * The SSAO PostProcess id in the pipeline
  27579. * @type {string}
  27580. */
  27581. this.SSAORenderEffect = "SSAORenderEffect";
  27582. /**
  27583. * The horizontal blur PostProcess id in the pipeline
  27584. * @type {string}
  27585. */
  27586. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  27587. /**
  27588. * The vertical blur PostProcess id in the pipeline
  27589. * @type {string}
  27590. */
  27591. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  27592. /**
  27593. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  27594. * @type {string}
  27595. */
  27596. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  27597. this._firstUpdate = true;
  27598. this._scene = scene;
  27599. // Set up assets
  27600. this._createRandomTexture();
  27601. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  27602. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27603. this._createSSAOPostProcess(ratio);
  27604. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 1.3, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27605. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 1.3, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27606. this._createSSAOCombinePostProcess();
  27607. // Set up pipeline
  27608. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  27609. return _this._originalColorPostProcess;
  27610. }, true));
  27611. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  27612. return _this._ssaoPostProcess;
  27613. }, true));
  27614. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  27615. return _this._blurHPostProcess;
  27616. }, true));
  27617. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  27618. return _this._blurVPostProcess;
  27619. }, true));
  27620. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  27621. return _this._ssaoCombinePostProcess;
  27622. }, true));
  27623. // Finish
  27624. scene.postProcessRenderPipelineManager.addPipeline(this);
  27625. if (cameras)
  27626. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  27627. }
  27628. // Public Methods
  27629. /**
  27630. * Returns the horizontal blur PostProcess
  27631. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  27632. */
  27633. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  27634. return this._blurHPostProcess;
  27635. };
  27636. /**
  27637. * Returns the vertical blur PostProcess
  27638. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  27639. */
  27640. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  27641. return this._blurVPostProcess;
  27642. };
  27643. /**
  27644. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  27645. */
  27646. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  27647. if (disableDepthRender === void 0) { disableDepthRender = false; }
  27648. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  27649. this._originalColorPostProcess = undefined;
  27650. this._ssaoPostProcess = undefined;
  27651. this._blurHPostProcess = undefined;
  27652. this._blurVPostProcess = undefined;
  27653. this._ssaoCombinePostProcess = undefined;
  27654. this._randomTexture.dispose();
  27655. if (disableDepthRender)
  27656. this._scene.disableDepthRenderer();
  27657. };
  27658. // Private Methods
  27659. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  27660. var _this = this;
  27661. var sampleSphere = [
  27662. 0.5381,
  27663. 0.1856,
  27664. -0.4319,
  27665. 0.1379,
  27666. 0.2486,
  27667. 0.4430,
  27668. 0.3371,
  27669. 0.5679,
  27670. -0.0057,
  27671. -0.6999,
  27672. -0.0451,
  27673. -0.0019,
  27674. 0.0689,
  27675. -0.1598,
  27676. -0.8547,
  27677. 0.0560,
  27678. 0.0069,
  27679. -0.1843,
  27680. -0.0146,
  27681. 0.1402,
  27682. 0.0762,
  27683. 0.0100,
  27684. -0.1924,
  27685. -0.0344,
  27686. -0.3577,
  27687. -0.5301,
  27688. -0.4358,
  27689. -0.3169,
  27690. 0.1063,
  27691. 0.0158,
  27692. 0.0103,
  27693. -0.5869,
  27694. 0.0046,
  27695. -0.0897,
  27696. -0.4940,
  27697. 0.3287,
  27698. 0.7119,
  27699. -0.0154,
  27700. -0.0918,
  27701. -0.0533,
  27702. 0.0596,
  27703. -0.5411,
  27704. 0.0352,
  27705. -0.0631,
  27706. 0.5460,
  27707. -0.4776,
  27708. 0.2847,
  27709. -0.0271
  27710. ];
  27711. var samplesFactor = 1.0 / 16.0;
  27712. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  27713. this._ssaoPostProcess.onApply = function (effect) {
  27714. if (_this._firstUpdate) {
  27715. effect.setArray3("sampleSphere", sampleSphere);
  27716. effect.setFloat("samplesFactor", samplesFactor);
  27717. effect.setFloat("randTextureTiles", 4.0 / ratio);
  27718. _this._firstUpdate = false;
  27719. }
  27720. effect.setTexture("textureSampler", _this._depthTexture);
  27721. effect.setTexture("randomSampler", _this._randomTexture);
  27722. };
  27723. };
  27724. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function () {
  27725. var _this = this;
  27726. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  27727. this._ssaoCombinePostProcess.onApply = function (effect) {
  27728. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  27729. };
  27730. };
  27731. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  27732. var size = 512;
  27733. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  27734. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  27735. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  27736. var context = this._randomTexture.getContext();
  27737. var rand = function (min, max) {
  27738. return Math.random() * (max - min) + min;
  27739. };
  27740. for (var x = 0; x < size; x++) {
  27741. for (var y = 0; y < size; y++) {
  27742. var randVector = BABYLON.Vector3.Zero();
  27743. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  27744. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  27745. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  27746. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  27747. context.fillRect(x, y, 1, 1);
  27748. }
  27749. }
  27750. this._randomTexture.update(false);
  27751. };
  27752. return SSAORenderingPipeline;
  27753. })(BABYLON.PostProcessRenderPipeline);
  27754. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  27755. })(BABYLON || (BABYLON = {}));
  27756. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  27757. var BABYLON;
  27758. (function (BABYLON) {
  27759. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  27760. var VolumetricLightScatteringPostProcess = (function (_super) {
  27761. __extends(VolumetricLightScatteringPostProcess, _super);
  27762. /**
  27763. * @constructor
  27764. * @param {string} name - The post-process name
  27765. * @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)
  27766. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  27767. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  27768. * @param {number} samplingMode - The post-process filtering mode
  27769. * @param {BABYLON.Engine} engine - The babylon engine
  27770. * @param {boolean} reusable - If the post-process is reusable
  27771. */
  27772. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  27773. var _this = this;
  27774. if (samples === void 0) { samples = 100; }
  27775. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  27776. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  27777. this._screenCoordinates = BABYLON.Vector2.Zero();
  27778. /**
  27779. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  27780. * @type {boolean}
  27781. */
  27782. this.useCustomMeshPosition = false;
  27783. /**
  27784. * If the post-process should inverse the light scattering direction
  27785. * @type {boolean}
  27786. */
  27787. this.invert = true;
  27788. /**
  27789. * Array containing the excluded meshes not rendered in the internal pass
  27790. */
  27791. this.excludedMeshes = new Array();
  27792. this.exposure = 0.3;
  27793. this.decay = 0.96815;
  27794. this.weight = 0.58767;
  27795. this.density = 0.926;
  27796. var scene = camera.getScene();
  27797. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  27798. // Configure mesh
  27799. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  27800. // Configure
  27801. this._createPass(scene, 0.5);
  27802. this.onApply = function (effect) {
  27803. _this._updateMeshScreenCoordinates(scene);
  27804. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  27805. effect.setFloat("exposure", _this.exposure);
  27806. effect.setFloat("decay", _this.decay);
  27807. effect.setFloat("weight", _this.weight);
  27808. effect.setFloat("density", _this.density);
  27809. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  27810. };
  27811. }
  27812. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  27813. var mesh = subMesh.getMesh();
  27814. var defines = [];
  27815. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27816. var material = subMesh.getMaterial();
  27817. // Render this.mesh as default
  27818. if (mesh === this.mesh) {
  27819. defines.push("#define BASIC_RENDER");
  27820. }
  27821. // Alpha test
  27822. if (material) {
  27823. if (material.needAlphaTesting() || mesh === this.mesh)
  27824. defines.push("#define ALPHATEST");
  27825. if (material.opacityTexture !== undefined)
  27826. defines.push("#define OPACITY");
  27827. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27828. attribs.push(BABYLON.VertexBuffer.UVKind);
  27829. defines.push("#define UV1");
  27830. }
  27831. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27832. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27833. defines.push("#define UV2");
  27834. }
  27835. }
  27836. // Bones
  27837. if (mesh.useBones) {
  27838. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27839. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27840. defines.push("#define BONES");
  27841. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27842. }
  27843. // Instances
  27844. if (useInstances) {
  27845. defines.push("#define INSTANCES");
  27846. attribs.push("world0");
  27847. attribs.push("world1");
  27848. attribs.push("world2");
  27849. attribs.push("world3");
  27850. }
  27851. // Get correct effect
  27852. var join = defines.join("\n");
  27853. if (this._cachedDefines !== join) {
  27854. this._cachedDefines = join;
  27855. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler", "opacitySampler"], join);
  27856. }
  27857. return this._volumetricLightScatteringPass.isReady();
  27858. };
  27859. /**
  27860. * Sets the new light position for light scattering effect
  27861. * @param {BABYLON.Vector3} The new custom light position
  27862. */
  27863. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  27864. this._customMeshPosition = position;
  27865. };
  27866. /**
  27867. * Returns the light position for light scattering effect
  27868. * @return {BABYLON.Vector3} The custom light position
  27869. */
  27870. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  27871. return this._customMeshPosition;
  27872. };
  27873. /**
  27874. * Disposes the internal assets and detaches the post-process from the camera
  27875. */
  27876. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  27877. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  27878. if (rttIndex !== -1) {
  27879. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  27880. }
  27881. this._volumetricLightScatteringRTT.dispose();
  27882. _super.prototype.dispose.call(this, camera);
  27883. };
  27884. /**
  27885. * Returns the render target texture used by the post-process
  27886. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  27887. */
  27888. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  27889. return this._volumetricLightScatteringRTT;
  27890. };
  27891. // Private methods
  27892. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  27893. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  27894. return true;
  27895. }
  27896. return false;
  27897. };
  27898. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  27899. var _this = this;
  27900. var engine = scene.getEngine();
  27901. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  27902. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27903. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27904. this._volumetricLightScatteringRTT.renderList = null;
  27905. this._volumetricLightScatteringRTT.renderParticles = false;
  27906. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  27907. // Custom render function for submeshes
  27908. var renderSubMesh = function (subMesh) {
  27909. var mesh = subMesh.getRenderingMesh();
  27910. if (_this._meshExcluded(mesh)) {
  27911. return;
  27912. }
  27913. var scene = mesh.getScene();
  27914. var engine = scene.getEngine();
  27915. // Culling
  27916. engine.setState(subMesh.getMaterial().backFaceCulling);
  27917. // Managing instances
  27918. var batch = mesh._getInstancesRenderList(subMesh._id);
  27919. if (batch.mustReturn) {
  27920. return;
  27921. }
  27922. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  27923. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  27924. engine.enableEffect(_this._volumetricLightScatteringPass);
  27925. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  27926. var material = subMesh.getMaterial();
  27927. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  27928. // Alpha test
  27929. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  27930. var alphaTexture = material.getAlphaTestTexture();
  27931. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  27932. if (_this.mesh.material && alphaTexture)
  27933. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27934. if (material.opacityTexture !== undefined)
  27935. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  27936. }
  27937. // Bones
  27938. if (mesh.useBones) {
  27939. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27940. }
  27941. // Draw
  27942. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  27943. }
  27944. };
  27945. // Render target texture callbacks
  27946. var savedSceneClearColor;
  27947. var sceneClearColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  27948. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  27949. savedSceneClearColor = scene.clearColor;
  27950. scene.clearColor = sceneClearColor;
  27951. };
  27952. this._volumetricLightScatteringRTT.onAfterRender = function () {
  27953. scene.clearColor = savedSceneClearColor;
  27954. };
  27955. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  27956. var index;
  27957. for (index = 0; index < opaqueSubMeshes.length; index++) {
  27958. renderSubMesh(opaqueSubMeshes.data[index]);
  27959. }
  27960. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  27961. renderSubMesh(alphaTestSubMeshes.data[index]);
  27962. }
  27963. for (index = 0; index < transparentSubMeshes.length; index++) {
  27964. renderSubMesh(transparentSubMeshes.data[index]);
  27965. }
  27966. };
  27967. };
  27968. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  27969. var transform = scene.getTransformMatrix();
  27970. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  27971. this._screenCoordinates.x = pos.x / this._viewPort.width;
  27972. this._screenCoordinates.y = pos.y / this._viewPort.height;
  27973. if (this.invert)
  27974. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  27975. };
  27976. // Static methods
  27977. /**
  27978. * Creates a default mesh for the Volumeric Light Scattering post-process
  27979. * @param {string} The mesh name
  27980. * @param {BABYLON.Scene} The scene where to create the mesh
  27981. * @return {BABYLON.Mesh} the default mesh
  27982. */
  27983. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  27984. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  27985. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  27986. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  27987. return mesh;
  27988. };
  27989. return VolumetricLightScatteringPostProcess;
  27990. })(BABYLON.PostProcess);
  27991. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  27992. })(BABYLON || (BABYLON = {}));
  27993. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map