babylon.2.0-alpha.debug.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var Color3 = (function () {
  4. function Color3(r, g, b) {
  5. if (typeof r === "undefined") { r = 0; }
  6. if (typeof g === "undefined") { g = 0; }
  7. if (typeof b === "undefined") { b = 0; }
  8. this.r = r;
  9. this.g = g;
  10. this.b = b;
  11. }
  12. Color3.prototype.toString = function () {
  13. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  14. };
  15. Color3.prototype.toArray = function (array, index) {
  16. if (index === undefined) {
  17. index = 0;
  18. }
  19. array[index] = this.r;
  20. array[index + 1] = this.g;
  21. array[index + 2] = this.b;
  22. };
  23. Color3.prototype.toColor4 = function (alpha) {
  24. if (typeof alpha === "undefined") { alpha = 1; }
  25. return new Color4(this.r, this.g, this.b, alpha);
  26. };
  27. Color3.prototype.asArray = function () {
  28. var result = [];
  29. this.toArray(result, 0);
  30. return result;
  31. };
  32. Color3.prototype.toLuminance = function () {
  33. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  34. };
  35. Color3.prototype.multiply = function (otherColor) {
  36. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  37. };
  38. Color3.prototype.multiplyToRef = function (otherColor, result) {
  39. result.r = this.r * otherColor.r;
  40. result.g = this.g * otherColor.g;
  41. result.b = this.b * otherColor.b;
  42. };
  43. Color3.prototype.equals = function (otherColor) {
  44. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  45. };
  46. Color3.prototype.scale = function (scale) {
  47. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  48. };
  49. Color3.prototype.scaleToRef = function (scale, result) {
  50. result.r = this.r * scale;
  51. result.g = this.g * scale;
  52. result.b = this.b * scale;
  53. };
  54. Color3.prototype.add = function (otherColor) {
  55. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  56. };
  57. Color3.prototype.addToRef = function (otherColor, result) {
  58. result.r = this.r + otherColor.r;
  59. result.g = this.g + otherColor.g;
  60. result.b = this.b + otherColor.b;
  61. };
  62. Color3.prototype.subtract = function (otherColor) {
  63. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  64. };
  65. Color3.prototype.subtractToRef = function (otherColor, result) {
  66. result.r = this.r - otherColor.r;
  67. result.g = this.g - otherColor.g;
  68. result.b = this.b - otherColor.b;
  69. };
  70. Color3.prototype.clone = function () {
  71. return new Color3(this.r, this.g, this.b);
  72. };
  73. Color3.prototype.copyFrom = function (source) {
  74. this.r = source.r;
  75. this.g = source.g;
  76. this.b = source.b;
  77. };
  78. Color3.prototype.copyFromFloats = function (r, g, b) {
  79. this.r = r;
  80. this.g = g;
  81. this.b = b;
  82. };
  83. Color3.FromArray = function (array) {
  84. return new Color3(array[0], array[1], array[2]);
  85. };
  86. Color3.FromInts = function (r, g, b) {
  87. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  88. };
  89. Color3.Lerp = function (start, end, amount) {
  90. var r = start.r + ((end.r - start.r) * amount);
  91. var g = start.g + ((end.g - start.g) * amount);
  92. var b = start.b + ((end.b - start.b) * amount);
  93. return new Color3(r, g, b);
  94. };
  95. Color3.Red = function () {
  96. return new Color3(1, 0, 0);
  97. };
  98. Color3.Green = function () {
  99. return new Color3(0, 1, 0);
  100. };
  101. Color3.Blue = function () {
  102. return new Color3(0, 0, 1);
  103. };
  104. Color3.Black = function () {
  105. return new Color3(0, 0, 0);
  106. };
  107. Color3.White = function () {
  108. return new Color3(1, 1, 1);
  109. };
  110. Color3.Purple = function () {
  111. return new Color3(0.5, 0, 0.5);
  112. };
  113. Color3.Magenta = function () {
  114. return new Color3(1, 0, 1);
  115. };
  116. Color3.Yellow = function () {
  117. return new Color3(1, 1, 0);
  118. };
  119. Color3.Gray = function () {
  120. return new Color3(0.5, 0.5, 0.5);
  121. };
  122. return Color3;
  123. })();
  124. BABYLON.Color3 = Color3;
  125. var Color4 = (function () {
  126. function Color4(r, g, b, a) {
  127. this.r = r;
  128. this.g = g;
  129. this.b = b;
  130. this.a = a;
  131. }
  132. Color4.prototype.addInPlace = function (right) {
  133. this.r += right.r;
  134. this.g += right.g;
  135. this.b += right.b;
  136. this.a += right.a;
  137. };
  138. Color4.prototype.asArray = function () {
  139. var result = [];
  140. this.toArray(result, 0);
  141. return result;
  142. };
  143. Color4.prototype.toArray = function (array, index) {
  144. if (index === undefined) {
  145. index = 0;
  146. }
  147. array[index] = this.r;
  148. array[index + 1] = this.g;
  149. array[index + 2] = this.b;
  150. array[index + 3] = this.a;
  151. };
  152. Color4.prototype.add = function (right) {
  153. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  154. };
  155. Color4.prototype.subtract = function (right) {
  156. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  157. };
  158. Color4.prototype.subtractToRef = function (right, result) {
  159. result.r = this.r - right.r;
  160. result.g = this.g - right.g;
  161. result.b = this.b - right.b;
  162. result.a = this.a - right.a;
  163. };
  164. Color4.prototype.scale = function (scale) {
  165. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  166. };
  167. Color4.prototype.scaleToRef = function (scale, result) {
  168. result.r = this.r * scale;
  169. result.g = this.g * scale;
  170. result.b = this.b * scale;
  171. result.a = this.a * scale;
  172. };
  173. Color4.prototype.toString = function () {
  174. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  175. };
  176. Color4.prototype.clone = function () {
  177. return new Color4(this.r, this.g, this.b, this.a);
  178. };
  179. Color4.Lerp = function (left, right, amount) {
  180. var result = new Color4(0, 0, 0, 0);
  181. BABYLON.Color4.LerpToRef(left, right, amount, result);
  182. return result;
  183. };
  184. Color4.LerpToRef = function (left, right, amount, result) {
  185. result.r = left.r + (right.r - left.r) * amount;
  186. result.g = left.g + (right.g - left.g) * amount;
  187. result.b = left.b + (right.b - left.b) * amount;
  188. result.a = left.a + (right.a - left.a) * amount;
  189. };
  190. Color4.FromArray = function (array, offset) {
  191. if (typeof offset === "undefined") { offset = 0; }
  192. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  193. };
  194. Color4.FromInts = function (r, g, b, a) {
  195. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  196. };
  197. return Color4;
  198. })();
  199. BABYLON.Color4 = Color4;
  200. var Vector2 = (function () {
  201. function Vector2(x, y) {
  202. this.x = x;
  203. this.y = y;
  204. }
  205. Vector2.prototype.toString = function () {
  206. return "{X: " + this.x + " Y:" + this.y + "}";
  207. };
  208. Vector2.prototype.toArray = function (array, index) {
  209. if (index === undefined) {
  210. index = 0;
  211. }
  212. array[index] = this.x;
  213. array[index + 1] = this.y;
  214. };
  215. Vector2.prototype.asArray = function () {
  216. var result = [];
  217. this.toArray(result, 0);
  218. return result;
  219. };
  220. Vector2.prototype.copyFrom = function (source) {
  221. this.x = source.x;
  222. this.y = source.y;
  223. };
  224. Vector2.prototype.copyFromFloats = function (x, y) {
  225. this.x = x;
  226. this.y = y;
  227. };
  228. Vector2.prototype.add = function (otherVector) {
  229. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  230. };
  231. Vector2.prototype.addVector3 = function (otherVector) {
  232. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  233. };
  234. Vector2.prototype.subtract = function (otherVector) {
  235. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  236. };
  237. Vector2.prototype.subtractInPlace = function (otherVector) {
  238. this.x -= otherVector.x;
  239. this.y -= otherVector.y;
  240. };
  241. Vector2.prototype.multiplyInPlace = function (otherVector) {
  242. this.x *= otherVector.x;
  243. this.y *= otherVector.y;
  244. };
  245. Vector2.prototype.multiply = function (otherVector) {
  246. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  247. };
  248. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  249. result.x = this.x * otherVector.x;
  250. result.y = this.y * otherVector.y;
  251. };
  252. Vector2.prototype.multiplyByFloats = function (x, y) {
  253. return new Vector2(this.x * x, this.y * y);
  254. };
  255. Vector2.prototype.divide = function (otherVector) {
  256. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  257. };
  258. Vector2.prototype.divideToRef = function (otherVector, result) {
  259. result.x = this.x / otherVector.x;
  260. result.y = this.y / otherVector.y;
  261. };
  262. Vector2.prototype.negate = function () {
  263. return new Vector2(-this.x, -this.y);
  264. };
  265. Vector2.prototype.scaleInPlace = function (scale) {
  266. this.x *= scale;
  267. this.y *= scale;
  268. return this;
  269. };
  270. Vector2.prototype.scale = function (scale) {
  271. return new Vector2(this.x * scale, this.y * scale);
  272. };
  273. Vector2.prototype.equals = function (otherVector) {
  274. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  275. };
  276. Vector2.prototype.length = function () {
  277. return Math.sqrt(this.x * this.x + this.y * this.y);
  278. };
  279. Vector2.prototype.lengthSquared = function () {
  280. return (this.x * this.x + this.y * this.y);
  281. };
  282. Vector2.prototype.normalize = function () {
  283. var len = this.length();
  284. if (len === 0)
  285. return this;
  286. var num = 1.0 / len;
  287. this.x *= num;
  288. this.y *= num;
  289. return this;
  290. };
  291. Vector2.prototype.clone = function () {
  292. return new Vector2(this.x, this.y);
  293. };
  294. Vector2.Zero = function () {
  295. return new Vector2(0, 0);
  296. };
  297. Vector2.FromArray = function (array, offset) {
  298. if (!offset) {
  299. offset = 0;
  300. }
  301. return new Vector2(array[offset], array[offset + 1]);
  302. };
  303. Vector2.FromArrayToRef = function (array, offset, result) {
  304. result.x = array[offset];
  305. result.y = array[offset + 1];
  306. };
  307. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  308. var squared = amount * amount;
  309. var cubed = amount * squared;
  310. 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));
  311. 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));
  312. return new Vector2(x, y);
  313. };
  314. Vector2.Clamp = function (value, min, max) {
  315. var x = value.x;
  316. x = (x > max.x) ? max.x : x;
  317. x = (x < min.x) ? min.x : x;
  318. var y = value.y;
  319. y = (y > max.y) ? max.y : y;
  320. y = (y < min.y) ? min.y : y;
  321. return new Vector2(x, y);
  322. };
  323. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  324. var squared = amount * amount;
  325. var cubed = amount * squared;
  326. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  327. var part2 = (-2.0 * cubed) + (3.0 * squared);
  328. var part3 = (cubed - (2.0 * squared)) + amount;
  329. var part4 = cubed - squared;
  330. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  331. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  332. return new Vector2(x, y);
  333. };
  334. Vector2.Lerp = function (start, end, amount) {
  335. var x = start.x + ((end.x - start.x) * amount);
  336. var y = start.y + ((end.y - start.y) * amount);
  337. return new Vector2(x, y);
  338. };
  339. Vector2.Dot = function (left, right) {
  340. return left.x * right.x + left.y * right.y;
  341. };
  342. Vector2.Normalize = function (vector) {
  343. var newVector = vector.clone();
  344. newVector.normalize();
  345. return newVector;
  346. };
  347. Vector2.Minimize = function (left, right) {
  348. var x = (left.x < right.x) ? left.x : right.x;
  349. var y = (left.y < right.y) ? left.y : right.y;
  350. return new Vector2(x, y);
  351. };
  352. Vector2.Maximize = function (left, right) {
  353. var x = (left.x > right.x) ? left.x : right.x;
  354. var y = (left.y > right.y) ? left.y : right.y;
  355. return new Vector2(x, y);
  356. };
  357. Vector2.Transform = function (vector, transformation) {
  358. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  359. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  360. return new Vector2(x, y);
  361. };
  362. Vector2.Distance = function (value1, value2) {
  363. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  364. };
  365. Vector2.DistanceSquared = function (value1, value2) {
  366. var x = value1.x - value2.x;
  367. var y = value1.y - value2.y;
  368. return (x * x) + (y * y);
  369. };
  370. return Vector2;
  371. })();
  372. BABYLON.Vector2 = Vector2;
  373. var Vector3 = (function () {
  374. function Vector3(x, y, z) {
  375. this.x = x;
  376. this.y = y;
  377. this.z = z;
  378. }
  379. Vector3.prototype.toString = function () {
  380. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  381. };
  382. Vector3.prototype.asArray = function () {
  383. var result = [];
  384. this.toArray(result, 0);
  385. return result;
  386. };
  387. Vector3.prototype.toArray = function (array, index) {
  388. if (index === undefined) {
  389. index = 0;
  390. }
  391. array[index] = this.x;
  392. array[index + 1] = this.y;
  393. array[index + 2] = this.z;
  394. };
  395. Vector3.prototype.addInPlace = function (otherVector) {
  396. this.x += otherVector.x;
  397. this.y += otherVector.y;
  398. this.z += otherVector.z;
  399. };
  400. Vector3.prototype.add = function (otherVector) {
  401. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  402. };
  403. Vector3.prototype.addToRef = function (otherVector, result) {
  404. result.x = this.x + otherVector.x;
  405. result.y = this.y + otherVector.y;
  406. result.z = this.z + otherVector.z;
  407. };
  408. Vector3.prototype.subtractInPlace = function (otherVector) {
  409. this.x -= otherVector.x;
  410. this.y -= otherVector.y;
  411. this.z -= otherVector.z;
  412. };
  413. Vector3.prototype.subtract = function (otherVector) {
  414. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  415. };
  416. Vector3.prototype.subtractToRef = function (otherVector, result) {
  417. result.x = this.x - otherVector.x;
  418. result.y = this.y - otherVector.y;
  419. result.z = this.z - otherVector.z;
  420. };
  421. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  422. return new Vector3(this.x - x, this.y - y, this.z - z);
  423. };
  424. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  425. result.x = this.x - x;
  426. result.y = this.y - y;
  427. result.z = this.z - z;
  428. };
  429. Vector3.prototype.negate = function () {
  430. return new Vector3(-this.x, -this.y, -this.z);
  431. };
  432. Vector3.prototype.scaleInPlace = function (scale) {
  433. this.x *= scale;
  434. this.y *= scale;
  435. this.z *= scale;
  436. return this;
  437. };
  438. Vector3.prototype.scale = function (scale) {
  439. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  440. };
  441. Vector3.prototype.scaleToRef = function (scale, result) {
  442. result.x = this.x * scale;
  443. result.y = this.y * scale;
  444. result.z = this.z * scale;
  445. };
  446. Vector3.prototype.equals = function (otherVector) {
  447. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  448. };
  449. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  450. 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;
  451. };
  452. Vector3.prototype.equalsToFloats = function (x, y, z) {
  453. return this.x === x && this.y === y && this.z === z;
  454. };
  455. Vector3.prototype.multiplyInPlace = function (otherVector) {
  456. this.x *= otherVector.x;
  457. this.y *= otherVector.y;
  458. this.z *= otherVector.z;
  459. };
  460. Vector3.prototype.multiply = function (otherVector) {
  461. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  462. };
  463. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  464. result.x = this.x * otherVector.x;
  465. result.y = this.y * otherVector.y;
  466. result.z = this.z * otherVector.z;
  467. };
  468. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  469. return new Vector3(this.x * x, this.y * y, this.z * z);
  470. };
  471. Vector3.prototype.divide = function (otherVector) {
  472. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  473. };
  474. Vector3.prototype.divideToRef = function (otherVector, result) {
  475. result.x = this.x / otherVector.x;
  476. result.y = this.y / otherVector.y;
  477. result.z = this.z / otherVector.z;
  478. };
  479. Vector3.prototype.MinimizeInPlace = function (other) {
  480. if (other.x < this.x)
  481. this.x = other.x;
  482. if (other.y < this.y)
  483. this.y = other.y;
  484. if (other.z < this.z)
  485. this.z = other.z;
  486. };
  487. Vector3.prototype.MaximizeInPlace = function (other) {
  488. if (other.x > this.x)
  489. this.x = other.x;
  490. if (other.y > this.y)
  491. this.y = other.y;
  492. if (other.z > this.z)
  493. this.z = other.z;
  494. };
  495. Vector3.prototype.length = function () {
  496. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  497. };
  498. Vector3.prototype.lengthSquared = function () {
  499. return (this.x * this.x + this.y * this.y + this.z * this.z);
  500. };
  501. Vector3.prototype.normalize = function () {
  502. var len = this.length();
  503. if (len === 0)
  504. return this;
  505. var num = 1.0 / len;
  506. this.x *= num;
  507. this.y *= num;
  508. this.z *= num;
  509. return this;
  510. };
  511. Vector3.prototype.clone = function () {
  512. return new Vector3(this.x, this.y, this.z);
  513. };
  514. Vector3.prototype.copyFrom = function (source) {
  515. this.x = source.x;
  516. this.y = source.y;
  517. this.z = source.z;
  518. };
  519. Vector3.prototype.copyFromFloats = function (x, y, z) {
  520. this.x = x;
  521. this.y = y;
  522. this.z = z;
  523. };
  524. Vector3.FromArray = function (array, offset) {
  525. if (!offset) {
  526. offset = 0;
  527. }
  528. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  529. };
  530. Vector3.FromArrayToRef = function (array, offset, result) {
  531. result.x = array[offset];
  532. result.y = array[offset + 1];
  533. result.z = array[offset + 2];
  534. };
  535. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  536. result.x = array[offset];
  537. result.y = array[offset + 1];
  538. result.z = array[offset + 2];
  539. };
  540. Vector3.FromFloatsToRef = function (x, y, z, result) {
  541. result.x = x;
  542. result.y = y;
  543. result.z = z;
  544. };
  545. Vector3.Zero = function () {
  546. return new Vector3(0, 0, 0);
  547. };
  548. Vector3.Up = function () {
  549. return new Vector3(0, 1.0, 0);
  550. };
  551. Vector3.TransformCoordinates = function (vector, transformation) {
  552. var result = Vector3.Zero();
  553. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  554. return result;
  555. };
  556. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  557. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  558. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  559. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  560. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  561. result.x = x / w;
  562. result.y = y / w;
  563. result.z = z / w;
  564. };
  565. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  566. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  567. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  568. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  569. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  570. result.x = rx / rw;
  571. result.y = ry / rw;
  572. result.z = rz / rw;
  573. };
  574. Vector3.TransformNormal = function (vector, transformation) {
  575. var result = Vector3.Zero();
  576. Vector3.TransformNormalToRef(vector, transformation, result);
  577. return result;
  578. };
  579. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  580. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  581. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  582. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  583. };
  584. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  585. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  586. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  587. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  588. };
  589. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  590. var squared = amount * amount;
  591. var cubed = amount * squared;
  592. 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));
  593. 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));
  594. 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));
  595. return new Vector3(x, y, z);
  596. };
  597. Vector3.Clamp = function (value, min, max) {
  598. var x = value.x;
  599. x = (x > max.x) ? max.x : x;
  600. x = (x < min.x) ? min.x : x;
  601. var y = value.y;
  602. y = (y > max.y) ? max.y : y;
  603. y = (y < min.y) ? min.y : y;
  604. var z = value.z;
  605. z = (z > max.z) ? max.z : z;
  606. z = (z < min.z) ? min.z : z;
  607. return new Vector3(x, y, z);
  608. };
  609. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  610. var squared = amount * amount;
  611. var cubed = amount * squared;
  612. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  613. var part2 = (-2.0 * cubed) + (3.0 * squared);
  614. var part3 = (cubed - (2.0 * squared)) + amount;
  615. var part4 = cubed - squared;
  616. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  617. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  618. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  619. return new Vector3(x, y, z);
  620. };
  621. Vector3.Lerp = function (start, end, amount) {
  622. var x = start.x + ((end.x - start.x) * amount);
  623. var y = start.y + ((end.y - start.y) * amount);
  624. var z = start.z + ((end.z - start.z) * amount);
  625. return new Vector3(x, y, z);
  626. };
  627. Vector3.Dot = function (left, right) {
  628. return (left.x * right.x + left.y * right.y + left.z * right.z);
  629. };
  630. Vector3.Cross = function (left, right) {
  631. var result = Vector3.Zero();
  632. Vector3.CrossToRef(left, right, result);
  633. return result;
  634. };
  635. Vector3.CrossToRef = function (left, right, result) {
  636. result.x = left.y * right.z - left.z * right.y;
  637. result.y = left.z * right.x - left.x * right.z;
  638. result.z = left.x * right.y - left.y * right.x;
  639. };
  640. Vector3.Normalize = function (vector) {
  641. var result = Vector3.Zero();
  642. Vector3.NormalizeToRef(vector, result);
  643. return result;
  644. };
  645. Vector3.NormalizeToRef = function (vector, result) {
  646. result.copyFrom(vector);
  647. result.normalize();
  648. };
  649. Vector3.Project = function (vector, world, transform, viewport) {
  650. var cw = viewport.width;
  651. var ch = viewport.height;
  652. var cx = viewport.x;
  653. var cy = viewport.y;
  654. var viewportMatrix = BABYLON.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);
  655. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  656. return Vector3.TransformCoordinates(vector, finalMatrix);
  657. };
  658. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  659. var matrix = world.multiply(view).multiply(projection);
  660. matrix.invert();
  661. source.x = source.x / viewportWidth * 2 - 1;
  662. source.y = -(source.y / viewportHeight * 2 - 1);
  663. var vector = BABYLON.Vector3.TransformCoordinates(source, matrix);
  664. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  665. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  666. vector = vector.scale(1.0 / num);
  667. }
  668. return vector;
  669. };
  670. Vector3.Minimize = function (left, right) {
  671. var min = left.clone();
  672. min.MinimizeInPlace(right);
  673. return min;
  674. };
  675. Vector3.Maximize = function (left, right) {
  676. var max = left.clone();
  677. max.MaximizeInPlace(right);
  678. return max;
  679. };
  680. Vector3.Distance = function (value1, value2) {
  681. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  682. };
  683. Vector3.DistanceSquared = function (value1, value2) {
  684. var x = value1.x - value2.x;
  685. var y = value1.y - value2.y;
  686. var z = value1.z - value2.z;
  687. return (x * x) + (y * y) + (z * z);
  688. };
  689. Vector3.Center = function (value1, value2) {
  690. var center = value1.add(value2);
  691. center.scaleInPlace(0.5);
  692. return center;
  693. };
  694. return Vector3;
  695. })();
  696. BABYLON.Vector3 = Vector3;
  697. var Vector4 = (function () {
  698. function Vector4(x, y, z, w) {
  699. this.x = x;
  700. this.y = y;
  701. this.z = z;
  702. this.w = w;
  703. }
  704. Vector4.prototype.toString = function () {
  705. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  706. };
  707. Vector4.prototype.asArray = function () {
  708. var result = [];
  709. this.toArray(result, 0);
  710. return result;
  711. };
  712. Vector4.prototype.toArray = function (array, index) {
  713. if (index === undefined) {
  714. index = 0;
  715. }
  716. array[index] = this.x;
  717. array[index + 1] = this.y;
  718. array[index + 2] = this.z;
  719. array[index + 3] = this.w;
  720. };
  721. Vector4.prototype.addInPlace = function (otherVector) {
  722. this.x += otherVector.x;
  723. this.y += otherVector.y;
  724. this.z += otherVector.z;
  725. this.w += otherVector.w;
  726. };
  727. Vector4.prototype.add = function (otherVector) {
  728. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  729. };
  730. Vector4.prototype.addToRef = function (otherVector, result) {
  731. result.x = this.x + otherVector.x;
  732. result.y = this.y + otherVector.y;
  733. result.z = this.z + otherVector.z;
  734. result.w = this.w + otherVector.w;
  735. };
  736. Vector4.prototype.subtractInPlace = function (otherVector) {
  737. this.x -= otherVector.x;
  738. this.y -= otherVector.y;
  739. this.z -= otherVector.z;
  740. this.w -= otherVector.w;
  741. };
  742. Vector4.prototype.subtract = function (otherVector) {
  743. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  744. };
  745. Vector4.prototype.subtractToRef = function (otherVector, result) {
  746. result.x = this.x - otherVector.x;
  747. result.y = this.y - otherVector.y;
  748. result.z = this.z - otherVector.z;
  749. result.w = this.w - otherVector.w;
  750. };
  751. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  752. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  753. };
  754. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  755. result.x = this.x - x;
  756. result.y = this.y - y;
  757. result.z = this.z - z;
  758. result.w = this.w - w;
  759. };
  760. Vector4.prototype.negate = function () {
  761. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  762. };
  763. Vector4.prototype.scaleInPlace = function (scale) {
  764. this.x *= scale;
  765. this.y *= scale;
  766. this.z *= scale;
  767. this.w *= scale;
  768. return this;
  769. };
  770. Vector4.prototype.scale = function (scale) {
  771. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  772. };
  773. Vector4.prototype.scaleToRef = function (scale, result) {
  774. result.x = this.x * scale;
  775. result.y = this.y * scale;
  776. result.z = this.z * scale;
  777. result.w = this.w * scale;
  778. };
  779. Vector4.prototype.equals = function (otherVector) {
  780. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  781. };
  782. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  783. 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;
  784. };
  785. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  786. return this.x === x && this.y === y && this.z === z && this.w === w;
  787. };
  788. Vector4.prototype.multiplyInPlace = function (otherVector) {
  789. this.x *= otherVector.x;
  790. this.y *= otherVector.y;
  791. this.z *= otherVector.z;
  792. this.w *= otherVector.w;
  793. };
  794. Vector4.prototype.multiply = function (otherVector) {
  795. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  796. };
  797. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  798. result.x = this.x * otherVector.x;
  799. result.y = this.y * otherVector.y;
  800. result.z = this.z * otherVector.z;
  801. result.w = this.w * otherVector.w;
  802. };
  803. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  804. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  805. };
  806. Vector4.prototype.divide = function (otherVector) {
  807. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  808. };
  809. Vector4.prototype.divideToRef = function (otherVector, result) {
  810. result.x = this.x / otherVector.x;
  811. result.y = this.y / otherVector.y;
  812. result.z = this.z / otherVector.z;
  813. result.w = this.w / otherVector.w;
  814. };
  815. Vector4.prototype.MinimizeInPlace = function (other) {
  816. if (other.x < this.x)
  817. this.x = other.x;
  818. if (other.y < this.y)
  819. this.y = other.y;
  820. if (other.z < this.z)
  821. this.z = other.z;
  822. if (other.w < this.w)
  823. this.w = other.w;
  824. };
  825. Vector4.prototype.MaximizeInPlace = function (other) {
  826. if (other.x > this.x)
  827. this.x = other.x;
  828. if (other.y > this.y)
  829. this.y = other.y;
  830. if (other.z > this.z)
  831. this.z = other.z;
  832. if (other.w > this.w)
  833. this.w = other.w;
  834. };
  835. Vector4.prototype.length = function () {
  836. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  837. };
  838. Vector4.prototype.lengthSquared = function () {
  839. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  840. };
  841. Vector4.prototype.normalize = function () {
  842. var len = this.length();
  843. if (len === 0)
  844. return this;
  845. var num = 1.0 / len;
  846. this.x *= num;
  847. this.y *= num;
  848. this.z *= num;
  849. this.w *= num;
  850. return this;
  851. };
  852. Vector4.prototype.clone = function () {
  853. return new Vector4(this.x, this.y, this.z, this.w);
  854. };
  855. Vector4.prototype.copyFrom = function (source) {
  856. this.x = source.x;
  857. this.y = source.y;
  858. this.z = source.z;
  859. this.w = source.w;
  860. };
  861. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  862. this.x = x;
  863. this.y = y;
  864. this.z = z;
  865. this.w = w;
  866. };
  867. Vector4.FromArray = function (array, offset) {
  868. if (!offset) {
  869. offset = 0;
  870. }
  871. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  872. };
  873. Vector4.FromArrayToRef = function (array, offset, result) {
  874. result.x = array[offset];
  875. result.y = array[offset + 1];
  876. result.z = array[offset + 2];
  877. result.w = array[offset + 3];
  878. };
  879. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  880. result.x = array[offset];
  881. result.y = array[offset + 1];
  882. result.z = array[offset + 2];
  883. result.w = array[offset + 3];
  884. };
  885. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  886. result.x = x;
  887. result.y = y;
  888. result.z = z;
  889. result.w = w;
  890. };
  891. Vector4.Zero = function () {
  892. return new Vector4(0, 0, 0, 0);
  893. };
  894. Vector4.Normalize = function (vector) {
  895. var result = Vector4.Zero();
  896. Vector4.NormalizeToRef(vector, result);
  897. return result;
  898. };
  899. Vector4.NormalizeToRef = function (vector, result) {
  900. result.copyFrom(vector);
  901. result.normalize();
  902. };
  903. Vector4.Minimize = function (left, right) {
  904. var min = left.clone();
  905. min.MinimizeInPlace(right);
  906. return min;
  907. };
  908. Vector4.Maximize = function (left, right) {
  909. var max = left.clone();
  910. max.MaximizeInPlace(right);
  911. return max;
  912. };
  913. Vector4.Distance = function (value1, value2) {
  914. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  915. };
  916. Vector4.DistanceSquared = function (value1, value2) {
  917. var x = value1.x - value2.x;
  918. var y = value1.y - value2.y;
  919. var z = value1.z - value2.z;
  920. var w = value1.w - value2.w;
  921. return (x * x) + (y * y) + (z * z) + (w * w);
  922. };
  923. Vector4.Center = function (value1, value2) {
  924. var center = value1.add(value2);
  925. center.scaleInPlace(0.5);
  926. return center;
  927. };
  928. return Vector4;
  929. })();
  930. BABYLON.Vector4 = Vector4;
  931. var Quaternion = (function () {
  932. function Quaternion(x, y, z, w) {
  933. if (typeof x === "undefined") { x = 0; }
  934. if (typeof y === "undefined") { y = 0; }
  935. if (typeof z === "undefined") { z = 0; }
  936. if (typeof w === "undefined") { w = 1; }
  937. this.x = x;
  938. this.y = y;
  939. this.z = z;
  940. this.w = w;
  941. }
  942. Quaternion.prototype.toString = function () {
  943. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  944. };
  945. Quaternion.prototype.asArray = function () {
  946. return [this.x, this.y, this.z, this.w];
  947. };
  948. Quaternion.prototype.equals = function (otherQuaternion) {
  949. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  950. };
  951. Quaternion.prototype.clone = function () {
  952. return new Quaternion(this.x, this.y, this.z, this.w);
  953. };
  954. Quaternion.prototype.copyFrom = function (other) {
  955. this.x = other.x;
  956. this.y = other.y;
  957. this.z = other.z;
  958. this.w = other.w;
  959. };
  960. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  961. this.x = x;
  962. this.y = y;
  963. this.z = z;
  964. this.w = w;
  965. };
  966. Quaternion.prototype.add = function (other) {
  967. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  968. };
  969. Quaternion.prototype.subtract = function (other) {
  970. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  971. };
  972. Quaternion.prototype.scale = function (value) {
  973. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  974. };
  975. Quaternion.prototype.multiply = function (q1) {
  976. var result = new Quaternion(0, 0, 0, 1.0);
  977. this.multiplyToRef(q1, result);
  978. return result;
  979. };
  980. Quaternion.prototype.multiplyToRef = function (q1, result) {
  981. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  982. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  983. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  984. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  985. };
  986. Quaternion.prototype.length = function () {
  987. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  988. };
  989. Quaternion.prototype.normalize = function () {
  990. var length = 1.0 / this.length();
  991. this.x *= length;
  992. this.y *= length;
  993. this.z *= length;
  994. this.w *= length;
  995. };
  996. Quaternion.prototype.toEulerAngles = function () {
  997. var result = Vector3.Zero();
  998. this.toEulerAnglesToRef(result);
  999. return result;
  1000. };
  1001. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1002. var qx = this.x;
  1003. var qy = this.y;
  1004. var qz = this.z;
  1005. var qw = this.w;
  1006. var qxy = qx * qy;
  1007. var qxz = qx * qz;
  1008. var qwy = qw * qy;
  1009. var qwz = qw * qz;
  1010. var qwx = qw * qx;
  1011. var qyz = qy * qz;
  1012. var sqx = qx * qx;
  1013. var sqy = qy * qy;
  1014. var determinant = sqx + sqy;
  1015. if (determinant != 0.000 && determinant != 1.000) {
  1016. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1017. result.y = Math.acos(1 - 2 * determinant);
  1018. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1019. } else {
  1020. if (determinant == 0.000) {
  1021. result.x = 0.0;
  1022. result.y = 0.0;
  1023. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz);
  1024. } else {
  1025. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz);
  1026. result.y = Math.PI;
  1027. result.z = 0.0;
  1028. }
  1029. }
  1030. };
  1031. Quaternion.prototype.toRotationMatrix = function (result) {
  1032. var xx = this.x * this.x;
  1033. var yy = this.y * this.y;
  1034. var zz = this.z * this.z;
  1035. var xy = this.x * this.y;
  1036. var zw = this.z * this.w;
  1037. var zx = this.z * this.x;
  1038. var yw = this.y * this.w;
  1039. var yz = this.y * this.z;
  1040. var xw = this.x * this.w;
  1041. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1042. result.m[1] = 2.0 * (xy + zw);
  1043. result.m[2] = 2.0 * (zx - yw);
  1044. result.m[3] = 0;
  1045. result.m[4] = 2.0 * (xy - zw);
  1046. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1047. result.m[6] = 2.0 * (yz + xw);
  1048. result.m[7] = 0;
  1049. result.m[8] = 2.0 * (zx + yw);
  1050. result.m[9] = 2.0 * (yz - xw);
  1051. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1052. result.m[11] = 0;
  1053. result.m[12] = 0;
  1054. result.m[13] = 0;
  1055. result.m[14] = 0;
  1056. result.m[15] = 1.0;
  1057. };
  1058. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1059. var data = matrix.m;
  1060. var m11 = data[0], m12 = data[4], m13 = data[8];
  1061. var m21 = data[1], m22 = data[5], m23 = data[9];
  1062. var m31 = data[2], m32 = data[6], m33 = data[10];
  1063. var trace = m11 + m22 + m33;
  1064. var s;
  1065. if (trace > 0) {
  1066. s = 0.5 / Math.sqrt(trace + 1.0);
  1067. this.w = 0.25 / s;
  1068. this.x = (m32 - m23) * s;
  1069. this.y = (m13 - m31) * s;
  1070. this.z = (m21 - m12) * s;
  1071. return;
  1072. }
  1073. if (m11 > m22 && m11 > m33) {
  1074. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1075. this.w = (m32 - m23) / s;
  1076. this.x = 0.25 * s;
  1077. this.y = (m12 + m21) / s;
  1078. this.z = (m13 + m31) / s;
  1079. return;
  1080. }
  1081. if (m22 > m33) {
  1082. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1083. this.w = (m13 - m31) / s;
  1084. this.x = (m12 + m21) / s;
  1085. this.y = 0.25 * s;
  1086. this.z = (m23 + m32) / s;
  1087. return;
  1088. }
  1089. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1090. this.w = (m21 - m12) / s;
  1091. this.x = (m13 + m31) / s;
  1092. this.y = (m23 + m32) / s;
  1093. this.z = 0.25 * s;
  1094. };
  1095. Quaternion.Inverse = function (q) {
  1096. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1097. };
  1098. Quaternion.RotationAxis = function (axis, angle) {
  1099. var result = new Quaternion();
  1100. var sin = Math.sin(angle / 2);
  1101. result.w = Math.cos(angle / 2);
  1102. result.x = axis.x * sin;
  1103. result.y = axis.y * sin;
  1104. result.z = axis.z * sin;
  1105. return result;
  1106. };
  1107. Quaternion.FromArray = function (array, offset) {
  1108. if (!offset) {
  1109. offset = 0;
  1110. }
  1111. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1112. };
  1113. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1114. var result = new Quaternion();
  1115. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1116. return result;
  1117. };
  1118. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1119. var halfRoll = roll * 0.5;
  1120. var halfPitch = pitch * 0.5;
  1121. var halfYaw = yaw * 0.5;
  1122. var sinRoll = Math.sin(halfRoll);
  1123. var cosRoll = Math.cos(halfRoll);
  1124. var sinPitch = Math.sin(halfPitch);
  1125. var cosPitch = Math.cos(halfPitch);
  1126. var sinYaw = Math.sin(halfYaw);
  1127. var cosYaw = Math.cos(halfYaw);
  1128. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1129. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1130. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1131. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1132. };
  1133. Quaternion.Slerp = function (left, right, amount) {
  1134. var num2;
  1135. var num3;
  1136. var num = amount;
  1137. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1138. var flag = false;
  1139. if (num4 < 0) {
  1140. flag = true;
  1141. num4 = -num4;
  1142. }
  1143. if (num4 > 0.999999) {
  1144. num3 = 1 - num;
  1145. num2 = flag ? -num : num;
  1146. } else {
  1147. var num5 = Math.acos(num4);
  1148. var num6 = (1.0 / Math.sin(num5));
  1149. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1150. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1151. }
  1152. 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));
  1153. };
  1154. return Quaternion;
  1155. })();
  1156. BABYLON.Quaternion = Quaternion;
  1157. var Matrix = (function () {
  1158. function Matrix() {
  1159. this.m = new Float32Array(16);
  1160. }
  1161. Matrix.prototype.isIdentity = function () {
  1162. if (this.m[0] != 1.0 || this.m[5] != 1.0 || this.m[10] != 1.0 || this.m[15] != 1.0)
  1163. return false;
  1164. 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)
  1165. return false;
  1166. return true;
  1167. };
  1168. Matrix.prototype.determinant = function () {
  1169. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1170. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1171. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1172. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1173. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1174. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1175. 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))));
  1176. };
  1177. Matrix.prototype.toArray = function () {
  1178. return this.m;
  1179. };
  1180. Matrix.prototype.asArray = function () {
  1181. return this.toArray();
  1182. };
  1183. Matrix.prototype.invert = function () {
  1184. this.invertToRef(this);
  1185. };
  1186. Matrix.prototype.invertToRef = function (other) {
  1187. var l1 = this.m[0];
  1188. var l2 = this.m[1];
  1189. var l3 = this.m[2];
  1190. var l4 = this.m[3];
  1191. var l5 = this.m[4];
  1192. var l6 = this.m[5];
  1193. var l7 = this.m[6];
  1194. var l8 = this.m[7];
  1195. var l9 = this.m[8];
  1196. var l10 = this.m[9];
  1197. var l11 = this.m[10];
  1198. var l12 = this.m[11];
  1199. var l13 = this.m[12];
  1200. var l14 = this.m[13];
  1201. var l15 = this.m[14];
  1202. var l16 = this.m[15];
  1203. var l17 = (l11 * l16) - (l12 * l15);
  1204. var l18 = (l10 * l16) - (l12 * l14);
  1205. var l19 = (l10 * l15) - (l11 * l14);
  1206. var l20 = (l9 * l16) - (l12 * l13);
  1207. var l21 = (l9 * l15) - (l11 * l13);
  1208. var l22 = (l9 * l14) - (l10 * l13);
  1209. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1210. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1211. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1212. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1213. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1214. var l28 = (l7 * l16) - (l8 * l15);
  1215. var l29 = (l6 * l16) - (l8 * l14);
  1216. var l30 = (l6 * l15) - (l7 * l14);
  1217. var l31 = (l5 * l16) - (l8 * l13);
  1218. var l32 = (l5 * l15) - (l7 * l13);
  1219. var l33 = (l5 * l14) - (l6 * l13);
  1220. var l34 = (l7 * l12) - (l8 * l11);
  1221. var l35 = (l6 * l12) - (l8 * l10);
  1222. var l36 = (l6 * l11) - (l7 * l10);
  1223. var l37 = (l5 * l12) - (l8 * l9);
  1224. var l38 = (l5 * l11) - (l7 * l9);
  1225. var l39 = (l5 * l10) - (l6 * l9);
  1226. other.m[0] = l23 * l27;
  1227. other.m[4] = l24 * l27;
  1228. other.m[8] = l25 * l27;
  1229. other.m[12] = l26 * l27;
  1230. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1231. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1232. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1233. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1234. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1235. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1236. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1237. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1238. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1239. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1240. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1241. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1242. };
  1243. Matrix.prototype.setTranslation = function (vector3) {
  1244. this.m[12] = vector3.x;
  1245. this.m[13] = vector3.y;
  1246. this.m[14] = vector3.z;
  1247. };
  1248. Matrix.prototype.multiply = function (other) {
  1249. var result = new Matrix();
  1250. this.multiplyToRef(other, result);
  1251. return result;
  1252. };
  1253. Matrix.prototype.copyFrom = function (other) {
  1254. for (var index = 0; index < 16; index++) {
  1255. this.m[index] = other.m[index];
  1256. }
  1257. };
  1258. Matrix.prototype.copyToArray = function (array, offset) {
  1259. if (typeof offset === "undefined") { offset = 0; }
  1260. for (var index = 0; index < 16; index++) {
  1261. array[offset + index] = this.m[index];
  1262. }
  1263. };
  1264. Matrix.prototype.multiplyToRef = function (other, result) {
  1265. this.multiplyToArray(other, result.m, 0);
  1266. };
  1267. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1268. var tm0 = this.m[0];
  1269. var tm1 = this.m[1];
  1270. var tm2 = this.m[2];
  1271. var tm3 = this.m[3];
  1272. var tm4 = this.m[4];
  1273. var tm5 = this.m[5];
  1274. var tm6 = this.m[6];
  1275. var tm7 = this.m[7];
  1276. var tm8 = this.m[8];
  1277. var tm9 = this.m[9];
  1278. var tm10 = this.m[10];
  1279. var tm11 = this.m[11];
  1280. var tm12 = this.m[12];
  1281. var tm13 = this.m[13];
  1282. var tm14 = this.m[14];
  1283. var tm15 = this.m[15];
  1284. var om0 = other.m[0];
  1285. var om1 = other.m[1];
  1286. var om2 = other.m[2];
  1287. var om3 = other.m[3];
  1288. var om4 = other.m[4];
  1289. var om5 = other.m[5];
  1290. var om6 = other.m[6];
  1291. var om7 = other.m[7];
  1292. var om8 = other.m[8];
  1293. var om9 = other.m[9];
  1294. var om10 = other.m[10];
  1295. var om11 = other.m[11];
  1296. var om12 = other.m[12];
  1297. var om13 = other.m[13];
  1298. var om14 = other.m[14];
  1299. var om15 = other.m[15];
  1300. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1301. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1302. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1303. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1304. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1305. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1306. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1307. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1308. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1309. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1310. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1311. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1312. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1313. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1314. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1315. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1316. };
  1317. Matrix.prototype.equals = function (value) {
  1318. 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]);
  1319. };
  1320. Matrix.prototype.clone = function () {
  1321. 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]);
  1322. };
  1323. Matrix.FromArray = function (array, offset) {
  1324. var result = new Matrix();
  1325. if (!offset) {
  1326. offset = 0;
  1327. }
  1328. Matrix.FromArrayToRef(array, offset, result);
  1329. return result;
  1330. };
  1331. Matrix.FromArrayToRef = function (array, offset, result) {
  1332. for (var index = 0; index < 16; index++) {
  1333. result.m[index] = array[index + offset];
  1334. }
  1335. };
  1336. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1337. result.m[0] = initialM11;
  1338. result.m[1] = initialM12;
  1339. result.m[2] = initialM13;
  1340. result.m[3] = initialM14;
  1341. result.m[4] = initialM21;
  1342. result.m[5] = initialM22;
  1343. result.m[6] = initialM23;
  1344. result.m[7] = initialM24;
  1345. result.m[8] = initialM31;
  1346. result.m[9] = initialM32;
  1347. result.m[10] = initialM33;
  1348. result.m[11] = initialM34;
  1349. result.m[12] = initialM41;
  1350. result.m[13] = initialM42;
  1351. result.m[14] = initialM43;
  1352. result.m[15] = initialM44;
  1353. };
  1354. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1355. var result = new Matrix();
  1356. result.m[0] = initialM11;
  1357. result.m[1] = initialM12;
  1358. result.m[2] = initialM13;
  1359. result.m[3] = initialM14;
  1360. result.m[4] = initialM21;
  1361. result.m[5] = initialM22;
  1362. result.m[6] = initialM23;
  1363. result.m[7] = initialM24;
  1364. result.m[8] = initialM31;
  1365. result.m[9] = initialM32;
  1366. result.m[10] = initialM33;
  1367. result.m[11] = initialM34;
  1368. result.m[12] = initialM41;
  1369. result.m[13] = initialM42;
  1370. result.m[14] = initialM43;
  1371. result.m[15] = initialM44;
  1372. return result;
  1373. };
  1374. Matrix.Identity = function () {
  1375. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1376. };
  1377. Matrix.IdentityToRef = function (result) {
  1378. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1379. };
  1380. Matrix.Zero = function () {
  1381. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1382. };
  1383. Matrix.RotationX = function (angle) {
  1384. var result = new Matrix();
  1385. Matrix.RotationXToRef(angle, result);
  1386. return result;
  1387. };
  1388. Matrix.RotationXToRef = function (angle, result) {
  1389. var s = Math.sin(angle);
  1390. var c = Math.cos(angle);
  1391. result.m[0] = 1.0;
  1392. result.m[15] = 1.0;
  1393. result.m[5] = c;
  1394. result.m[10] = c;
  1395. result.m[9] = -s;
  1396. result.m[6] = s;
  1397. result.m[1] = 0;
  1398. result.m[2] = 0;
  1399. result.m[3] = 0;
  1400. result.m[4] = 0;
  1401. result.m[7] = 0;
  1402. result.m[8] = 0;
  1403. result.m[11] = 0;
  1404. result.m[12] = 0;
  1405. result.m[13] = 0;
  1406. result.m[14] = 0;
  1407. };
  1408. Matrix.RotationY = function (angle) {
  1409. var result = new Matrix();
  1410. Matrix.RotationYToRef(angle, result);
  1411. return result;
  1412. };
  1413. Matrix.RotationYToRef = function (angle, result) {
  1414. var s = Math.sin(angle);
  1415. var c = Math.cos(angle);
  1416. result.m[5] = 1.0;
  1417. result.m[15] = 1.0;
  1418. result.m[0] = c;
  1419. result.m[2] = -s;
  1420. result.m[8] = s;
  1421. result.m[10] = c;
  1422. result.m[1] = 0;
  1423. result.m[3] = 0;
  1424. result.m[4] = 0;
  1425. result.m[6] = 0;
  1426. result.m[7] = 0;
  1427. result.m[9] = 0;
  1428. result.m[11] = 0;
  1429. result.m[12] = 0;
  1430. result.m[13] = 0;
  1431. result.m[14] = 0;
  1432. };
  1433. Matrix.RotationZ = function (angle) {
  1434. var result = new Matrix();
  1435. Matrix.RotationZToRef(angle, result);
  1436. return result;
  1437. };
  1438. Matrix.RotationZToRef = function (angle, result) {
  1439. var s = Math.sin(angle);
  1440. var c = Math.cos(angle);
  1441. result.m[10] = 1.0;
  1442. result.m[15] = 1.0;
  1443. result.m[0] = c;
  1444. result.m[1] = s;
  1445. result.m[4] = -s;
  1446. result.m[5] = c;
  1447. result.m[2] = 0;
  1448. result.m[3] = 0;
  1449. result.m[6] = 0;
  1450. result.m[7] = 0;
  1451. result.m[8] = 0;
  1452. result.m[9] = 0;
  1453. result.m[11] = 0;
  1454. result.m[12] = 0;
  1455. result.m[13] = 0;
  1456. result.m[14] = 0;
  1457. };
  1458. Matrix.RotationAxis = function (axis, angle) {
  1459. var s = Math.sin(-angle);
  1460. var c = Math.cos(-angle);
  1461. var c1 = 1 - c;
  1462. axis.normalize();
  1463. var result = Matrix.Zero();
  1464. result.m[0] = (axis.x * axis.x) * c1 + c;
  1465. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1466. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1467. result.m[3] = 0.0;
  1468. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1469. result.m[5] = (axis.y * axis.y) * c1 + c;
  1470. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1471. result.m[7] = 0.0;
  1472. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1473. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1474. result.m[10] = (axis.z * axis.z) * c1 + c;
  1475. result.m[11] = 0.0;
  1476. result.m[15] = 1.0;
  1477. return result;
  1478. };
  1479. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1480. var result = new Matrix();
  1481. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1482. return result;
  1483. };
  1484. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1485. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1486. this._tempQuaternion.toRotationMatrix(result);
  1487. };
  1488. Matrix.Scaling = function (x, y, z) {
  1489. var result = Matrix.Zero();
  1490. Matrix.ScalingToRef(x, y, z, result);
  1491. return result;
  1492. };
  1493. Matrix.ScalingToRef = function (x, y, z, result) {
  1494. result.m[0] = x;
  1495. result.m[1] = 0;
  1496. result.m[2] = 0;
  1497. result.m[3] = 0;
  1498. result.m[4] = 0;
  1499. result.m[5] = y;
  1500. result.m[6] = 0;
  1501. result.m[7] = 0;
  1502. result.m[8] = 0;
  1503. result.m[9] = 0;
  1504. result.m[10] = z;
  1505. result.m[11] = 0;
  1506. result.m[12] = 0;
  1507. result.m[13] = 0;
  1508. result.m[14] = 0;
  1509. result.m[15] = 1.0;
  1510. };
  1511. Matrix.Translation = function (x, y, z) {
  1512. var result = Matrix.Identity();
  1513. Matrix.TranslationToRef(x, y, z, result);
  1514. return result;
  1515. };
  1516. Matrix.TranslationToRef = function (x, y, z, result) {
  1517. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1518. };
  1519. Matrix.LookAtLH = function (eye, target, up) {
  1520. var result = Matrix.Zero();
  1521. Matrix.LookAtLHToRef(eye, target, up, result);
  1522. return result;
  1523. };
  1524. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1525. target.subtractToRef(eye, this._zAxis);
  1526. this._zAxis.normalize();
  1527. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1528. this._xAxis.normalize();
  1529. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1530. this._yAxis.normalize();
  1531. var ex = -Vector3.Dot(this._xAxis, eye);
  1532. var ey = -Vector3.Dot(this._yAxis, eye);
  1533. var ez = -Vector3.Dot(this._zAxis, eye);
  1534. 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);
  1535. };
  1536. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1537. var hw = 2.0 / width;
  1538. var hh = 2.0 / height;
  1539. var id = 1.0 / (zfar - znear);
  1540. var nid = znear / (znear - zfar);
  1541. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1542. };
  1543. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1544. var matrix = Matrix.Zero();
  1545. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1546. return matrix;
  1547. };
  1548. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1549. result.m[0] = 2.0 / (right - left);
  1550. result.m[1] = result.m[2] = result.m[3] = 0;
  1551. result.m[5] = 2.0 / (top - bottom);
  1552. result.m[4] = result.m[6] = result.m[7] = 0;
  1553. result.m[10] = -1.0 / (znear - zfar);
  1554. result.m[8] = result.m[9] = result.m[11] = 0;
  1555. result.m[12] = (left + right) / (left - right);
  1556. result.m[13] = (top + bottom) / (bottom - top);
  1557. result.m[14] = znear / (znear - zfar);
  1558. result.m[15] = 1.0;
  1559. };
  1560. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1561. var matrix = Matrix.Zero();
  1562. matrix.m[0] = (2.0 * znear) / width;
  1563. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1564. matrix.m[5] = (2.0 * znear) / height;
  1565. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1566. matrix.m[10] = -zfar / (znear - zfar);
  1567. matrix.m[8] = matrix.m[9] = 0.0;
  1568. matrix.m[11] = 1.0;
  1569. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1570. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1571. return matrix;
  1572. };
  1573. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1574. var matrix = Matrix.Zero();
  1575. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1576. return matrix;
  1577. };
  1578. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1579. var tan = 1.0 / (Math.tan(fov * 0.5));
  1580. result.m[0] = tan / aspect;
  1581. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1582. result.m[5] = tan;
  1583. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1584. result.m[8] = result.m[9] = 0.0;
  1585. result.m[10] = -zfar / (znear - zfar);
  1586. result.m[11] = 1.0;
  1587. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1588. result.m[14] = (znear * zfar) / (znear - zfar);
  1589. };
  1590. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1591. var cw = viewport.width;
  1592. var ch = viewport.height;
  1593. var cx = viewport.x;
  1594. var cy = viewport.y;
  1595. 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);
  1596. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1597. };
  1598. Matrix.Transpose = function (matrix) {
  1599. var result = new Matrix();
  1600. result.m[0] = matrix.m[0];
  1601. result.m[1] = matrix.m[4];
  1602. result.m[2] = matrix.m[8];
  1603. result.m[3] = matrix.m[12];
  1604. result.m[4] = matrix.m[1];
  1605. result.m[5] = matrix.m[5];
  1606. result.m[6] = matrix.m[9];
  1607. result.m[7] = matrix.m[13];
  1608. result.m[8] = matrix.m[2];
  1609. result.m[9] = matrix.m[6];
  1610. result.m[10] = matrix.m[10];
  1611. result.m[11] = matrix.m[14];
  1612. result.m[12] = matrix.m[3];
  1613. result.m[13] = matrix.m[7];
  1614. result.m[14] = matrix.m[11];
  1615. result.m[15] = matrix.m[15];
  1616. return result;
  1617. };
  1618. Matrix.Reflection = function (plane) {
  1619. var matrix = new Matrix();
  1620. Matrix.ReflectionToRef(plane, matrix);
  1621. return matrix;
  1622. };
  1623. Matrix.ReflectionToRef = function (plane, result) {
  1624. plane.normalize();
  1625. var x = plane.normal.x;
  1626. var y = plane.normal.y;
  1627. var z = plane.normal.z;
  1628. var temp = -2 * x;
  1629. var temp2 = -2 * y;
  1630. var temp3 = -2 * z;
  1631. result.m[0] = (temp * x) + 1;
  1632. result.m[1] = temp2 * x;
  1633. result.m[2] = temp3 * x;
  1634. result.m[3] = 0.0;
  1635. result.m[4] = temp * y;
  1636. result.m[5] = (temp2 * y) + 1;
  1637. result.m[6] = temp3 * y;
  1638. result.m[7] = 0.0;
  1639. result.m[8] = temp * z;
  1640. result.m[9] = temp2 * z;
  1641. result.m[10] = (temp3 * z) + 1;
  1642. result.m[11] = 0.0;
  1643. result.m[12] = temp * plane.d;
  1644. result.m[13] = temp2 * plane.d;
  1645. result.m[14] = temp3 * plane.d;
  1646. result.m[15] = 1.0;
  1647. };
  1648. Matrix._tempQuaternion = new Quaternion();
  1649. Matrix._xAxis = Vector3.Zero();
  1650. Matrix._yAxis = Vector3.Zero();
  1651. Matrix._zAxis = Vector3.Zero();
  1652. return Matrix;
  1653. })();
  1654. BABYLON.Matrix = Matrix;
  1655. var Plane = (function () {
  1656. function Plane(a, b, c, d) {
  1657. this.normal = new Vector3(a, b, c);
  1658. this.d = d;
  1659. }
  1660. Plane.prototype.asArray = function () {
  1661. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1662. };
  1663. Plane.prototype.clone = function () {
  1664. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1665. };
  1666. Plane.prototype.normalize = function () {
  1667. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1668. var magnitude = 0;
  1669. if (norm != 0) {
  1670. magnitude = 1.0 / norm;
  1671. }
  1672. this.normal.x *= magnitude;
  1673. this.normal.y *= magnitude;
  1674. this.normal.z *= magnitude;
  1675. this.d *= magnitude;
  1676. };
  1677. Plane.prototype.transform = function (transformation) {
  1678. var transposedMatrix = BABYLON.Matrix.Transpose(transformation);
  1679. var x = this.normal.x;
  1680. var y = this.normal.y;
  1681. var z = this.normal.z;
  1682. var d = this.d;
  1683. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1684. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1685. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1686. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1687. return new BABYLON.Plane(normalX, normalY, normalZ, finalD);
  1688. };
  1689. Plane.prototype.dotCoordinate = function (point) {
  1690. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1691. };
  1692. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1693. var x1 = point2.x - point1.x;
  1694. var y1 = point2.y - point1.y;
  1695. var z1 = point2.z - point1.z;
  1696. var x2 = point3.x - point1.x;
  1697. var y2 = point3.y - point1.y;
  1698. var z2 = point3.z - point1.z;
  1699. var yz = (y1 * z2) - (z1 * y2);
  1700. var xz = (z1 * x2) - (x1 * z2);
  1701. var xy = (x1 * y2) - (y1 * x2);
  1702. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1703. var invPyth;
  1704. if (pyth != 0) {
  1705. invPyth = 1.0 / pyth;
  1706. } else {
  1707. invPyth = 0;
  1708. }
  1709. this.normal.x = yz * invPyth;
  1710. this.normal.y = xz * invPyth;
  1711. this.normal.z = xy * invPyth;
  1712. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1713. };
  1714. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1715. var dot = Vector3.Dot(this.normal, direction);
  1716. return (dot <= epsilon);
  1717. };
  1718. Plane.prototype.signedDistanceTo = function (point) {
  1719. return Vector3.Dot(point, this.normal) + this.d;
  1720. };
  1721. Plane.FromArray = function (array) {
  1722. return new BABYLON.Plane(array[0], array[1], array[2], array[3]);
  1723. };
  1724. Plane.FromPoints = function (point1, point2, point3) {
  1725. var result = new BABYLON.Plane(0, 0, 0, 0);
  1726. result.copyFromPoints(point1, point2, point3);
  1727. return result;
  1728. };
  1729. Plane.FromPositionAndNormal = function (origin, normal) {
  1730. var result = new BABYLON.Plane(0, 0, 0, 0);
  1731. normal.normalize();
  1732. result.normal = normal;
  1733. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1734. return result;
  1735. };
  1736. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1737. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1738. return Vector3.Dot(point, normal) + d;
  1739. };
  1740. return Plane;
  1741. })();
  1742. BABYLON.Plane = Plane;
  1743. var Viewport = (function () {
  1744. function Viewport(x, y, width, height) {
  1745. this.x = x;
  1746. this.y = y;
  1747. this.width = width;
  1748. this.height = height;
  1749. }
  1750. Viewport.prototype.toGlobal = function (engine) {
  1751. var width = engine.getRenderWidth();
  1752. var height = engine.getRenderHeight();
  1753. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1754. };
  1755. return Viewport;
  1756. })();
  1757. BABYLON.Viewport = Viewport;
  1758. var Frustum = (function () {
  1759. function Frustum() {
  1760. }
  1761. Frustum.GetPlanes = function (transform) {
  1762. var frustumPlanes = [];
  1763. for (var index = 0; index < 6; index++) {
  1764. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1765. }
  1766. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1767. return frustumPlanes;
  1768. };
  1769. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1770. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1771. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1772. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1773. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1774. frustumPlanes[0].normalize();
  1775. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1776. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1777. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1778. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1779. frustumPlanes[1].normalize();
  1780. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1781. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1782. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1783. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1784. frustumPlanes[2].normalize();
  1785. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1786. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1787. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1788. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1789. frustumPlanes[3].normalize();
  1790. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1791. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1792. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1793. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1794. frustumPlanes[4].normalize();
  1795. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1796. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1797. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1798. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1799. frustumPlanes[5].normalize();
  1800. };
  1801. return Frustum;
  1802. })();
  1803. BABYLON.Frustum = Frustum;
  1804. var Ray = (function () {
  1805. function Ray(origin, direction) {
  1806. this.origin = origin;
  1807. this.direction = direction;
  1808. }
  1809. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1810. var d = 0.0;
  1811. var maxValue = Number.MAX_VALUE;
  1812. if (Math.abs(this.direction.x) < 0.0000001) {
  1813. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1814. return false;
  1815. }
  1816. } else {
  1817. var inv = 1.0 / this.direction.x;
  1818. var min = (minimum.x - this.origin.x) * inv;
  1819. var max = (maximum.x - this.origin.x) * inv;
  1820. if (min > max) {
  1821. var temp = min;
  1822. min = max;
  1823. max = temp;
  1824. }
  1825. d = Math.max(min, d);
  1826. maxValue = Math.min(max, maxValue);
  1827. if (d > maxValue) {
  1828. return false;
  1829. }
  1830. }
  1831. if (Math.abs(this.direction.y) < 0.0000001) {
  1832. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1833. return false;
  1834. }
  1835. } else {
  1836. inv = 1.0 / this.direction.y;
  1837. min = (minimum.y - this.origin.y) * inv;
  1838. max = (maximum.y - this.origin.y) * inv;
  1839. if (min > max) {
  1840. temp = min;
  1841. min = max;
  1842. max = temp;
  1843. }
  1844. d = Math.max(min, d);
  1845. maxValue = Math.min(max, maxValue);
  1846. if (d > maxValue) {
  1847. return false;
  1848. }
  1849. }
  1850. if (Math.abs(this.direction.z) < 0.0000001) {
  1851. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1852. return false;
  1853. }
  1854. } else {
  1855. inv = 1.0 / this.direction.z;
  1856. min = (minimum.z - this.origin.z) * inv;
  1857. max = (maximum.z - this.origin.z) * inv;
  1858. if (min > max) {
  1859. temp = min;
  1860. min = max;
  1861. max = temp;
  1862. }
  1863. d = Math.max(min, d);
  1864. maxValue = Math.min(max, maxValue);
  1865. if (d > maxValue) {
  1866. return false;
  1867. }
  1868. }
  1869. return true;
  1870. };
  1871. Ray.prototype.intersectsBox = function (box) {
  1872. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1873. };
  1874. Ray.prototype.intersectsSphere = function (sphere) {
  1875. var x = sphere.center.x - this.origin.x;
  1876. var y = sphere.center.y - this.origin.y;
  1877. var z = sphere.center.z - this.origin.z;
  1878. var pyth = (x * x) + (y * y) + (z * z);
  1879. var rr = sphere.radius * sphere.radius;
  1880. if (pyth <= rr) {
  1881. return true;
  1882. }
  1883. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1884. if (dot < 0.0) {
  1885. return false;
  1886. }
  1887. var temp = pyth - (dot * dot);
  1888. return temp <= rr;
  1889. };
  1890. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1891. if (!this._edge1) {
  1892. this._edge1 = BABYLON.Vector3.Zero();
  1893. this._edge2 = BABYLON.Vector3.Zero();
  1894. this._pvec = BABYLON.Vector3.Zero();
  1895. this._tvec = BABYLON.Vector3.Zero();
  1896. this._qvec = BABYLON.Vector3.Zero();
  1897. }
  1898. vertex1.subtractToRef(vertex0, this._edge1);
  1899. vertex2.subtractToRef(vertex0, this._edge2);
  1900. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1901. var det = Vector3.Dot(this._edge1, this._pvec);
  1902. if (det === 0) {
  1903. return null;
  1904. }
  1905. var invdet = 1 / det;
  1906. this.origin.subtractToRef(vertex0, this._tvec);
  1907. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1908. if (bu < 0 || bu > 1.0) {
  1909. return null;
  1910. }
  1911. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1912. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1913. if (bv < 0 || bu + bv > 1.0) {
  1914. return null;
  1915. }
  1916. return new BABYLON.IntersectionInfo(bu, bv, Vector3.Dot(this._edge2, this._qvec) * invdet);
  1917. };
  1918. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1919. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1920. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1921. var direction = end.subtract(start);
  1922. direction.normalize();
  1923. return new Ray(start, direction);
  1924. };
  1925. Ray.Transform = function (ray, matrix) {
  1926. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  1927. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  1928. return new Ray(newOrigin, newDirection);
  1929. };
  1930. return Ray;
  1931. })();
  1932. BABYLON.Ray = Ray;
  1933. (function (Space) {
  1934. Space[Space["LOCAL"] = 0] = "LOCAL";
  1935. Space[Space["WORLD"] = 1] = "WORLD";
  1936. })(BABYLON.Space || (BABYLON.Space = {}));
  1937. var Space = BABYLON.Space;
  1938. var Axis = (function () {
  1939. function Axis() {
  1940. }
  1941. Axis.X = new BABYLON.Vector3(1, 0, 0);
  1942. Axis.Y = new BABYLON.Vector3(0, 1, 0);
  1943. Axis.Z = new BABYLON.Vector3(0, 0, 1);
  1944. return Axis;
  1945. })();
  1946. BABYLON.Axis = Axis;
  1947. ;
  1948. })(BABYLON || (BABYLON = {}));
  1949. var BABYLON;
  1950. (function (BABYLON) {
  1951. var screenshotCanvas;
  1952. var fpsRange = 60;
  1953. var previousFramesDuration = [];
  1954. var fps = 60;
  1955. var deltaTime = 0;
  1956. var cloneValue = function (source, destinationObject) {
  1957. if (!source)
  1958. return null;
  1959. if (source instanceof BABYLON.Mesh) {
  1960. return null;
  1961. }
  1962. if (source instanceof BABYLON.SubMesh) {
  1963. return source.clone(destinationObject);
  1964. } else if (source.clone) {
  1965. return source.clone();
  1966. }
  1967. return null;
  1968. };
  1969. var Tools = (function () {
  1970. function Tools() {
  1971. }
  1972. Tools.GetFilename = function (path) {
  1973. var index = path.lastIndexOf("/");
  1974. if (index < 0)
  1975. return path;
  1976. return path.substring(index + 1);
  1977. };
  1978. Tools.GetDOMTextContent = function (element) {
  1979. var result = "";
  1980. var child = element.firstChild;
  1981. while (child) {
  1982. if (child.nodeType == 3) {
  1983. result += child.textContent;
  1984. }
  1985. child = child.nextSibling;
  1986. }
  1987. return result;
  1988. };
  1989. Tools.ToDegrees = function (angle) {
  1990. return angle * 180 / Math.PI;
  1991. };
  1992. Tools.ToRadians = function (angle) {
  1993. return angle * Math.PI / 180;
  1994. };
  1995. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  1996. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1997. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1998. for (var index = indexStart; index < indexStart + indexCount; index++) {
  1999. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2000. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2001. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2002. }
  2003. return {
  2004. minimum: minimum,
  2005. maximum: maximum
  2006. };
  2007. };
  2008. Tools.ExtractMinAndMax = function (positions, start, count) {
  2009. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2010. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2011. for (var index = start; index < start + count; index++) {
  2012. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2013. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2014. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2015. }
  2016. return {
  2017. minimum: minimum,
  2018. maximum: maximum
  2019. };
  2020. };
  2021. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2022. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2023. return undefined;
  2024. return Array.isArray(obj) ? obj : [obj];
  2025. };
  2026. Tools.GetPointerPrefix = function () {
  2027. var eventPrefix = "pointer";
  2028. if (!navigator.pointerEnabled) {
  2029. eventPrefix = "mouse";
  2030. }
  2031. return eventPrefix;
  2032. };
  2033. Tools.QueueNewFrame = function (func) {
  2034. if (window.requestAnimationFrame)
  2035. window.requestAnimationFrame(func);
  2036. else if (window.msRequestAnimationFrame)
  2037. window.msRequestAnimationFrame(func);
  2038. else if (window.webkitRequestAnimationFrame)
  2039. window.webkitRequestAnimationFrame(func);
  2040. else if (window.mozRequestAnimationFrame)
  2041. window.mozRequestAnimationFrame(func);
  2042. else if (window.oRequestAnimationFrame)
  2043. window.oRequestAnimationFrame(func);
  2044. else {
  2045. window.setTimeout(func, 16);
  2046. }
  2047. };
  2048. Tools.RequestFullscreen = function (element) {
  2049. if (element.requestFullscreen)
  2050. element.requestFullscreen();
  2051. else if (element.msRequestFullscreen)
  2052. element.msRequestFullscreen();
  2053. else if (element.webkitRequestFullscreen)
  2054. element.webkitRequestFullscreen();
  2055. else if (element.mozRequestFullScreen)
  2056. element.mozRequestFullScreen();
  2057. };
  2058. Tools.ExitFullscreen = function () {
  2059. if (document.exitFullscreen) {
  2060. document.exitFullscreen();
  2061. } else if (document.mozCancelFullScreen) {
  2062. document.mozCancelFullScreen();
  2063. } else if (document.webkitCancelFullScreen) {
  2064. document.webkitCancelFullScreen();
  2065. } else if (document.msCancelFullScreen) {
  2066. document.msCancelFullScreen();
  2067. }
  2068. };
  2069. Tools.CleanUrl = function (url) {
  2070. url = url.replace(/#/mg, "%23");
  2071. return url;
  2072. };
  2073. Tools.LoadImage = function (url, onload, onerror, database) {
  2074. url = Tools.CleanUrl(url);
  2075. var img = new Image();
  2076. if (url.substr(0, 5) != "data:")
  2077. img.crossOrigin = 'anonymous';
  2078. img.onload = function () {
  2079. onload(img);
  2080. };
  2081. img.onerror = function (err) {
  2082. onerror(img, err);
  2083. };
  2084. var noIndexedDB = function () {
  2085. img.src = url;
  2086. };
  2087. var loadFromIndexedDB = function () {
  2088. database.loadImageFromDB(url, img);
  2089. };
  2090. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2091. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2092. } else {
  2093. if (url.indexOf("file:") === -1) {
  2094. noIndexedDB();
  2095. } else {
  2096. try {
  2097. var textureName = url.substring(5);
  2098. var blobURL;
  2099. try {
  2100. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2101. } catch (ex) {
  2102. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2103. }
  2104. img.src = blobURL;
  2105. } catch (e) {
  2106. Tools.Log("Error while trying to load texture: " + textureName);
  2107. img.src = null;
  2108. }
  2109. }
  2110. }
  2111. return img;
  2112. };
  2113. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2114. url = Tools.CleanUrl(url);
  2115. var noIndexedDB = function () {
  2116. var request = new XMLHttpRequest();
  2117. var loadUrl = Tools.BaseUrl + url;
  2118. request.open('GET', loadUrl, true);
  2119. if (useArrayBuffer) {
  2120. request.responseType = "arraybuffer";
  2121. }
  2122. request.onprogress = progressCallBack;
  2123. request.onreadystatechange = function () {
  2124. if (request.readyState == 4) {
  2125. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2126. callback(!useArrayBuffer ? request.responseText : request.response);
  2127. } else {
  2128. if (onError) {
  2129. onError();
  2130. } else {
  2131. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2132. }
  2133. }
  2134. }
  2135. };
  2136. request.send(null);
  2137. };
  2138. var loadFromIndexedDB = function () {
  2139. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2140. };
  2141. if (url.indexOf("file:") !== -1) {
  2142. var fileName = url.substring(5);
  2143. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2144. } else {
  2145. if (database && database.enableSceneOffline) {
  2146. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2147. } else {
  2148. noIndexedDB();
  2149. }
  2150. }
  2151. };
  2152. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2153. var reader = new FileReader();
  2154. reader.onload = function (e) {
  2155. callback(e.target.result);
  2156. };
  2157. reader.onprogress = progressCallback;
  2158. reader.readAsDataURL(fileToLoad);
  2159. };
  2160. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2161. var reader = new FileReader();
  2162. reader.onload = function (e) {
  2163. callback(e.target.result);
  2164. };
  2165. reader.onprogress = progressCallBack;
  2166. if (!useArrayBuffer) {
  2167. reader.readAsText(fileToLoad);
  2168. } else {
  2169. reader.readAsArrayBuffer(fileToLoad);
  2170. }
  2171. };
  2172. Tools.CheckExtends = function (v, min, max) {
  2173. if (v.x < min.x)
  2174. min.x = v.x;
  2175. if (v.y < min.y)
  2176. min.y = v.y;
  2177. if (v.z < min.z)
  2178. min.z = v.z;
  2179. if (v.x > max.x)
  2180. max.x = v.x;
  2181. if (v.y > max.y)
  2182. max.y = v.y;
  2183. if (v.z > max.z)
  2184. max.z = v.z;
  2185. };
  2186. Tools.WithinEpsilon = function (a, b) {
  2187. var num = a - b;
  2188. return -1.401298E-45 <= num && num <= 1.401298E-45;
  2189. };
  2190. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2191. for (var prop in source) {
  2192. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2193. continue;
  2194. }
  2195. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2196. continue;
  2197. }
  2198. var sourceValue = source[prop];
  2199. var typeOfSourceValue = typeof sourceValue;
  2200. if (typeOfSourceValue == "function") {
  2201. continue;
  2202. }
  2203. if (typeOfSourceValue == "object") {
  2204. if (sourceValue instanceof Array) {
  2205. destination[prop] = [];
  2206. if (sourceValue.length > 0) {
  2207. if (typeof sourceValue[0] == "object") {
  2208. for (var index = 0; index < sourceValue.length; index++) {
  2209. var clonedValue = cloneValue(sourceValue[index], destination);
  2210. if (destination[prop].indexOf(clonedValue) === -1) {
  2211. destination[prop].push(clonedValue);
  2212. }
  2213. }
  2214. } else {
  2215. destination[prop] = sourceValue.slice(0);
  2216. }
  2217. }
  2218. } else {
  2219. destination[prop] = cloneValue(sourceValue, destination);
  2220. }
  2221. } else {
  2222. destination[prop] = sourceValue;
  2223. }
  2224. }
  2225. };
  2226. Tools.IsEmpty = function (obj) {
  2227. for (var i in obj) {
  2228. return false;
  2229. }
  2230. return true;
  2231. };
  2232. Tools.RegisterTopRootEvents = function (events) {
  2233. for (var index = 0; index < events.length; index++) {
  2234. var event = events[index];
  2235. window.addEventListener(event.name, event.handler, false);
  2236. try {
  2237. if (window.parent) {
  2238. window.parent.addEventListener(event.name, event.handler, false);
  2239. }
  2240. } catch (e) {
  2241. }
  2242. }
  2243. };
  2244. Tools.UnregisterTopRootEvents = function (events) {
  2245. for (var index = 0; index < events.length; index++) {
  2246. var event = events[index];
  2247. window.removeEventListener(event.name, event.handler);
  2248. try {
  2249. if (window.parent) {
  2250. window.parent.removeEventListener(event.name, event.handler);
  2251. }
  2252. } catch (e) {
  2253. }
  2254. }
  2255. };
  2256. Tools.GetFps = function () {
  2257. return fps;
  2258. };
  2259. Tools.GetDeltaTime = function () {
  2260. return deltaTime;
  2261. };
  2262. Tools._MeasureFps = function () {
  2263. previousFramesDuration.push(Tools.Now);
  2264. var length = previousFramesDuration.length;
  2265. if (length >= 2) {
  2266. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  2267. }
  2268. if (length >= fpsRange) {
  2269. if (length > fpsRange) {
  2270. previousFramesDuration.splice(0, 1);
  2271. length = previousFramesDuration.length;
  2272. }
  2273. var sum = 0;
  2274. for (var id = 0; id < length - 1; id++) {
  2275. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  2276. }
  2277. fps = 1000.0 / (sum / (length - 1));
  2278. }
  2279. };
  2280. Tools.CreateScreenshot = function (engine, camera, size) {
  2281. var width;
  2282. var height;
  2283. var scene = camera.getScene();
  2284. var previousCamera = null;
  2285. if (scene.activeCamera !== camera) {
  2286. previousCamera = scene.activeCamera;
  2287. scene.activeCamera = camera;
  2288. }
  2289. if (size.precision) {
  2290. width = Math.round(engine.getRenderWidth() * size.precision);
  2291. height = Math.round(width / engine.getAspectRatio(camera));
  2292. size = { width: width, height: height };
  2293. } else if (size.width && size.height) {
  2294. width = size.width;
  2295. height = size.height;
  2296. } else if (size.width && !size.height) {
  2297. width = size.width;
  2298. height = Math.round(width / engine.getAspectRatio(camera));
  2299. size = { width: width, height: height };
  2300. } else if (size.height && !size.width) {
  2301. height = size.height;
  2302. width = Math.round(height * engine.getAspectRatio(camera));
  2303. size = { width: width, height: height };
  2304. } else if (!isNaN(size)) {
  2305. height = size;
  2306. width = size;
  2307. } else {
  2308. Tools.Error("Invalid 'size' parameter !");
  2309. return;
  2310. }
  2311. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2312. texture.renderList = engine.scenes[0].meshes;
  2313. texture.onAfterRender = function () {
  2314. var numberOfChannelsByLine = width * 4;
  2315. var halfHeight = height / 2;
  2316. var data = engine.readPixels(0, 0, width, height);
  2317. for (var i = 0; i < halfHeight; i++) {
  2318. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2319. var currentCell = j + i * numberOfChannelsByLine;
  2320. var targetLine = height - i - 1;
  2321. var targetCell = j + targetLine * numberOfChannelsByLine;
  2322. var temp = data[currentCell];
  2323. data[currentCell] = data[targetCell];
  2324. data[targetCell] = temp;
  2325. }
  2326. }
  2327. if (!screenshotCanvas) {
  2328. screenshotCanvas = document.createElement('canvas');
  2329. }
  2330. screenshotCanvas.width = width;
  2331. screenshotCanvas.height = height;
  2332. var context = screenshotCanvas.getContext('2d');
  2333. var imageData = context.createImageData(width, height);
  2334. imageData.data.set(data);
  2335. context.putImageData(imageData, 0, 0);
  2336. var base64Image = screenshotCanvas.toDataURL();
  2337. if (("download" in document.createElement("a"))) {
  2338. var a = window.document.createElement("a");
  2339. a.href = base64Image;
  2340. var date = new Date();
  2341. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2342. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2343. window.document.body.appendChild(a);
  2344. a.addEventListener("click", function () {
  2345. a.parentElement.removeChild(a);
  2346. });
  2347. a.click();
  2348. } else {
  2349. var newWindow = window.open("");
  2350. var img = newWindow.document.createElement("img");
  2351. img.src = base64Image;
  2352. newWindow.document.body.appendChild(img);
  2353. }
  2354. };
  2355. texture.render(true);
  2356. texture.dispose();
  2357. if (previousCamera) {
  2358. scene.activeCamera = previousCamera;
  2359. }
  2360. };
  2361. Tools.ValidateXHRData = function (xhr, dataType) {
  2362. if (typeof dataType === "undefined") { dataType = 7; }
  2363. try {
  2364. if (dataType & 1) {
  2365. if (xhr.responseText && xhr.responseText.length > 0) {
  2366. return true;
  2367. } else if (dataType === 1) {
  2368. return false;
  2369. }
  2370. }
  2371. if (dataType & 2) {
  2372. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2373. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2374. return true;
  2375. } else if (dataType === 2) {
  2376. return false;
  2377. }
  2378. }
  2379. if (dataType & 4) {
  2380. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2381. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2382. return true;
  2383. } else {
  2384. return false;
  2385. }
  2386. }
  2387. } catch (e) {
  2388. }
  2389. return false;
  2390. };
  2391. Object.defineProperty(Tools, "NoneLogLevel", {
  2392. get: function () {
  2393. return Tools._NoneLogLevel;
  2394. },
  2395. enumerable: true,
  2396. configurable: true
  2397. });
  2398. Object.defineProperty(Tools, "MessageLogLevel", {
  2399. get: function () {
  2400. return Tools._MessageLogLevel;
  2401. },
  2402. enumerable: true,
  2403. configurable: true
  2404. });
  2405. Object.defineProperty(Tools, "WarningLogLevel", {
  2406. get: function () {
  2407. return Tools._WarningLogLevel;
  2408. },
  2409. enumerable: true,
  2410. configurable: true
  2411. });
  2412. Object.defineProperty(Tools, "ErrorLogLevel", {
  2413. get: function () {
  2414. return Tools._ErrorLogLevel;
  2415. },
  2416. enumerable: true,
  2417. configurable: true
  2418. });
  2419. Object.defineProperty(Tools, "AllLogLevel", {
  2420. get: function () {
  2421. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2422. },
  2423. enumerable: true,
  2424. configurable: true
  2425. });
  2426. Tools._FormatMessage = function (message) {
  2427. var padStr = function (i) {
  2428. return (i < 10) ? "0" + i : "" + i;
  2429. };
  2430. var date = new Date();
  2431. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2432. };
  2433. Tools._LogDisabled = function (message) {
  2434. };
  2435. Tools._LogEnabled = function (message) {
  2436. console.log(Tools._FormatMessage(message));
  2437. };
  2438. Tools._WarnDisabled = function (message) {
  2439. };
  2440. Tools._WarnEnabled = function (message) {
  2441. console.warn(Tools._FormatMessage(message));
  2442. };
  2443. Tools._ErrorDisabled = function (message) {
  2444. };
  2445. Tools._ErrorEnabled = function (message) {
  2446. console.error(Tools._FormatMessage(message));
  2447. };
  2448. Object.defineProperty(Tools, "LogLevels", {
  2449. set: function (level) {
  2450. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2451. Tools.Log = Tools._LogEnabled;
  2452. } else {
  2453. Tools.Log = Tools._LogDisabled;
  2454. }
  2455. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2456. Tools.Warn = Tools._WarnEnabled;
  2457. } else {
  2458. Tools.Warn = Tools._WarnDisabled;
  2459. }
  2460. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2461. Tools.Error = Tools._ErrorEnabled;
  2462. } else {
  2463. Tools.Error = Tools._ErrorDisabled;
  2464. }
  2465. },
  2466. enumerable: true,
  2467. configurable: true
  2468. });
  2469. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2470. get: function () {
  2471. return Tools._PerformanceNoneLogLevel;
  2472. },
  2473. enumerable: true,
  2474. configurable: true
  2475. });
  2476. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2477. get: function () {
  2478. return Tools._PerformanceUserMarkLogLevel;
  2479. },
  2480. enumerable: true,
  2481. configurable: true
  2482. });
  2483. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2484. get: function () {
  2485. return Tools._PerformanceConsoleLogLevel;
  2486. },
  2487. enumerable: true,
  2488. configurable: true
  2489. });
  2490. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2491. set: function (level) {
  2492. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2493. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2494. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2495. return;
  2496. }
  2497. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2498. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2499. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2500. return;
  2501. }
  2502. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2503. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2504. },
  2505. enumerable: true,
  2506. configurable: true
  2507. });
  2508. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2509. };
  2510. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2511. };
  2512. Tools._StartUserMark = function (counterName, condition) {
  2513. if (typeof condition === "undefined") { condition = true; }
  2514. if (!condition || !Tools._performance.mark) {
  2515. return;
  2516. }
  2517. Tools._performance.mark(counterName + "-Begin");
  2518. };
  2519. Tools._EndUserMark = function (counterName, condition) {
  2520. if (typeof condition === "undefined") { condition = true; }
  2521. if (!condition || !Tools._performance.mark) {
  2522. return;
  2523. }
  2524. Tools._performance.mark(counterName + "-End");
  2525. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2526. };
  2527. Tools._StartPerformanceConsole = function (counterName, condition) {
  2528. if (typeof condition === "undefined") { condition = true; }
  2529. if (!condition) {
  2530. return;
  2531. }
  2532. Tools._StartUserMark(counterName, condition);
  2533. if (console.time) {
  2534. console.time(counterName);
  2535. }
  2536. };
  2537. Tools._EndPerformanceConsole = function (counterName, condition) {
  2538. if (typeof condition === "undefined") { condition = true; }
  2539. if (!condition) {
  2540. return;
  2541. }
  2542. Tools._EndUserMark(counterName, condition);
  2543. if (console.time) {
  2544. console.timeEnd(counterName);
  2545. }
  2546. };
  2547. Object.defineProperty(Tools, "Now", {
  2548. get: function () {
  2549. if (window.performance.now) {
  2550. return window.performance.now();
  2551. }
  2552. return new Date().getTime();
  2553. },
  2554. enumerable: true,
  2555. configurable: true
  2556. });
  2557. Tools.BaseUrl = "";
  2558. Tools.GetExponantOfTwo = function (value, max) {
  2559. var count = 1;
  2560. do {
  2561. count *= 2;
  2562. } while(count < value);
  2563. if (count > max)
  2564. count = max;
  2565. return count;
  2566. };
  2567. Tools._NoneLogLevel = 0;
  2568. Tools._MessageLogLevel = 1;
  2569. Tools._WarningLogLevel = 2;
  2570. Tools._ErrorLogLevel = 4;
  2571. Tools.Log = Tools._LogEnabled;
  2572. Tools.Warn = Tools._WarnEnabled;
  2573. Tools.Error = Tools._ErrorEnabled;
  2574. Tools._PerformanceNoneLogLevel = 0;
  2575. Tools._PerformanceUserMarkLogLevel = 1;
  2576. Tools._PerformanceConsoleLogLevel = 2;
  2577. Tools._performance = window.performance;
  2578. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2579. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2580. return Tools;
  2581. })();
  2582. BABYLON.Tools = Tools;
  2583. })(BABYLON || (BABYLON = {}));
  2584. var BABYLON;
  2585. (function (BABYLON) {
  2586. var _DepthCullingState = (function () {
  2587. function _DepthCullingState() {
  2588. this._isDepthTestDirty = false;
  2589. this._isDepthMaskDirty = false;
  2590. this._isDepthFuncDirty = false;
  2591. this._isCullFaceDirty = false;
  2592. this._isCullDirty = false;
  2593. }
  2594. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2595. get: function () {
  2596. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2597. },
  2598. enumerable: true,
  2599. configurable: true
  2600. });
  2601. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2602. get: function () {
  2603. return this._cullFace;
  2604. },
  2605. set: function (value) {
  2606. if (this._cullFace === value) {
  2607. return;
  2608. }
  2609. this._cullFace = value;
  2610. this._isCullFaceDirty = true;
  2611. },
  2612. enumerable: true,
  2613. configurable: true
  2614. });
  2615. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2616. get: function () {
  2617. return this._cull;
  2618. },
  2619. set: function (value) {
  2620. if (this._cull === value) {
  2621. return;
  2622. }
  2623. this._cull = value;
  2624. this._isCullDirty = true;
  2625. },
  2626. enumerable: true,
  2627. configurable: true
  2628. });
  2629. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2630. get: function () {
  2631. return this._depthFunc;
  2632. },
  2633. set: function (value) {
  2634. if (this._depthFunc === value) {
  2635. return;
  2636. }
  2637. this._depthFunc = value;
  2638. this._isDepthFuncDirty = true;
  2639. },
  2640. enumerable: true,
  2641. configurable: true
  2642. });
  2643. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2644. get: function () {
  2645. return this._depthMask;
  2646. },
  2647. set: function (value) {
  2648. if (this._depthMask === value) {
  2649. return;
  2650. }
  2651. this._depthMask = value;
  2652. this._isDepthMaskDirty = true;
  2653. },
  2654. enumerable: true,
  2655. configurable: true
  2656. });
  2657. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  2658. get: function () {
  2659. return this._depthTest;
  2660. },
  2661. set: function (value) {
  2662. if (this._depthTest === value) {
  2663. return;
  2664. }
  2665. this._depthTest = value;
  2666. this._isDepthTestDirty = true;
  2667. },
  2668. enumerable: true,
  2669. configurable: true
  2670. });
  2671. _DepthCullingState.prototype.reset = function () {
  2672. this._depthMask = true;
  2673. this._depthTest = true;
  2674. this._depthFunc = null;
  2675. this._cull = null;
  2676. this._cullFace = null;
  2677. this._isDepthTestDirty = true;
  2678. this._isDepthMaskDirty = true;
  2679. this._isDepthFuncDirty = false;
  2680. this._isCullFaceDirty = false;
  2681. this._isCullDirty = false;
  2682. };
  2683. _DepthCullingState.prototype.apply = function (gl) {
  2684. if (!this.isDirty) {
  2685. return;
  2686. }
  2687. if (this._isCullDirty) {
  2688. if (this.cull === true) {
  2689. gl.enable(gl.CULL_FACE);
  2690. } else if (this.cull === false) {
  2691. gl.disable(gl.CULL_FACE);
  2692. }
  2693. this._isCullDirty = false;
  2694. }
  2695. if (this._isCullFaceDirty) {
  2696. gl.cullFace(this.cullFace);
  2697. this._isCullFaceDirty = false;
  2698. }
  2699. if (this._isDepthMaskDirty) {
  2700. gl.depthMask(this.depthMask);
  2701. this._isDepthMaskDirty = false;
  2702. }
  2703. if (this._isDepthTestDirty) {
  2704. if (this.depthTest === true) {
  2705. gl.enable(gl.DEPTH_TEST);
  2706. } else if (this.depthTest === false) {
  2707. gl.disable(gl.DEPTH_TEST);
  2708. }
  2709. this._isDepthTestDirty = false;
  2710. }
  2711. if (this._isDepthFuncDirty) {
  2712. gl.depthFunc(this.depthFunc);
  2713. this._isDepthFuncDirty = false;
  2714. }
  2715. };
  2716. return _DepthCullingState;
  2717. })();
  2718. BABYLON._DepthCullingState = _DepthCullingState;
  2719. var _AlphaState = (function () {
  2720. function _AlphaState() {
  2721. this._isAlphaBlendDirty = false;
  2722. this._isBlendFunctionParametersDirty = false;
  2723. this._alphaBlend = false;
  2724. this._blendFunctionParameters = new Array(4);
  2725. }
  2726. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  2727. get: function () {
  2728. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  2729. },
  2730. enumerable: true,
  2731. configurable: true
  2732. });
  2733. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  2734. get: function () {
  2735. return this._alphaBlend;
  2736. },
  2737. set: function (value) {
  2738. if (this._alphaBlend === value) {
  2739. return;
  2740. }
  2741. this._alphaBlend = value;
  2742. this._isAlphaBlendDirty = true;
  2743. },
  2744. enumerable: true,
  2745. configurable: true
  2746. });
  2747. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  2748. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  2749. return;
  2750. }
  2751. this._blendFunctionParameters[0] = value0;
  2752. this._blendFunctionParameters[1] = value1;
  2753. this._blendFunctionParameters[2] = value2;
  2754. this._blendFunctionParameters[3] = value3;
  2755. this._isBlendFunctionParametersDirty = true;
  2756. };
  2757. _AlphaState.prototype.reset = function () {
  2758. this._alphaBlend = false;
  2759. this._blendFunctionParameters[0] = null;
  2760. this._blendFunctionParameters[1] = null;
  2761. this._blendFunctionParameters[2] = null;
  2762. this._blendFunctionParameters[3] = null;
  2763. this._isAlphaBlendDirty = true;
  2764. this._isBlendFunctionParametersDirty = false;
  2765. };
  2766. _AlphaState.prototype.apply = function (gl) {
  2767. if (!this.isDirty) {
  2768. return;
  2769. }
  2770. if (this._isAlphaBlendDirty) {
  2771. if (this._alphaBlend === true) {
  2772. gl.enable(gl.BLEND);
  2773. } else if (this._alphaBlend === false) {
  2774. gl.disable(gl.BLEND);
  2775. }
  2776. this._isAlphaBlendDirty = false;
  2777. }
  2778. if (this._isBlendFunctionParametersDirty) {
  2779. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  2780. this._isBlendFunctionParametersDirty = false;
  2781. }
  2782. };
  2783. return _AlphaState;
  2784. })();
  2785. BABYLON._AlphaState = _AlphaState;
  2786. var compileShader = function (gl, source, type, defines) {
  2787. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2788. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  2789. gl.compileShader(shader);
  2790. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2791. throw new Error(gl.getShaderInfoLog(shader));
  2792. }
  2793. return shader;
  2794. };
  2795. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  2796. var magFilter = gl.NEAREST;
  2797. var minFilter = gl.NEAREST;
  2798. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  2799. magFilter = gl.LINEAR;
  2800. if (generateMipMaps) {
  2801. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2802. } else {
  2803. minFilter = gl.LINEAR;
  2804. }
  2805. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  2806. magFilter = gl.LINEAR;
  2807. if (generateMipMaps) {
  2808. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2809. } else {
  2810. minFilter = gl.LINEAR;
  2811. }
  2812. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  2813. magFilter = gl.NEAREST;
  2814. if (generateMipMaps) {
  2815. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2816. } else {
  2817. minFilter = gl.NEAREST;
  2818. }
  2819. }
  2820. return {
  2821. min: minFilter,
  2822. mag: magFilter
  2823. };
  2824. };
  2825. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  2826. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  2827. var engine = scene.getEngine();
  2828. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  2829. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  2830. gl.bindTexture(gl.TEXTURE_2D, texture);
  2831. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2832. processFunction(potWidth, potHeight);
  2833. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  2834. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2835. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2836. if (!noMipmap && !isCompressed) {
  2837. gl.generateMipmap(gl.TEXTURE_2D);
  2838. }
  2839. gl.bindTexture(gl.TEXTURE_2D, null);
  2840. engine._activeTexturesCache = [];
  2841. texture._baseWidth = width;
  2842. texture._baseHeight = height;
  2843. texture._width = potWidth;
  2844. texture._height = potHeight;
  2845. texture.isReady = true;
  2846. scene._removePendingData(texture);
  2847. };
  2848. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  2849. var img;
  2850. var onload = function () {
  2851. loadedImages[index] = img;
  2852. loadedImages._internalCount++;
  2853. scene._removePendingData(img);
  2854. if (loadedImages._internalCount == 6) {
  2855. onfinish(loadedImages);
  2856. }
  2857. };
  2858. var onerror = function () {
  2859. scene._removePendingData(img);
  2860. };
  2861. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  2862. scene._addPendingData(img);
  2863. };
  2864. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  2865. var loadedImages = [];
  2866. loadedImages._internalCount = 0;
  2867. for (var index = 0; index < 6; index++) {
  2868. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  2869. }
  2870. };
  2871. var EngineCapabilities = (function () {
  2872. function EngineCapabilities() {
  2873. }
  2874. return EngineCapabilities;
  2875. })();
  2876. BABYLON.EngineCapabilities = EngineCapabilities;
  2877. var Engine = (function () {
  2878. function Engine(canvas, antialias, options) {
  2879. var _this = this;
  2880. this.isFullscreen = false;
  2881. this.isPointerLock = false;
  2882. this.forceWireframe = false;
  2883. this.cullBackFaces = true;
  2884. this.renderEvenInBackground = true;
  2885. this.scenes = new Array();
  2886. this._windowIsBackground = false;
  2887. this._runningLoop = false;
  2888. this._loadingDivBackgroundColor = "black";
  2889. this._depthCullingState = new _DepthCullingState();
  2890. this._alphaState = new _AlphaState();
  2891. this._loadedTexturesCache = new Array();
  2892. this._activeTexturesCache = new Array();
  2893. this._compiledEffects = {};
  2894. this._renderingCanvas = canvas;
  2895. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2896. options = options || {};
  2897. options.antialias = antialias;
  2898. try {
  2899. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  2900. } catch (e) {
  2901. throw new Error("WebGL not supported");
  2902. }
  2903. if (!this._gl) {
  2904. throw new Error("WebGL not supported");
  2905. }
  2906. this._onBlur = function () {
  2907. _this._windowIsBackground = true;
  2908. };
  2909. this._onFocus = function () {
  2910. _this._windowIsBackground = false;
  2911. };
  2912. window.addEventListener("blur", this._onBlur);
  2913. window.addEventListener("focus", this._onFocus);
  2914. this._workingCanvas = document.createElement("canvas");
  2915. this._workingContext = this._workingCanvas.getContext("2d");
  2916. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  2917. this.resize();
  2918. this._caps = new EngineCapabilities();
  2919. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  2920. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  2921. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  2922. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  2923. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  2924. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  2925. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  2926. 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');
  2927. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  2928. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  2929. this.setDepthBuffer(true);
  2930. this.setDepthFunctionToLessOrEqual();
  2931. this.setDepthWrite(true);
  2932. this._onFullscreenChange = function () {
  2933. if (document.fullscreen !== undefined) {
  2934. _this.isFullscreen = document.fullscreen;
  2935. } else if (document.mozFullScreen !== undefined) {
  2936. _this.isFullscreen = document.mozFullScreen;
  2937. } else if (document.webkitIsFullScreen !== undefined) {
  2938. _this.isFullscreen = document.webkitIsFullScreen;
  2939. } else if (document.msIsFullScreen !== undefined) {
  2940. _this.isFullscreen = document.msIsFullScreen;
  2941. }
  2942. if (_this.isFullscreen && _this._pointerLockRequested) {
  2943. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  2944. if (canvas.requestPointerLock) {
  2945. canvas.requestPointerLock();
  2946. }
  2947. }
  2948. };
  2949. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  2950. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  2951. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  2952. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  2953. this._onPointerLockChange = function () {
  2954. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  2955. };
  2956. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  2957. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  2958. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  2959. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  2960. }
  2961. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  2962. get: function () {
  2963. return Engine._ALPHA_DISABLE;
  2964. },
  2965. enumerable: true,
  2966. configurable: true
  2967. });
  2968. Object.defineProperty(Engine, "ALPHA_ADD", {
  2969. get: function () {
  2970. return Engine._ALPHA_ADD;
  2971. },
  2972. enumerable: true,
  2973. configurable: true
  2974. });
  2975. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  2976. get: function () {
  2977. return Engine._ALPHA_COMBINE;
  2978. },
  2979. enumerable: true,
  2980. configurable: true
  2981. });
  2982. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  2983. get: function () {
  2984. return Engine._DELAYLOADSTATE_NONE;
  2985. },
  2986. enumerable: true,
  2987. configurable: true
  2988. });
  2989. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  2990. get: function () {
  2991. return Engine._DELAYLOADSTATE_LOADED;
  2992. },
  2993. enumerable: true,
  2994. configurable: true
  2995. });
  2996. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  2997. get: function () {
  2998. return Engine._DELAYLOADSTATE_LOADING;
  2999. },
  3000. enumerable: true,
  3001. configurable: true
  3002. });
  3003. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3004. get: function () {
  3005. return Engine._DELAYLOADSTATE_NOTLOADED;
  3006. },
  3007. enumerable: true,
  3008. configurable: true
  3009. });
  3010. Object.defineProperty(Engine, "Version", {
  3011. get: function () {
  3012. return "2.0.0";
  3013. },
  3014. enumerable: true,
  3015. configurable: true
  3016. });
  3017. Engine.prototype.getAspectRatio = function (camera) {
  3018. var viewport = camera.viewport;
  3019. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3020. };
  3021. Engine.prototype.getRenderWidth = function () {
  3022. if (this._currentRenderTarget) {
  3023. return this._currentRenderTarget._width;
  3024. }
  3025. return this._renderingCanvas.width;
  3026. };
  3027. Engine.prototype.getRenderHeight = function () {
  3028. if (this._currentRenderTarget) {
  3029. return this._currentRenderTarget._height;
  3030. }
  3031. return this._renderingCanvas.height;
  3032. };
  3033. Engine.prototype.getRenderingCanvas = function () {
  3034. return this._renderingCanvas;
  3035. };
  3036. Engine.prototype.getRenderingCanvasClientRect = function () {
  3037. return this._renderingCanvas.getBoundingClientRect();
  3038. };
  3039. Engine.prototype.setHardwareScalingLevel = function (level) {
  3040. this._hardwareScalingLevel = level;
  3041. this.resize();
  3042. };
  3043. Engine.prototype.getHardwareScalingLevel = function () {
  3044. return this._hardwareScalingLevel;
  3045. };
  3046. Engine.prototype.getLoadedTexturesCache = function () {
  3047. return this._loadedTexturesCache;
  3048. };
  3049. Engine.prototype.getCaps = function () {
  3050. return this._caps;
  3051. };
  3052. Engine.prototype.setDepthFunctionToGreater = function () {
  3053. this._depthCullingState.depthFunc = this._gl.GREATER;
  3054. };
  3055. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3056. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3057. };
  3058. Engine.prototype.setDepthFunctionToLess = function () {
  3059. this._depthCullingState.depthFunc = this._gl.LESS;
  3060. };
  3061. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3062. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3063. };
  3064. Engine.prototype.stopRenderLoop = function () {
  3065. this._renderFunction = null;
  3066. this._runningLoop = false;
  3067. };
  3068. Engine.prototype._renderLoop = function () {
  3069. var _this = this;
  3070. var shouldRender = true;
  3071. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3072. shouldRender = false;
  3073. }
  3074. if (shouldRender) {
  3075. this.beginFrame();
  3076. if (this._renderFunction) {
  3077. this._renderFunction();
  3078. }
  3079. this.endFrame();
  3080. }
  3081. if (this._runningLoop) {
  3082. BABYLON.Tools.QueueNewFrame(function () {
  3083. _this._renderLoop();
  3084. });
  3085. }
  3086. };
  3087. Engine.prototype.runRenderLoop = function (renderFunction) {
  3088. var _this = this;
  3089. this._runningLoop = true;
  3090. this._renderFunction = renderFunction;
  3091. BABYLON.Tools.QueueNewFrame(function () {
  3092. _this._renderLoop();
  3093. });
  3094. };
  3095. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3096. if (this.isFullscreen) {
  3097. BABYLON.Tools.ExitFullscreen();
  3098. } else {
  3099. this._pointerLockRequested = requestPointerLock;
  3100. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3101. }
  3102. };
  3103. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3104. this.applyStates();
  3105. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3106. if (this._depthCullingState.depthMask) {
  3107. this._gl.clearDepth(1.0);
  3108. }
  3109. var mode = 0;
  3110. if (backBuffer)
  3111. mode |= this._gl.COLOR_BUFFER_BIT;
  3112. if (depthStencil && this._depthCullingState.depthMask)
  3113. mode |= this._gl.DEPTH_BUFFER_BIT;
  3114. this._gl.clear(mode);
  3115. };
  3116. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3117. var width = requiredWidth || this._renderingCanvas.width;
  3118. var height = requiredHeight || this._renderingCanvas.height;
  3119. var x = viewport.x || 0;
  3120. var y = viewport.y || 0;
  3121. this._cachedViewport = viewport;
  3122. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3123. };
  3124. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3125. this._cachedViewport = null;
  3126. this._gl.viewport(x, y, width, height);
  3127. };
  3128. Engine.prototype.beginFrame = function () {
  3129. BABYLON.Tools._MeasureFps();
  3130. };
  3131. Engine.prototype.endFrame = function () {
  3132. this.flushFramebuffer();
  3133. };
  3134. Engine.prototype.resize = function () {
  3135. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3136. };
  3137. Engine.prototype.setSize = function (width, height) {
  3138. this._renderingCanvas.width = width;
  3139. this._renderingCanvas.height = height;
  3140. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3141. };
  3142. Engine.prototype.bindFramebuffer = function (texture) {
  3143. this._currentRenderTarget = texture;
  3144. var gl = this._gl;
  3145. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3146. this._gl.viewport(0, 0, texture._width, texture._height);
  3147. this.wipeCaches();
  3148. };
  3149. Engine.prototype.unBindFramebuffer = function (texture) {
  3150. this._currentRenderTarget = null;
  3151. if (texture.generateMipMaps) {
  3152. var gl = this._gl;
  3153. gl.bindTexture(gl.TEXTURE_2D, texture);
  3154. gl.generateMipmap(gl.TEXTURE_2D);
  3155. gl.bindTexture(gl.TEXTURE_2D, null);
  3156. }
  3157. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3158. };
  3159. Engine.prototype.flushFramebuffer = function () {
  3160. this._gl.flush();
  3161. };
  3162. Engine.prototype.restoreDefaultFramebuffer = function () {
  3163. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3164. this.setViewport(this._cachedViewport);
  3165. this.wipeCaches();
  3166. };
  3167. Engine.prototype._resetVertexBufferBinding = function () {
  3168. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3169. this._cachedVertexBuffers = null;
  3170. };
  3171. Engine.prototype.createVertexBuffer = function (vertices) {
  3172. var vbo = this._gl.createBuffer();
  3173. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3174. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3175. this._resetVertexBufferBinding();
  3176. vbo.references = 1;
  3177. return vbo;
  3178. };
  3179. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3180. var vbo = this._gl.createBuffer();
  3181. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3182. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3183. this._resetVertexBufferBinding();
  3184. vbo.references = 1;
  3185. return vbo;
  3186. };
  3187. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, length) {
  3188. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3189. if (vertices instanceof Float32Array) {
  3190. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  3191. } else {
  3192. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  3193. }
  3194. this._resetVertexBufferBinding();
  3195. };
  3196. Engine.prototype._resetIndexBufferBinding = function () {
  3197. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3198. this._cachedIndexBuffer = null;
  3199. };
  3200. Engine.prototype.createIndexBuffer = function (indices) {
  3201. var vbo = this._gl.createBuffer();
  3202. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3203. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  3204. this._resetIndexBufferBinding();
  3205. vbo.references = 1;
  3206. return vbo;
  3207. };
  3208. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3209. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3210. this._cachedVertexBuffers = vertexBuffer;
  3211. this._cachedEffectForVertexBuffers = effect;
  3212. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3213. var offset = 0;
  3214. for (var index = 0; index < vertexDeclaration.length; index++) {
  3215. var order = effect.getAttributeLocation(index);
  3216. if (order >= 0) {
  3217. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3218. }
  3219. offset += vertexDeclaration[index] * 4;
  3220. }
  3221. }
  3222. if (this._cachedIndexBuffer !== indexBuffer) {
  3223. this._cachedIndexBuffer = indexBuffer;
  3224. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3225. }
  3226. };
  3227. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3228. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3229. this._cachedVertexBuffers = vertexBuffers;
  3230. this._cachedEffectForVertexBuffers = effect;
  3231. var attributes = effect.getAttributesNames();
  3232. for (var index = 0; index < attributes.length; index++) {
  3233. var order = effect.getAttributeLocation(index);
  3234. if (order >= 0) {
  3235. var vertexBuffer = vertexBuffers[attributes[index]];
  3236. if (!vertexBuffer) {
  3237. continue;
  3238. }
  3239. var stride = vertexBuffer.getStrideSize();
  3240. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3241. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3242. }
  3243. }
  3244. }
  3245. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3246. this._cachedIndexBuffer = indexBuffer;
  3247. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3248. }
  3249. };
  3250. Engine.prototype._releaseBuffer = function (buffer) {
  3251. buffer.references--;
  3252. if (buffer.references === 0) {
  3253. this._gl.deleteBuffer(buffer);
  3254. return true;
  3255. }
  3256. return false;
  3257. };
  3258. Engine.prototype.createInstancesBuffer = function (capacity) {
  3259. var buffer = this._gl.createBuffer();
  3260. buffer.capacity = capacity;
  3261. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3262. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3263. return buffer;
  3264. };
  3265. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3266. this._gl.deleteBuffer(buffer);
  3267. };
  3268. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3269. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3270. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3271. for (var index = 0; index < 4; index++) {
  3272. var offsetLocation = offsetLocations[index];
  3273. this._gl.enableVertexAttribArray(offsetLocation);
  3274. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3275. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3276. }
  3277. };
  3278. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3279. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3280. for (var index = 0; index < 4; index++) {
  3281. var offsetLocation = offsetLocations[index];
  3282. this._gl.disableVertexAttribArray(offsetLocation);
  3283. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3284. }
  3285. };
  3286. Engine.prototype.applyStates = function () {
  3287. this._depthCullingState.apply(this._gl);
  3288. this._alphaState.apply(this._gl);
  3289. };
  3290. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  3291. this.applyStates();
  3292. if (instancesCount) {
  3293. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2, instancesCount);
  3294. return;
  3295. }
  3296. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  3297. };
  3298. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  3299. this.applyStates();
  3300. if (instancesCount) {
  3301. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  3302. return;
  3303. }
  3304. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  3305. };
  3306. Engine.prototype._releaseEffect = function (effect) {
  3307. if (this._compiledEffects[effect._key]) {
  3308. delete this._compiledEffects[effect._key];
  3309. if (effect.getProgram()) {
  3310. this._gl.deleteProgram(effect.getProgram());
  3311. }
  3312. }
  3313. };
  3314. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3315. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3316. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  3317. var name = vertex + "+" + fragment + "@" + defines;
  3318. if (this._compiledEffects[name]) {
  3319. return this._compiledEffects[name];
  3320. }
  3321. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  3322. effect._key = name;
  3323. this._compiledEffects[name] = effect;
  3324. return effect;
  3325. };
  3326. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3327. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  3328. if (typeof samplers === "undefined") { samplers = []; }
  3329. if (typeof defines === "undefined") { defines = ""; }
  3330. return this.createEffect({
  3331. vertex: "particles",
  3332. fragmentElement: fragmentName
  3333. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  3334. };
  3335. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  3336. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  3337. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  3338. var shaderProgram = this._gl.createProgram();
  3339. this._gl.attachShader(shaderProgram, vertexShader);
  3340. this._gl.attachShader(shaderProgram, fragmentShader);
  3341. this._gl.linkProgram(shaderProgram);
  3342. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  3343. if (!linked) {
  3344. var error = this._gl.getProgramInfoLog(shaderProgram);
  3345. if (error) {
  3346. throw new Error(error);
  3347. }
  3348. }
  3349. this._gl.deleteShader(vertexShader);
  3350. this._gl.deleteShader(fragmentShader);
  3351. return shaderProgram;
  3352. };
  3353. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3354. var results = [];
  3355. for (var index = 0; index < uniformsNames.length; index++) {
  3356. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3357. }
  3358. return results;
  3359. };
  3360. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3361. var results = [];
  3362. for (var index = 0; index < attributesNames.length; index++) {
  3363. try {
  3364. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3365. } catch (e) {
  3366. results.push(-1);
  3367. }
  3368. }
  3369. return results;
  3370. };
  3371. Engine.prototype.enableEffect = function (effect) {
  3372. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3373. return;
  3374. }
  3375. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3376. this._gl.useProgram(effect.getProgram());
  3377. for (var i in this._vertexAttribArrays) {
  3378. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3379. continue;
  3380. }
  3381. this._vertexAttribArrays[i] = false;
  3382. this._gl.disableVertexAttribArray(i);
  3383. }
  3384. var attributesCount = effect.getAttributesCount();
  3385. for (var index = 0; index < attributesCount; index++) {
  3386. var order = effect.getAttributeLocation(index);
  3387. if (order >= 0) {
  3388. this._vertexAttribArrays[order] = true;
  3389. this._gl.enableVertexAttribArray(order);
  3390. }
  3391. }
  3392. this._currentEffect = effect;
  3393. };
  3394. Engine.prototype.setArray = function (uniform, array) {
  3395. if (!uniform)
  3396. return;
  3397. this._gl.uniform1fv(uniform, array);
  3398. };
  3399. Engine.prototype.setMatrices = function (uniform, matrices) {
  3400. if (!uniform)
  3401. return;
  3402. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3403. };
  3404. Engine.prototype.setMatrix = function (uniform, matrix) {
  3405. if (!uniform)
  3406. return;
  3407. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3408. };
  3409. Engine.prototype.setFloat = function (uniform, value) {
  3410. if (!uniform)
  3411. return;
  3412. this._gl.uniform1f(uniform, value);
  3413. };
  3414. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3415. if (!uniform)
  3416. return;
  3417. this._gl.uniform2f(uniform, x, y);
  3418. };
  3419. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3420. if (!uniform)
  3421. return;
  3422. this._gl.uniform3f(uniform, x, y, z);
  3423. };
  3424. Engine.prototype.setBool = function (uniform, bool) {
  3425. if (!uniform)
  3426. return;
  3427. this._gl.uniform1i(uniform, bool);
  3428. };
  3429. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3430. if (!uniform)
  3431. return;
  3432. this._gl.uniform4f(uniform, x, y, z, w);
  3433. };
  3434. Engine.prototype.setColor3 = function (uniform, color3) {
  3435. if (!uniform)
  3436. return;
  3437. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3438. };
  3439. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3440. if (!uniform)
  3441. return;
  3442. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3443. };
  3444. Engine.prototype.setState = function (culling, force) {
  3445. if (this._depthCullingState.cull !== culling || force) {
  3446. if (culling) {
  3447. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3448. this._depthCullingState.cull = true;
  3449. } else {
  3450. this._depthCullingState.cull = false;
  3451. }
  3452. }
  3453. };
  3454. Engine.prototype.setDepthBuffer = function (enable) {
  3455. this._depthCullingState.depthTest = enable;
  3456. };
  3457. Engine.prototype.getDepthWrite = function () {
  3458. return this._depthCullingState.depthMask;
  3459. };
  3460. Engine.prototype.setDepthWrite = function (enable) {
  3461. this._depthCullingState.depthMask = enable;
  3462. };
  3463. Engine.prototype.setColorWrite = function (enable) {
  3464. this._gl.colorMask(enable, enable, enable, enable);
  3465. };
  3466. Engine.prototype.setAlphaMode = function (mode) {
  3467. switch (mode) {
  3468. case BABYLON.Engine.ALPHA_DISABLE:
  3469. this.setDepthWrite(true);
  3470. this._alphaState.alphaBlend = false;
  3471. break;
  3472. case BABYLON.Engine.ALPHA_COMBINE:
  3473. this.setDepthWrite(false);
  3474. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3475. this._alphaState.alphaBlend = true;
  3476. break;
  3477. case BABYLON.Engine.ALPHA_ADD:
  3478. this.setDepthWrite(false);
  3479. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3480. this._alphaState.alphaBlend = true;
  3481. break;
  3482. }
  3483. };
  3484. Engine.prototype.setAlphaTesting = function (enable) {
  3485. this._alphaTest = enable;
  3486. };
  3487. Engine.prototype.getAlphaTesting = function () {
  3488. return this._alphaTest;
  3489. };
  3490. Engine.prototype.wipeCaches = function () {
  3491. this._activeTexturesCache = [];
  3492. this._currentEffect = null;
  3493. this._depthCullingState.reset();
  3494. this._alphaState.reset();
  3495. this._cachedVertexBuffers = null;
  3496. this._cachedIndexBuffer = null;
  3497. this._cachedEffectForVertexBuffers = null;
  3498. };
  3499. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3500. var gl = this._gl;
  3501. gl.bindTexture(gl.TEXTURE_2D, texture);
  3502. var magFilter = gl.NEAREST;
  3503. var minFilter = gl.NEAREST;
  3504. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3505. magFilter = gl.LINEAR;
  3506. minFilter = gl.LINEAR;
  3507. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3508. magFilter = gl.LINEAR;
  3509. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3510. }
  3511. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3512. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3513. gl.bindTexture(gl.TEXTURE_2D, null);
  3514. };
  3515. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  3516. var _this = this;
  3517. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3518. if (typeof onLoad === "undefined") { onLoad = null; }
  3519. if (typeof onError === "undefined") { onError = null; }
  3520. if (typeof buffer === "undefined") { buffer = null; }
  3521. var texture = this._gl.createTexture();
  3522. var extension;
  3523. var fromData = false;
  3524. if (url.substr(0, 5) === "data:") {
  3525. fromData = true;
  3526. }
  3527. if (!fromData)
  3528. extension = url.substr(url.length - 4, 4).toLowerCase();
  3529. else {
  3530. var oldUrl = url;
  3531. fromData = oldUrl.split(':');
  3532. url = oldUrl;
  3533. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  3534. }
  3535. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3536. var isTGA = (extension === ".tga");
  3537. scene._addPendingData(texture);
  3538. texture.url = url;
  3539. texture.noMipmap = noMipmap;
  3540. texture.references = 1;
  3541. this._loadedTexturesCache.push(texture);
  3542. var onerror = function () {
  3543. scene._removePendingData(texture);
  3544. if (onError) {
  3545. onError();
  3546. }
  3547. };
  3548. if (isTGA) {
  3549. var callback = function (arrayBuffer) {
  3550. var data = new Uint8Array(arrayBuffer);
  3551. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3552. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3553. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3554. if (onLoad) {
  3555. onLoad();
  3556. }
  3557. }, samplingMode);
  3558. };
  3559. if (!(fromData instanceof Array))
  3560. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3561. callback(arrayBuffer);
  3562. }, onerror, scene.database, true);
  3563. else
  3564. callback(buffer);
  3565. } else if (isDDS) {
  3566. callback = function (data) {
  3567. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3568. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3569. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3570. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3571. if (onLoad) {
  3572. onLoad();
  3573. }
  3574. }, samplingMode);
  3575. };
  3576. if (!(fromData instanceof Array))
  3577. BABYLON.Tools.LoadFile(url, function (data) {
  3578. callback(data);
  3579. }, onerror, scene.database, true);
  3580. else
  3581. callback(buffer);
  3582. } else {
  3583. var onload = function (img) {
  3584. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3585. var isPot = (img.width == potWidth && img.height == potHeight);
  3586. if (!isPot) {
  3587. _this._workingCanvas.width = potWidth;
  3588. _this._workingCanvas.height = potHeight;
  3589. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3590. }
  3591. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3592. if (onLoad) {
  3593. onLoad();
  3594. }
  3595. }, samplingMode);
  3596. };
  3597. if (!(fromData instanceof Array))
  3598. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3599. else
  3600. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  3601. }
  3602. return texture;
  3603. };
  3604. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  3605. var texture = this._gl.createTexture();
  3606. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  3607. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  3608. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3609. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3610. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3611. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3612. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3613. this._activeTexturesCache = [];
  3614. texture._baseWidth = width;
  3615. texture._baseHeight = height;
  3616. texture._width = width;
  3617. texture._height = height;
  3618. texture.isReady = false;
  3619. texture.generateMipMaps = generateMipMaps;
  3620. texture.references = 1;
  3621. this._loadedTexturesCache.push(texture);
  3622. return texture;
  3623. };
  3624. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  3625. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3626. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3627. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  3628. if (texture.generateMipMaps) {
  3629. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3630. }
  3631. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3632. this._activeTexturesCache = [];
  3633. texture.isReady = true;
  3634. };
  3635. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  3636. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3637. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1);
  3638. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  3639. if (!texture._workingCanvas) {
  3640. texture._workingCanvas = document.createElement("canvas");
  3641. texture._workingContext = texture._workingCanvas.getContext("2d");
  3642. texture._workingCanvas.width = texture._width;
  3643. texture._workingCanvas.height = texture._height;
  3644. }
  3645. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  3646. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3647. } else {
  3648. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3649. }
  3650. if (texture.generateMipMaps) {
  3651. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3652. }
  3653. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3654. this._activeTexturesCache = [];
  3655. texture.isReady = true;
  3656. };
  3657. Engine.prototype.createRenderTargetTexture = function (size, options) {
  3658. var generateMipMaps = false;
  3659. var generateDepthBuffer = true;
  3660. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3661. if (options !== undefined) {
  3662. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  3663. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3664. if (options.samplingMode !== undefined) {
  3665. samplingMode = options.samplingMode;
  3666. }
  3667. }
  3668. var gl = this._gl;
  3669. var texture = gl.createTexture();
  3670. gl.bindTexture(gl.TEXTURE_2D, texture);
  3671. var width = size.width || size;
  3672. var height = size.height || size;
  3673. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3674. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3675. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3676. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3677. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3678. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  3679. var depthBuffer;
  3680. if (generateDepthBuffer) {
  3681. depthBuffer = gl.createRenderbuffer();
  3682. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  3683. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3684. }
  3685. var framebuffer = gl.createFramebuffer();
  3686. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  3687. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3688. if (generateDepthBuffer) {
  3689. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  3690. }
  3691. gl.bindTexture(gl.TEXTURE_2D, null);
  3692. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3693. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3694. texture._framebuffer = framebuffer;
  3695. if (generateDepthBuffer) {
  3696. texture._depthBuffer = depthBuffer;
  3697. }
  3698. texture._width = width;
  3699. texture._height = height;
  3700. texture.isReady = true;
  3701. texture.generateMipMaps = generateMipMaps;
  3702. texture.references = 1;
  3703. this._activeTexturesCache = [];
  3704. this._loadedTexturesCache.push(texture);
  3705. return texture;
  3706. };
  3707. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  3708. var _this = this;
  3709. var gl = this._gl;
  3710. var texture = gl.createTexture();
  3711. texture.isCube = true;
  3712. texture.url = rootUrl;
  3713. texture.references = 1;
  3714. this._loadedTexturesCache.push(texture);
  3715. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  3716. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3717. if (isDDS) {
  3718. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  3719. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3720. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3721. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3722. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3723. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  3724. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  3725. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3726. }
  3727. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3728. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3729. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3730. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3731. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3732. _this._activeTexturesCache = [];
  3733. texture._width = info.width;
  3734. texture._height = info.height;
  3735. texture.isReady = true;
  3736. }, null, null, true);
  3737. } else {
  3738. cascadeLoad(rootUrl, scene, function (imgs) {
  3739. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  3740. var height = width;
  3741. _this._workingCanvas.width = width;
  3742. _this._workingCanvas.height = height;
  3743. var faces = [
  3744. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3745. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3746. ];
  3747. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3748. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3749. for (var index = 0; index < faces.length; index++) {
  3750. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3751. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  3752. }
  3753. if (!noMipmap) {
  3754. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3755. }
  3756. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3757. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  3758. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3759. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3760. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3761. _this._activeTexturesCache = [];
  3762. texture._width = width;
  3763. texture._height = height;
  3764. texture.isReady = true;
  3765. }, extensions);
  3766. }
  3767. return texture;
  3768. };
  3769. Engine.prototype._releaseTexture = function (texture) {
  3770. var gl = this._gl;
  3771. if (texture._framebuffer) {
  3772. gl.deleteFramebuffer(texture._framebuffer);
  3773. }
  3774. if (texture._depthBuffer) {
  3775. gl.deleteRenderbuffer(texture._depthBuffer);
  3776. }
  3777. gl.deleteTexture(texture);
  3778. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3779. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3780. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3781. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3782. this._activeTexturesCache[channel] = null;
  3783. }
  3784. var index = this._loadedTexturesCache.indexOf(texture);
  3785. if (index !== -1) {
  3786. this._loadedTexturesCache.splice(index, 1);
  3787. }
  3788. };
  3789. Engine.prototype.bindSamplers = function (effect) {
  3790. this._gl.useProgram(effect.getProgram());
  3791. var samplers = effect.getSamplers();
  3792. for (var index = 0; index < samplers.length; index++) {
  3793. var uniform = effect.getUniform(samplers[index]);
  3794. this._gl.uniform1i(uniform, index);
  3795. }
  3796. this._currentEffect = null;
  3797. };
  3798. Engine.prototype._bindTexture = function (channel, texture) {
  3799. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3800. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3801. this._activeTexturesCache[channel] = null;
  3802. };
  3803. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  3804. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3805. };
  3806. Engine.prototype.setTexture = function (channel, texture) {
  3807. if (channel < 0) {
  3808. return;
  3809. }
  3810. if (!texture || !texture.isReady()) {
  3811. if (this._activeTexturesCache[channel] != null) {
  3812. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3813. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3814. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3815. this._activeTexturesCache[channel] = null;
  3816. }
  3817. return;
  3818. }
  3819. if (texture instanceof BABYLON.VideoTexture) {
  3820. if (texture.update()) {
  3821. this._activeTexturesCache[channel] = null;
  3822. }
  3823. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  3824. texture.delayLoad();
  3825. return;
  3826. }
  3827. if (this._activeTexturesCache[channel] == texture) {
  3828. return;
  3829. }
  3830. this._activeTexturesCache[channel] = texture;
  3831. var internalTexture = texture.getInternalTexture();
  3832. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3833. if (internalTexture.isCube) {
  3834. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3835. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3836. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3837. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3838. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3839. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3840. }
  3841. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3842. } else {
  3843. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  3844. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3845. internalTexture._cachedWrapU = texture.wrapU;
  3846. switch (texture.wrapU) {
  3847. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3848. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3849. break;
  3850. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3851. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3852. break;
  3853. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3854. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3855. break;
  3856. }
  3857. }
  3858. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3859. internalTexture._cachedWrapV = texture.wrapV;
  3860. switch (texture.wrapV) {
  3861. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3862. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3863. break;
  3864. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3865. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  3866. break;
  3867. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3868. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  3869. break;
  3870. }
  3871. }
  3872. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3873. }
  3874. };
  3875. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  3876. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3877. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  3878. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  3879. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  3880. }
  3881. };
  3882. Engine.prototype.readPixels = function (x, y, width, height) {
  3883. var data = new Uint8Array(height * width * 4);
  3884. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  3885. return data;
  3886. };
  3887. Engine.prototype.dispose = function () {
  3888. this.hideLoadingUI();
  3889. this.stopRenderLoop();
  3890. while (this.scenes.length) {
  3891. this.scenes[0].dispose();
  3892. }
  3893. for (var name in this._compiledEffects) {
  3894. this._gl.deleteProgram(this._compiledEffects[name]._program);
  3895. }
  3896. for (var i in this._vertexAttribArrays) {
  3897. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3898. continue;
  3899. }
  3900. this._gl.disableVertexAttribArray(i);
  3901. }
  3902. window.removeEventListener("blur", this._onBlur);
  3903. window.removeEventListener("focus", this._onFocus);
  3904. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  3905. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  3906. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  3907. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  3908. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  3909. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  3910. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  3911. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  3912. };
  3913. Engine.prototype.displayLoadingUI = function () {
  3914. var _this = this;
  3915. this._loadingDiv = document.createElement("div");
  3916. this._loadingDiv.style.opacity = "0";
  3917. this._loadingDiv.style.transition = "opacity 1.5s ease";
  3918. this._loadingTextDiv = document.createElement("div");
  3919. this._loadingTextDiv.style.position = "absolute";
  3920. this._loadingTextDiv.style.left = "0";
  3921. this._loadingTextDiv.style.top = "50%";
  3922. this._loadingTextDiv.style.marginTop = "80px";
  3923. this._loadingTextDiv.style.width = "100%";
  3924. this._loadingTextDiv.style.height = "20px";
  3925. this._loadingTextDiv.style.fontFamily = "Arial";
  3926. this._loadingTextDiv.style.fontSize = "14px";
  3927. this._loadingTextDiv.style.color = "white";
  3928. this._loadingTextDiv.style.textAlign = "center";
  3929. this._loadingTextDiv.innerHTML = "Loading";
  3930. this._loadingDiv.appendChild(this._loadingTextDiv);
  3931. var imgBack = new Image();
  3932. 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==";
  3933. imgBack.style.position = "absolute";
  3934. imgBack.style.left = "50%";
  3935. imgBack.style.top = "50%";
  3936. imgBack.style.marginLeft = "-50px";
  3937. imgBack.style.marginTop = "-50px";
  3938. imgBack.style.transition = "transform 1.0s ease";
  3939. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  3940. var deg = 360;
  3941. var onTransitionEnd = function () {
  3942. deg += 360;
  3943. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  3944. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  3945. };
  3946. imgBack.addEventListener("transitionend", onTransitionEnd);
  3947. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  3948. this._loadingDiv.appendChild(imgBack);
  3949. var imgFront = new Image();
  3950. 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=";
  3951. imgFront.style.position = "absolute";
  3952. imgFront.style.left = "50%";
  3953. imgFront.style.top = "50%";
  3954. imgFront.style.marginLeft = "-50px";
  3955. imgFront.style.marginTop = "-50px";
  3956. this._loadingDiv.appendChild(imgFront);
  3957. this._resizeLoadingUI = function () {
  3958. var canvasRect = _this.getRenderingCanvasClientRect();
  3959. _this._loadingDiv.style.position = "absolute";
  3960. _this._loadingDiv.style.left = canvasRect.left + "px";
  3961. _this._loadingDiv.style.top = canvasRect.top + "px";
  3962. _this._loadingDiv.style.width = canvasRect.width + "px";
  3963. _this._loadingDiv.style.height = canvasRect.height + "px";
  3964. };
  3965. this._resizeLoadingUI();
  3966. window.addEventListener("resize", this._resizeLoadingUI);
  3967. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3968. document.body.appendChild(this._loadingDiv);
  3969. setTimeout(function () {
  3970. _this._loadingDiv.style.opacity = "1";
  3971. imgBack.style.transform = "rotateZ(360deg)";
  3972. imgBack.style.webkitTransform = "rotateZ(360deg)";
  3973. }, 0);
  3974. };
  3975. Object.defineProperty(Engine.prototype, "loadingUIText", {
  3976. set: function (text) {
  3977. if (!this._loadingDiv) {
  3978. return;
  3979. }
  3980. this._loadingTextDiv.innerHTML = text;
  3981. },
  3982. enumerable: true,
  3983. configurable: true
  3984. });
  3985. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  3986. get: function () {
  3987. return this._loadingDivBackgroundColor;
  3988. },
  3989. set: function (color) {
  3990. this._loadingDivBackgroundColor = color;
  3991. if (!this._loadingDiv) {
  3992. return;
  3993. }
  3994. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3995. },
  3996. enumerable: true,
  3997. configurable: true
  3998. });
  3999. Engine.prototype.hideLoadingUI = function () {
  4000. var _this = this;
  4001. if (!this._loadingDiv) {
  4002. return;
  4003. }
  4004. var onTransitionEnd = function () {
  4005. if (!_this._loadingDiv) {
  4006. return;
  4007. }
  4008. document.body.removeChild(_this._loadingDiv);
  4009. window.removeEventListener("resize", _this._resizeLoadingUI);
  4010. _this._loadingDiv = null;
  4011. };
  4012. this._loadingDiv.style.opacity = "0";
  4013. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4014. };
  4015. Engine.isSupported = function () {
  4016. try {
  4017. if (navigator.isCocoonJS) {
  4018. return true;
  4019. }
  4020. var tempcanvas = document.createElement("canvas");
  4021. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4022. return gl != null && !!window.WebGLRenderingContext;
  4023. } catch (e) {
  4024. return false;
  4025. }
  4026. };
  4027. Engine._ALPHA_DISABLE = 0;
  4028. Engine._ALPHA_ADD = 1;
  4029. Engine._ALPHA_COMBINE = 2;
  4030. Engine._DELAYLOADSTATE_NONE = 0;
  4031. Engine._DELAYLOADSTATE_LOADED = 1;
  4032. Engine._DELAYLOADSTATE_LOADING = 2;
  4033. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4034. Engine.Epsilon = 0.001;
  4035. Engine.CollisionsEpsilon = 0.001;
  4036. Engine.ShadersRepository = "Babylon/Shaders/";
  4037. return Engine;
  4038. })();
  4039. BABYLON.Engine = Engine;
  4040. })(BABYLON || (BABYLON = {}));
  4041. var BABYLON;
  4042. (function (BABYLON) {
  4043. var Node = (function () {
  4044. function Node(name, scene) {
  4045. this.state = "";
  4046. this.animations = new Array();
  4047. this._childrenFlag = -1;
  4048. this._isEnabled = true;
  4049. this._isReady = true;
  4050. this._currentRenderId = -1;
  4051. this.name = name;
  4052. this.id = name;
  4053. this._scene = scene;
  4054. this._initCache();
  4055. }
  4056. Node.prototype.getScene = function () {
  4057. return this._scene;
  4058. };
  4059. Node.prototype.getEngine = function () {
  4060. return this._scene.getEngine();
  4061. };
  4062. Node.prototype.getWorldMatrix = function () {
  4063. return BABYLON.Matrix.Identity();
  4064. };
  4065. Node.prototype._initCache = function () {
  4066. this._cache = {};
  4067. this._cache.parent = undefined;
  4068. };
  4069. Node.prototype.updateCache = function (force) {
  4070. if (!force && this.isSynchronized())
  4071. return;
  4072. this._cache.parent = this.parent;
  4073. this._updateCache();
  4074. };
  4075. Node.prototype._updateCache = function (ignoreParentClass) {
  4076. };
  4077. Node.prototype._isSynchronized = function () {
  4078. return true;
  4079. };
  4080. Node.prototype.isSynchronizedWithParent = function () {
  4081. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4082. };
  4083. Node.prototype.isSynchronized = function (updateCache) {
  4084. var check = this.hasNewParent();
  4085. check = check || !this.isSynchronizedWithParent();
  4086. check = check || !this._isSynchronized();
  4087. if (updateCache)
  4088. this.updateCache(true);
  4089. return !check;
  4090. };
  4091. Node.prototype.hasNewParent = function (update) {
  4092. if (this._cache.parent === this.parent)
  4093. return false;
  4094. if (update)
  4095. this._cache.parent = this.parent;
  4096. return true;
  4097. };
  4098. Node.prototype.isReady = function () {
  4099. return this._isReady;
  4100. };
  4101. Node.prototype.isEnabled = function () {
  4102. if (!this._isEnabled) {
  4103. return false;
  4104. }
  4105. if (this.parent) {
  4106. return this.parent.isEnabled();
  4107. }
  4108. return true;
  4109. };
  4110. Node.prototype.setEnabled = function (value) {
  4111. this._isEnabled = value;
  4112. };
  4113. Node.prototype.isDescendantOf = function (ancestor) {
  4114. if (this.parent) {
  4115. if (this.parent === ancestor) {
  4116. return true;
  4117. }
  4118. return this.parent.isDescendantOf(ancestor);
  4119. }
  4120. return false;
  4121. };
  4122. Node.prototype._getDescendants = function (list, results) {
  4123. for (var index = 0; index < list.length; index++) {
  4124. var item = list[index];
  4125. if (item.isDescendantOf(this)) {
  4126. results.push(item);
  4127. }
  4128. }
  4129. };
  4130. Node.prototype.getDescendants = function () {
  4131. var results = [];
  4132. this._getDescendants(this._scene.meshes, results);
  4133. this._getDescendants(this._scene.lights, results);
  4134. this._getDescendants(this._scene.cameras, results);
  4135. return results;
  4136. };
  4137. Node.prototype._setReady = function (state) {
  4138. if (state == this._isReady) {
  4139. return;
  4140. }
  4141. if (!state) {
  4142. this._isReady = false;
  4143. return;
  4144. }
  4145. this._isReady = true;
  4146. if (this.onReady) {
  4147. this.onReady(this);
  4148. }
  4149. };
  4150. return Node;
  4151. })();
  4152. BABYLON.Node = Node;
  4153. })(BABYLON || (BABYLON = {}));
  4154. var BABYLON;
  4155. (function (BABYLON) {
  4156. var BoundingSphere = (function () {
  4157. function BoundingSphere(minimum, maximum) {
  4158. this.minimum = minimum;
  4159. this.maximum = maximum;
  4160. this._tempRadiusVector = BABYLON.Vector3.Zero();
  4161. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  4162. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  4163. this.radius = distance * 0.5;
  4164. this.centerWorld = BABYLON.Vector3.Zero();
  4165. this._update(BABYLON.Matrix.Identity());
  4166. }
  4167. BoundingSphere.prototype._update = function (world) {
  4168. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  4169. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  4170. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  4171. };
  4172. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  4173. for (var i = 0; i < 6; i++) {
  4174. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  4175. return false;
  4176. }
  4177. return true;
  4178. };
  4179. BoundingSphere.prototype.intersectsPoint = function (point) {
  4180. var x = this.centerWorld.x - point.x;
  4181. var y = this.centerWorld.y - point.y;
  4182. var z = this.centerWorld.z - point.z;
  4183. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4184. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  4185. return false;
  4186. return true;
  4187. };
  4188. BoundingSphere.Intersects = function (sphere0, sphere1) {
  4189. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  4190. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  4191. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  4192. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4193. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  4194. return false;
  4195. return true;
  4196. };
  4197. return BoundingSphere;
  4198. })();
  4199. BABYLON.BoundingSphere = BoundingSphere;
  4200. })(BABYLON || (BABYLON = {}));
  4201. var BABYLON;
  4202. (function (BABYLON) {
  4203. var BoundingBox = (function () {
  4204. function BoundingBox(minimum, maximum) {
  4205. this.minimum = minimum;
  4206. this.maximum = maximum;
  4207. this.vectors = new Array();
  4208. this.vectorsWorld = new Array();
  4209. this.vectors.push(this.minimum.clone());
  4210. this.vectors.push(this.maximum.clone());
  4211. this.vectors.push(this.minimum.clone());
  4212. this.vectors[2].x = this.maximum.x;
  4213. this.vectors.push(this.minimum.clone());
  4214. this.vectors[3].y = this.maximum.y;
  4215. this.vectors.push(this.minimum.clone());
  4216. this.vectors[4].z = this.maximum.z;
  4217. this.vectors.push(this.maximum.clone());
  4218. this.vectors[5].z = this.minimum.z;
  4219. this.vectors.push(this.maximum.clone());
  4220. this.vectors[6].x = this.minimum.x;
  4221. this.vectors.push(this.maximum.clone());
  4222. this.vectors[7].y = this.minimum.y;
  4223. this.center = this.maximum.add(this.minimum).scale(0.5);
  4224. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  4225. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  4226. for (var index = 0; index < this.vectors.length; index++) {
  4227. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  4228. }
  4229. this.minimumWorld = BABYLON.Vector3.Zero();
  4230. this.maximumWorld = BABYLON.Vector3.Zero();
  4231. this._update(BABYLON.Matrix.Identity());
  4232. }
  4233. BoundingBox.prototype.getWorldMatrix = function () {
  4234. return this._worldMatrix;
  4235. };
  4236. BoundingBox.prototype._update = function (world) {
  4237. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  4238. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  4239. for (var index = 0; index < this.vectors.length; index++) {
  4240. var v = this.vectorsWorld[index];
  4241. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  4242. if (v.x < this.minimumWorld.x)
  4243. this.minimumWorld.x = v.x;
  4244. if (v.y < this.minimumWorld.y)
  4245. this.minimumWorld.y = v.y;
  4246. if (v.z < this.minimumWorld.z)
  4247. this.minimumWorld.z = v.z;
  4248. if (v.x > this.maximumWorld.x)
  4249. this.maximumWorld.x = v.x;
  4250. if (v.y > this.maximumWorld.y)
  4251. this.maximumWorld.y = v.y;
  4252. if (v.z > this.maximumWorld.z)
  4253. this.maximumWorld.z = v.z;
  4254. }
  4255. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  4256. this.center.scaleInPlace(0.5);
  4257. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  4258. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  4259. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  4260. this._worldMatrix = world;
  4261. };
  4262. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  4263. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  4264. };
  4265. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4266. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  4267. };
  4268. BoundingBox.prototype.intersectsPoint = function (point) {
  4269. var delta = BABYLON.Engine.Epsilon;
  4270. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  4271. return false;
  4272. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  4273. return false;
  4274. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  4275. return false;
  4276. return true;
  4277. };
  4278. BoundingBox.prototype.intersectsSphere = function (sphere) {
  4279. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  4280. };
  4281. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  4282. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  4283. return false;
  4284. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  4285. return false;
  4286. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  4287. return false;
  4288. return true;
  4289. };
  4290. BoundingBox.Intersects = function (box0, box1) {
  4291. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  4292. return false;
  4293. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  4294. return false;
  4295. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  4296. return false;
  4297. return true;
  4298. };
  4299. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  4300. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  4301. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  4302. return (num <= (sphereRadius * sphereRadius));
  4303. };
  4304. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  4305. for (var p = 0; p < 6; p++) {
  4306. for (var i = 0; i < 8; i++) {
  4307. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4308. return false;
  4309. }
  4310. }
  4311. }
  4312. return true;
  4313. };
  4314. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  4315. for (var p = 0; p < 6; p++) {
  4316. var inCount = 8;
  4317. for (var i = 0; i < 8; i++) {
  4318. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4319. --inCount;
  4320. } else {
  4321. break;
  4322. }
  4323. }
  4324. if (inCount == 0)
  4325. return false;
  4326. }
  4327. return true;
  4328. };
  4329. return BoundingBox;
  4330. })();
  4331. BABYLON.BoundingBox = BoundingBox;
  4332. })(BABYLON || (BABYLON = {}));
  4333. var BABYLON;
  4334. (function (BABYLON) {
  4335. var computeBoxExtents = function (axis, box) {
  4336. var p = BABYLON.Vector3.Dot(box.center, axis);
  4337. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  4338. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  4339. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  4340. var r = r0 + r1 + r2;
  4341. return {
  4342. min: p - r,
  4343. max: p + r
  4344. };
  4345. };
  4346. var extentsOverlap = function (min0, max0, min1, max1) {
  4347. return !(min0 > max1 || min1 > max0);
  4348. };
  4349. var axisOverlap = function (axis, box0, box1) {
  4350. var result0 = computeBoxExtents(axis, box0);
  4351. var result1 = computeBoxExtents(axis, box1);
  4352. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  4353. };
  4354. var BoundingInfo = (function () {
  4355. function BoundingInfo(minimum, maximum) {
  4356. this.minimum = minimum;
  4357. this.maximum = maximum;
  4358. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  4359. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  4360. }
  4361. BoundingInfo.prototype._update = function (world) {
  4362. this.boundingBox._update(world);
  4363. this.boundingSphere._update(world);
  4364. };
  4365. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  4366. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  4367. return false;
  4368. return this.boundingBox.isInFrustum(frustumPlanes);
  4369. };
  4370. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4371. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  4372. };
  4373. BoundingInfo.prototype._checkCollision = function (collider) {
  4374. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  4375. };
  4376. BoundingInfo.prototype.intersectsPoint = function (point) {
  4377. if (!this.boundingSphere.centerWorld) {
  4378. return false;
  4379. }
  4380. if (!this.boundingSphere.intersectsPoint(point)) {
  4381. return false;
  4382. }
  4383. if (!this.boundingBox.intersectsPoint(point)) {
  4384. return false;
  4385. }
  4386. return true;
  4387. };
  4388. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  4389. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  4390. return false;
  4391. }
  4392. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  4393. return false;
  4394. }
  4395. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  4396. return false;
  4397. }
  4398. if (!precise) {
  4399. return true;
  4400. }
  4401. var box0 = this.boundingBox;
  4402. var box1 = boundingInfo.boundingBox;
  4403. if (!axisOverlap(box0.directions[0], box0, box1))
  4404. return false;
  4405. if (!axisOverlap(box0.directions[1], box0, box1))
  4406. return false;
  4407. if (!axisOverlap(box0.directions[2], box0, box1))
  4408. return false;
  4409. if (!axisOverlap(box1.directions[0], box0, box1))
  4410. return false;
  4411. if (!axisOverlap(box1.directions[1], box0, box1))
  4412. return false;
  4413. if (!axisOverlap(box1.directions[2], box0, box1))
  4414. return false;
  4415. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  4416. return false;
  4417. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  4418. return false;
  4419. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  4420. return false;
  4421. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  4422. return false;
  4423. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  4424. return false;
  4425. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  4426. return false;
  4427. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  4428. return false;
  4429. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  4430. return false;
  4431. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  4432. return false;
  4433. return true;
  4434. };
  4435. return BoundingInfo;
  4436. })();
  4437. BABYLON.BoundingInfo = BoundingInfo;
  4438. })(BABYLON || (BABYLON = {}));
  4439. var __extends = this.__extends || function (d, b) {
  4440. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4441. function __() { this.constructor = d; }
  4442. __.prototype = b.prototype;
  4443. d.prototype = new __();
  4444. };
  4445. var BABYLON;
  4446. (function (BABYLON) {
  4447. var Light = (function (_super) {
  4448. __extends(Light, _super);
  4449. function Light(name, scene) {
  4450. _super.call(this, name, scene);
  4451. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  4452. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  4453. this.intensity = 1.0;
  4454. this.range = Number.MAX_VALUE;
  4455. this.includedOnlyMeshes = new Array();
  4456. this.excludedMeshes = new Array();
  4457. this._excludedMeshesIds = new Array();
  4458. this._includedOnlyMeshesIds = new Array();
  4459. scene.lights.push(this);
  4460. }
  4461. Light.prototype.getShadowGenerator = function () {
  4462. return this._shadowGenerator;
  4463. };
  4464. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4465. };
  4466. Light.prototype._getWorldMatrix = function () {
  4467. return BABYLON.Matrix.Identity();
  4468. };
  4469. Light.prototype.canAffectMesh = function (mesh) {
  4470. if (!mesh) {
  4471. return true;
  4472. }
  4473. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4474. return false;
  4475. }
  4476. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4477. return false;
  4478. }
  4479. return true;
  4480. };
  4481. Light.prototype.getWorldMatrix = function () {
  4482. this._currentRenderId = this.getScene().getRenderId();
  4483. var worldMatrix = this._getWorldMatrix();
  4484. if (this.parent && this.parent.getWorldMatrix) {
  4485. if (!this._parentedWorldMatrix) {
  4486. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4487. }
  4488. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4489. return this._parentedWorldMatrix;
  4490. }
  4491. return worldMatrix;
  4492. };
  4493. Light.prototype.dispose = function () {
  4494. if (this._shadowGenerator) {
  4495. this._shadowGenerator.dispose();
  4496. this._shadowGenerator = null;
  4497. }
  4498. var index = this.getScene().lights.indexOf(this);
  4499. this.getScene().lights.splice(index, 1);
  4500. };
  4501. return Light;
  4502. })(BABYLON.Node);
  4503. BABYLON.Light = Light;
  4504. })(BABYLON || (BABYLON = {}));
  4505. var __extends = this.__extends || function (d, b) {
  4506. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4507. function __() { this.constructor = d; }
  4508. __.prototype = b.prototype;
  4509. d.prototype = new __();
  4510. };
  4511. var BABYLON;
  4512. (function (BABYLON) {
  4513. var PointLight = (function (_super) {
  4514. __extends(PointLight, _super);
  4515. function PointLight(name, position, scene) {
  4516. _super.call(this, name, scene);
  4517. this.position = position;
  4518. }
  4519. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  4520. if (this.parent && this.parent.getWorldMatrix) {
  4521. if (!this._transformedPosition) {
  4522. this._transformedPosition = BABYLON.Vector3.Zero();
  4523. }
  4524. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4525. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  4526. return;
  4527. }
  4528. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  4529. };
  4530. PointLight.prototype.getShadowGenerator = function () {
  4531. return null;
  4532. };
  4533. PointLight.prototype._getWorldMatrix = function () {
  4534. if (!this._worldMatrix) {
  4535. this._worldMatrix = BABYLON.Matrix.Identity();
  4536. }
  4537. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4538. return this._worldMatrix;
  4539. };
  4540. return PointLight;
  4541. })(BABYLON.Light);
  4542. BABYLON.PointLight = PointLight;
  4543. })(BABYLON || (BABYLON = {}));
  4544. var __extends = this.__extends || function (d, b) {
  4545. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4546. function __() { this.constructor = d; }
  4547. __.prototype = b.prototype;
  4548. d.prototype = new __();
  4549. };
  4550. var BABYLON;
  4551. (function (BABYLON) {
  4552. var SpotLight = (function (_super) {
  4553. __extends(SpotLight, _super);
  4554. function SpotLight(name, position, direction, angle, exponent, scene) {
  4555. _super.call(this, name, scene);
  4556. this.position = position;
  4557. this.direction = direction;
  4558. this.angle = angle;
  4559. this.exponent = exponent;
  4560. }
  4561. SpotLight.prototype.setDirectionToTarget = function (target) {
  4562. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4563. return this.direction;
  4564. };
  4565. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  4566. var normalizeDirection;
  4567. if (this.parent && this.parent.getWorldMatrix) {
  4568. if (!this._transformedDirection) {
  4569. this._transformedDirection = BABYLON.Vector3.Zero();
  4570. }
  4571. if (!this._transformedPosition) {
  4572. this._transformedPosition = BABYLON.Vector3.Zero();
  4573. }
  4574. var parentWorldMatrix = this.parent.getWorldMatrix();
  4575. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  4576. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  4577. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  4578. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  4579. } else {
  4580. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  4581. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4582. }
  4583. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  4584. };
  4585. SpotLight.prototype._getWorldMatrix = function () {
  4586. if (!this._worldMatrix) {
  4587. this._worldMatrix = BABYLON.Matrix.Identity();
  4588. }
  4589. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4590. return this._worldMatrix;
  4591. };
  4592. return SpotLight;
  4593. })(BABYLON.Light);
  4594. BABYLON.SpotLight = SpotLight;
  4595. })(BABYLON || (BABYLON = {}));
  4596. var __extends = this.__extends || function (d, b) {
  4597. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4598. function __() { this.constructor = d; }
  4599. __.prototype = b.prototype;
  4600. d.prototype = new __();
  4601. };
  4602. var BABYLON;
  4603. (function (BABYLON) {
  4604. var DirectionalLight = (function (_super) {
  4605. __extends(DirectionalLight, _super);
  4606. function DirectionalLight(name, direction, scene) {
  4607. _super.call(this, name, scene);
  4608. this.direction = direction;
  4609. this.position = direction.scale(-1);
  4610. }
  4611. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  4612. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4613. return this.direction;
  4614. };
  4615. DirectionalLight.prototype._computeTransformedPosition = function () {
  4616. if (this.parent && this.parent.getWorldMatrix) {
  4617. if (!this._transformedPosition) {
  4618. this._transformedPosition = BABYLON.Vector3.Zero();
  4619. }
  4620. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4621. return true;
  4622. }
  4623. return false;
  4624. };
  4625. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  4626. if (this.parent && this.parent.getWorldMatrix) {
  4627. if (!this._transformedDirection) {
  4628. this._transformedDirection = BABYLON.Vector3.Zero();
  4629. }
  4630. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  4631. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  4632. return;
  4633. }
  4634. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  4635. };
  4636. DirectionalLight.prototype._getWorldMatrix = function () {
  4637. if (!this._worldMatrix) {
  4638. this._worldMatrix = BABYLON.Matrix.Identity();
  4639. }
  4640. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4641. return this._worldMatrix;
  4642. };
  4643. return DirectionalLight;
  4644. })(BABYLON.Light);
  4645. BABYLON.DirectionalLight = DirectionalLight;
  4646. })(BABYLON || (BABYLON = {}));
  4647. var BABYLON;
  4648. (function (BABYLON) {
  4649. var ShadowGenerator = (function () {
  4650. function ShadowGenerator(mapSize, light) {
  4651. var _this = this;
  4652. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4653. this._darkness = 0;
  4654. this._transparencyShadow = false;
  4655. this._viewMatrix = BABYLON.Matrix.Zero();
  4656. this._projectionMatrix = BABYLON.Matrix.Zero();
  4657. this._transformMatrix = BABYLON.Matrix.Zero();
  4658. this._worldViewProjection = BABYLON.Matrix.Zero();
  4659. this._light = light;
  4660. this._scene = light.getScene();
  4661. light._shadowGenerator = this;
  4662. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  4663. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4664. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4665. this._shadowMap.renderParticles = false;
  4666. var renderSubMesh = function (subMesh) {
  4667. var mesh = subMesh.getRenderingMesh();
  4668. var scene = _this._scene;
  4669. var engine = scene.getEngine();
  4670. engine.setState(subMesh.getMaterial().backFaceCulling);
  4671. var batch = mesh._getInstancesRenderList(subMesh._id);
  4672. if (batch.mustReturn) {
  4673. return;
  4674. }
  4675. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  4676. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  4677. engine.enableEffect(_this._effect);
  4678. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  4679. var material = subMesh.getMaterial();
  4680. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  4681. if (material && material.needAlphaTesting()) {
  4682. var alphaTexture = material.getAlphaTestTexture();
  4683. _this._effect.setTexture("diffuseSampler", alphaTexture);
  4684. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  4685. }
  4686. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  4687. if (useBones) {
  4688. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  4689. }
  4690. if (hardwareInstancedRendering) {
  4691. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  4692. } else {
  4693. if (batch.renderSelf[subMesh._id]) {
  4694. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  4695. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  4696. }
  4697. if (batch.visibleInstances[subMesh._id]) {
  4698. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  4699. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  4700. _this._effect.setMatrix("world", instance.getWorldMatrix());
  4701. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  4702. }
  4703. }
  4704. }
  4705. } else {
  4706. _this._shadowMap.resetRefreshCounter();
  4707. }
  4708. };
  4709. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  4710. var index;
  4711. for (index = 0; index < opaqueSubMeshes.length; index++) {
  4712. renderSubMesh(opaqueSubMeshes.data[index]);
  4713. }
  4714. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  4715. renderSubMesh(alphaTestSubMeshes.data[index]);
  4716. }
  4717. if (_this._transparencyShadow) {
  4718. for (index = 0; index < transparentSubMeshes.length; index++) {
  4719. renderSubMesh(transparentSubMeshes.data[index]);
  4720. }
  4721. }
  4722. };
  4723. }
  4724. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  4725. get: function () {
  4726. return ShadowGenerator._FILTER_NONE;
  4727. },
  4728. enumerable: true,
  4729. configurable: true
  4730. });
  4731. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  4732. get: function () {
  4733. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  4734. },
  4735. enumerable: true,
  4736. configurable: true
  4737. });
  4738. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  4739. get: function () {
  4740. return ShadowGenerator._FILTER_POISSONSAMPLING;
  4741. },
  4742. enumerable: true,
  4743. configurable: true
  4744. });
  4745. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  4746. get: function () {
  4747. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4748. },
  4749. set: function (value) {
  4750. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  4751. },
  4752. enumerable: true,
  4753. configurable: true
  4754. });
  4755. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  4756. get: function () {
  4757. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  4758. },
  4759. set: function (value) {
  4760. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  4761. },
  4762. enumerable: true,
  4763. configurable: true
  4764. });
  4765. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  4766. var defines = [];
  4767. if (this.useVarianceShadowMap) {
  4768. defines.push("#define VSM");
  4769. }
  4770. var attribs = [BABYLON.VertexBuffer.PositionKind];
  4771. var mesh = subMesh.getMesh();
  4772. var material = subMesh.getMaterial();
  4773. if (material && material.needAlphaTesting()) {
  4774. defines.push("#define ALPHATEST");
  4775. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  4776. attribs.push(BABYLON.VertexBuffer.UVKind);
  4777. defines.push("#define UV1");
  4778. }
  4779. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  4780. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  4781. defines.push("#define UV2");
  4782. }
  4783. }
  4784. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  4785. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  4786. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  4787. defines.push("#define BONES");
  4788. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  4789. }
  4790. if (useInstances) {
  4791. defines.push("#define INSTANCES");
  4792. attribs.push("world0");
  4793. attribs.push("world1");
  4794. attribs.push("world2");
  4795. attribs.push("world3");
  4796. }
  4797. var join = defines.join("\n");
  4798. if (this._cachedDefines != join) {
  4799. this._cachedDefines = join;
  4800. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  4801. }
  4802. return this._effect.isReady();
  4803. };
  4804. ShadowGenerator.prototype.getShadowMap = function () {
  4805. return this._shadowMap;
  4806. };
  4807. ShadowGenerator.prototype.getLight = function () {
  4808. return this._light;
  4809. };
  4810. ShadowGenerator.prototype.getTransformMatrix = function () {
  4811. var lightPosition = this._light.position;
  4812. var lightDirection = this._light.direction;
  4813. if (this._light._computeTransformedPosition()) {
  4814. lightPosition = this._light._transformedPosition;
  4815. }
  4816. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  4817. this._cachedPosition = lightPosition.clone();
  4818. this._cachedDirection = lightDirection.clone();
  4819. var activeCamera = this._scene.activeCamera;
  4820. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  4821. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  4822. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  4823. }
  4824. return this._transformMatrix;
  4825. };
  4826. ShadowGenerator.prototype.getDarkness = function () {
  4827. return this._darkness;
  4828. };
  4829. ShadowGenerator.prototype.setDarkness = function (darkness) {
  4830. if (darkness >= 1.0)
  4831. this._darkness = 1.0;
  4832. else if (darkness <= 0.0)
  4833. this._darkness = 0.0;
  4834. else
  4835. this._darkness = darkness;
  4836. };
  4837. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  4838. this._transparencyShadow = hasShadow;
  4839. };
  4840. ShadowGenerator.prototype.dispose = function () {
  4841. this._shadowMap.dispose();
  4842. };
  4843. ShadowGenerator._FILTER_NONE = 0;
  4844. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  4845. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  4846. return ShadowGenerator;
  4847. })();
  4848. BABYLON.ShadowGenerator = ShadowGenerator;
  4849. })(BABYLON || (BABYLON = {}));
  4850. var __extends = this.__extends || function (d, b) {
  4851. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4852. function __() { this.constructor = d; }
  4853. __.prototype = b.prototype;
  4854. d.prototype = new __();
  4855. };
  4856. var BABYLON;
  4857. (function (BABYLON) {
  4858. var HemisphericLight = (function (_super) {
  4859. __extends(HemisphericLight, _super);
  4860. function HemisphericLight(name, direction, scene) {
  4861. _super.call(this, name, scene);
  4862. this.direction = direction;
  4863. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  4864. }
  4865. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  4866. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  4867. return this.direction;
  4868. };
  4869. HemisphericLight.prototype.getShadowGenerator = function () {
  4870. return null;
  4871. };
  4872. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  4873. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4874. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  4875. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  4876. };
  4877. HemisphericLight.prototype._getWorldMatrix = function () {
  4878. if (!this._worldMatrix) {
  4879. this._worldMatrix = BABYLON.Matrix.Identity();
  4880. }
  4881. return this._worldMatrix;
  4882. };
  4883. return HemisphericLight;
  4884. })(BABYLON.Light);
  4885. BABYLON.HemisphericLight = HemisphericLight;
  4886. })(BABYLON || (BABYLON = {}));
  4887. var BABYLON;
  4888. (function (BABYLON) {
  4889. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  4890. if (boxMin.x > sphereCenter.x + sphereRadius)
  4891. return false;
  4892. if (sphereCenter.x - sphereRadius > boxMax.x)
  4893. return false;
  4894. if (boxMin.y > sphereCenter.y + sphereRadius)
  4895. return false;
  4896. if (sphereCenter.y - sphereRadius > boxMax.y)
  4897. return false;
  4898. if (boxMin.z > sphereCenter.z + sphereRadius)
  4899. return false;
  4900. if (sphereCenter.z - sphereRadius > boxMax.z)
  4901. return false;
  4902. return true;
  4903. };
  4904. var getLowestRoot = function (a, b, c, maxR) {
  4905. var determinant = b * b - 4.0 * a * c;
  4906. var result = { root: 0, found: false };
  4907. if (determinant < 0)
  4908. return result;
  4909. var sqrtD = Math.sqrt(determinant);
  4910. var r1 = (-b - sqrtD) / (2.0 * a);
  4911. var r2 = (-b + sqrtD) / (2.0 * a);
  4912. if (r1 > r2) {
  4913. var temp = r2;
  4914. r2 = r1;
  4915. r1 = temp;
  4916. }
  4917. if (r1 > 0 && r1 < maxR) {
  4918. result.root = r1;
  4919. result.found = true;
  4920. return result;
  4921. }
  4922. if (r2 > 0 && r2 < maxR) {
  4923. result.root = r2;
  4924. result.found = true;
  4925. return result;
  4926. }
  4927. return result;
  4928. };
  4929. var Collider = (function () {
  4930. function Collider() {
  4931. this.radius = new BABYLON.Vector3(1, 1, 1);
  4932. this.retry = 0;
  4933. this.basePointWorld = BABYLON.Vector3.Zero();
  4934. this.velocityWorld = BABYLON.Vector3.Zero();
  4935. this.normalizedVelocity = BABYLON.Vector3.Zero();
  4936. this._collisionPoint = BABYLON.Vector3.Zero();
  4937. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  4938. this._tempVector = BABYLON.Vector3.Zero();
  4939. this._tempVector2 = BABYLON.Vector3.Zero();
  4940. this._tempVector3 = BABYLON.Vector3.Zero();
  4941. this._tempVector4 = BABYLON.Vector3.Zero();
  4942. this._edge = BABYLON.Vector3.Zero();
  4943. this._baseToVertex = BABYLON.Vector3.Zero();
  4944. this._destinationPoint = BABYLON.Vector3.Zero();
  4945. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  4946. this._displacementVector = BABYLON.Vector3.Zero();
  4947. }
  4948. Collider.prototype._initialize = function (source, dir, e) {
  4949. this.velocity = dir;
  4950. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  4951. this.basePoint = source;
  4952. source.multiplyToRef(this.radius, this.basePointWorld);
  4953. dir.multiplyToRef(this.radius, this.velocityWorld);
  4954. this.velocityWorldLength = this.velocityWorld.length();
  4955. this.epsilon = e;
  4956. this.collisionFound = false;
  4957. };
  4958. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  4959. pa.subtractToRef(point, this._tempVector);
  4960. pb.subtractToRef(point, this._tempVector2);
  4961. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  4962. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4963. if (d < 0)
  4964. return false;
  4965. pc.subtractToRef(point, this._tempVector3);
  4966. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  4967. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4968. if (d < 0)
  4969. return false;
  4970. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  4971. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4972. return d >= 0;
  4973. };
  4974. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  4975. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  4976. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  4977. if (distance > this.velocityWorldLength + max + sphereRadius) {
  4978. return false;
  4979. }
  4980. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  4981. return false;
  4982. return true;
  4983. };
  4984. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  4985. var t0;
  4986. var embeddedInPlane = false;
  4987. if (!subMesh._trianglePlanes) {
  4988. subMesh._trianglePlanes = [];
  4989. }
  4990. if (!subMesh._trianglePlanes[faceIndex]) {
  4991. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  4992. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  4993. }
  4994. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  4995. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  4996. return;
  4997. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  4998. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  4999. if (normalDotVelocity == 0) {
  5000. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5001. return;
  5002. embeddedInPlane = true;
  5003. t0 = 0;
  5004. } else {
  5005. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5006. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5007. if (t0 > t1) {
  5008. var temp = t1;
  5009. t1 = t0;
  5010. t0 = temp;
  5011. }
  5012. if (t0 > 1.0 || t1 < 0.0)
  5013. return;
  5014. if (t0 < 0)
  5015. t0 = 0;
  5016. if (t0 > 1.0)
  5017. t0 = 1.0;
  5018. }
  5019. this._collisionPoint.copyFromFloats(0, 0, 0);
  5020. var found = false;
  5021. var t = 1.0;
  5022. if (!embeddedInPlane) {
  5023. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5024. this.velocity.scaleToRef(t0, this._tempVector);
  5025. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5026. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5027. found = true;
  5028. t = t0;
  5029. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5030. }
  5031. }
  5032. if (!found) {
  5033. var velocitySquaredLength = this.velocity.lengthSquared();
  5034. var a = velocitySquaredLength;
  5035. this.basePoint.subtractToRef(p1, this._tempVector);
  5036. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5037. var c = this._tempVector.lengthSquared() - 1.0;
  5038. var lowestRoot = getLowestRoot(a, b, c, t);
  5039. if (lowestRoot.found) {
  5040. t = lowestRoot.root;
  5041. found = true;
  5042. this._collisionPoint.copyFrom(p1);
  5043. }
  5044. this.basePoint.subtractToRef(p2, this._tempVector);
  5045. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5046. c = this._tempVector.lengthSquared() - 1.0;
  5047. lowestRoot = getLowestRoot(a, b, c, t);
  5048. if (lowestRoot.found) {
  5049. t = lowestRoot.root;
  5050. found = true;
  5051. this._collisionPoint.copyFrom(p2);
  5052. }
  5053. this.basePoint.subtractToRef(p3, this._tempVector);
  5054. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5055. c = this._tempVector.lengthSquared() - 1.0;
  5056. lowestRoot = getLowestRoot(a, b, c, t);
  5057. if (lowestRoot.found) {
  5058. t = lowestRoot.root;
  5059. found = true;
  5060. this._collisionPoint.copyFrom(p3);
  5061. }
  5062. p2.subtractToRef(p1, this._edge);
  5063. p1.subtractToRef(this.basePoint, this._baseToVertex);
  5064. var edgeSquaredLength = this._edge.lengthSquared();
  5065. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5066. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5067. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5068. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5069. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5070. lowestRoot = getLowestRoot(a, b, c, t);
  5071. if (lowestRoot.found) {
  5072. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5073. if (f >= 0.0 && f <= 1.0) {
  5074. t = lowestRoot.root;
  5075. found = true;
  5076. this._edge.scaleInPlace(f);
  5077. p1.addToRef(this._edge, this._collisionPoint);
  5078. }
  5079. }
  5080. p3.subtractToRef(p2, this._edge);
  5081. p2.subtractToRef(this.basePoint, this._baseToVertex);
  5082. edgeSquaredLength = this._edge.lengthSquared();
  5083. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5084. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5085. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5086. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5087. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5088. lowestRoot = getLowestRoot(a, b, c, t);
  5089. if (lowestRoot.found) {
  5090. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5091. if (f >= 0.0 && f <= 1.0) {
  5092. t = lowestRoot.root;
  5093. found = true;
  5094. this._edge.scaleInPlace(f);
  5095. p2.addToRef(this._edge, this._collisionPoint);
  5096. }
  5097. }
  5098. p1.subtractToRef(p3, this._edge);
  5099. p3.subtractToRef(this.basePoint, this._baseToVertex);
  5100. edgeSquaredLength = this._edge.lengthSquared();
  5101. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5102. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5103. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5104. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5105. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5106. lowestRoot = getLowestRoot(a, b, c, t);
  5107. if (lowestRoot.found) {
  5108. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5109. if (f >= 0.0 && f <= 1.0) {
  5110. t = lowestRoot.root;
  5111. found = true;
  5112. this._edge.scaleInPlace(f);
  5113. p3.addToRef(this._edge, this._collisionPoint);
  5114. }
  5115. }
  5116. }
  5117. if (found) {
  5118. var distToCollision = t * this.velocity.length();
  5119. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  5120. if (!this.intersectionPoint) {
  5121. this.intersectionPoint = this._collisionPoint.clone();
  5122. } else {
  5123. this.intersectionPoint.copyFrom(this._collisionPoint);
  5124. }
  5125. this.nearestDistance = distToCollision;
  5126. this.collisionFound = true;
  5127. this.collidedMesh = subMesh.getMesh();
  5128. }
  5129. }
  5130. };
  5131. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  5132. for (var i = indexStart; i < indexEnd; i += 3) {
  5133. var p1 = pts[indices[i] - decal];
  5134. var p2 = pts[indices[i + 1] - decal];
  5135. var p3 = pts[indices[i + 2] - decal];
  5136. this._testTriangle(i, subMesh, p3, p2, p1);
  5137. }
  5138. };
  5139. Collider.prototype._getResponse = function (pos, vel) {
  5140. pos.addToRef(vel, this._destinationPoint);
  5141. vel.scaleInPlace((this.nearestDistance / vel.length()));
  5142. this.basePoint.addToRef(vel, pos);
  5143. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  5144. this._slidePlaneNormal.normalize();
  5145. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  5146. pos.addInPlace(this._displacementVector);
  5147. this.intersectionPoint.addInPlace(this._displacementVector);
  5148. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  5149. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  5150. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  5151. };
  5152. return Collider;
  5153. })();
  5154. BABYLON.Collider = Collider;
  5155. })(BABYLON || (BABYLON = {}));
  5156. var __extends = this.__extends || function (d, b) {
  5157. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5158. function __() { this.constructor = d; }
  5159. __.prototype = b.prototype;
  5160. d.prototype = new __();
  5161. };
  5162. var BABYLON;
  5163. (function (BABYLON) {
  5164. var Camera = (function (_super) {
  5165. __extends(Camera, _super);
  5166. function Camera(name, position, scene) {
  5167. _super.call(this, name, scene);
  5168. this.position = position;
  5169. this.upVector = BABYLON.Vector3.Up();
  5170. this.orthoLeft = null;
  5171. this.orthoRight = null;
  5172. this.orthoBottom = null;
  5173. this.orthoTop = null;
  5174. this.fov = 0.8;
  5175. this.minZ = 1.0;
  5176. this.maxZ = 10000.0;
  5177. this.inertia = 0.9;
  5178. this.mode = Camera.PERSPECTIVE_CAMERA;
  5179. this.isIntermediate = false;
  5180. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  5181. this.subCameras = [];
  5182. this.layerMask = 0xFFFFFFFF;
  5183. this._computedViewMatrix = BABYLON.Matrix.Identity();
  5184. this._projectionMatrix = new BABYLON.Matrix();
  5185. this._postProcesses = new Array();
  5186. this._postProcessesTakenIndices = [];
  5187. scene.cameras.push(this);
  5188. if (!scene.activeCamera) {
  5189. scene.activeCamera = this;
  5190. }
  5191. }
  5192. Camera.prototype._initCache = function () {
  5193. _super.prototype._initCache.call(this);
  5194. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5195. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5196. this._cache.mode = undefined;
  5197. this._cache.minZ = undefined;
  5198. this._cache.maxZ = undefined;
  5199. this._cache.fov = undefined;
  5200. this._cache.aspectRatio = undefined;
  5201. this._cache.orthoLeft = undefined;
  5202. this._cache.orthoRight = undefined;
  5203. this._cache.orthoBottom = undefined;
  5204. this._cache.orthoTop = undefined;
  5205. this._cache.renderWidth = undefined;
  5206. this._cache.renderHeight = undefined;
  5207. };
  5208. Camera.prototype._updateCache = function (ignoreParentClass) {
  5209. if (!ignoreParentClass) {
  5210. _super.prototype._updateCache.call(this);
  5211. }
  5212. var engine = this.getEngine();
  5213. this._cache.position.copyFrom(this.position);
  5214. this._cache.upVector.copyFrom(this.upVector);
  5215. this._cache.mode = this.mode;
  5216. this._cache.minZ = this.minZ;
  5217. this._cache.maxZ = this.maxZ;
  5218. this._cache.fov = this.fov;
  5219. this._cache.aspectRatio = engine.getAspectRatio(this);
  5220. this._cache.orthoLeft = this.orthoLeft;
  5221. this._cache.orthoRight = this.orthoRight;
  5222. this._cache.orthoBottom = this.orthoBottom;
  5223. this._cache.orthoTop = this.orthoTop;
  5224. this._cache.renderWidth = engine.getRenderWidth();
  5225. this._cache.renderHeight = engine.getRenderHeight();
  5226. };
  5227. Camera.prototype._updateFromScene = function () {
  5228. this.updateCache();
  5229. this._update();
  5230. };
  5231. Camera.prototype._isSynchronized = function () {
  5232. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  5233. };
  5234. Camera.prototype._isSynchronizedViewMatrix = function () {
  5235. if (!_super.prototype._isSynchronized.call(this))
  5236. return false;
  5237. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  5238. };
  5239. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  5240. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  5241. if (!check) {
  5242. return false;
  5243. }
  5244. var engine = this.getEngine();
  5245. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5246. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  5247. } else {
  5248. 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();
  5249. }
  5250. return check;
  5251. };
  5252. Camera.prototype.attachControl = function (element) {
  5253. };
  5254. Camera.prototype.detachControl = function (element) {
  5255. };
  5256. Camera.prototype._update = function () {
  5257. };
  5258. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  5259. if (typeof insertAt === "undefined") { insertAt = null; }
  5260. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  5261. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  5262. return 0;
  5263. }
  5264. if (insertAt == null || insertAt < 0) {
  5265. this._postProcesses.push(postProcess);
  5266. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  5267. return this._postProcesses.length - 1;
  5268. }
  5269. var add = 0;
  5270. if (this._postProcesses[insertAt]) {
  5271. var start = this._postProcesses.length - 1;
  5272. for (var i = start; i >= insertAt + 1; --i) {
  5273. this._postProcesses[i + 1] = this._postProcesses[i];
  5274. }
  5275. add = 1;
  5276. }
  5277. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5278. if (this._postProcessesTakenIndices[i] < insertAt) {
  5279. continue;
  5280. }
  5281. start = this._postProcessesTakenIndices.length - 1;
  5282. for (var j = start; j >= i; --j) {
  5283. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  5284. }
  5285. this._postProcessesTakenIndices[i] = insertAt;
  5286. break;
  5287. }
  5288. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  5289. this._postProcessesTakenIndices.push(insertAt);
  5290. }
  5291. var result = insertAt + add;
  5292. this._postProcesses[result] = postProcess;
  5293. return result;
  5294. };
  5295. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  5296. if (typeof atIndices === "undefined") { atIndices = null; }
  5297. var result = [];
  5298. if (!atIndices) {
  5299. var length = this._postProcesses.length;
  5300. for (var i = 0; i < length; i++) {
  5301. if (this._postProcesses[i] !== postProcess) {
  5302. continue;
  5303. }
  5304. delete this._postProcesses[i];
  5305. var index = this._postProcessesTakenIndices.indexOf(i);
  5306. this._postProcessesTakenIndices.splice(index, 1);
  5307. }
  5308. } else {
  5309. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  5310. for (i = 0; i < atIndices.length; i++) {
  5311. var foundPostProcess = this._postProcesses[atIndices[i]];
  5312. if (foundPostProcess !== postProcess) {
  5313. result.push(i);
  5314. continue;
  5315. }
  5316. delete this._postProcesses[atIndices[i]];
  5317. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  5318. this._postProcessesTakenIndices.splice(index, 1);
  5319. }
  5320. }
  5321. return result;
  5322. };
  5323. Camera.prototype.getWorldMatrix = function () {
  5324. if (!this._worldMatrix) {
  5325. this._worldMatrix = BABYLON.Matrix.Identity();
  5326. }
  5327. var viewMatrix = this.getViewMatrix();
  5328. viewMatrix.invertToRef(this._worldMatrix);
  5329. return this._worldMatrix;
  5330. };
  5331. Camera.prototype._getViewMatrix = function () {
  5332. return BABYLON.Matrix.Identity();
  5333. };
  5334. Camera.prototype.getViewMatrix = function () {
  5335. this._computedViewMatrix = this._computeViewMatrix();
  5336. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  5337. return this._computedViewMatrix;
  5338. }
  5339. if (!this._worldMatrix) {
  5340. this._worldMatrix = BABYLON.Matrix.Identity();
  5341. }
  5342. this._computedViewMatrix.invertToRef(this._worldMatrix);
  5343. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  5344. this._computedViewMatrix.invert();
  5345. this._currentRenderId = this.getScene().getRenderId();
  5346. return this._computedViewMatrix;
  5347. };
  5348. Camera.prototype._computeViewMatrix = function (force) {
  5349. if (!force && this._isSynchronizedViewMatrix()) {
  5350. return this._computedViewMatrix;
  5351. }
  5352. this._computedViewMatrix = this._getViewMatrix();
  5353. if (!this.parent || !this.parent.getWorldMatrix) {
  5354. this._currentRenderId = this.getScene().getRenderId();
  5355. }
  5356. return this._computedViewMatrix;
  5357. };
  5358. Camera.prototype.getProjectionMatrix = function (force) {
  5359. if (!force && this._isSynchronizedProjectionMatrix()) {
  5360. return this._projectionMatrix;
  5361. }
  5362. var engine = this.getEngine();
  5363. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5364. if (this.minZ <= 0) {
  5365. this.minZ = 0.1;
  5366. }
  5367. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  5368. return this._projectionMatrix;
  5369. }
  5370. var halfWidth = engine.getRenderWidth() / 2.0;
  5371. var halfHeight = engine.getRenderHeight() / 2.0;
  5372. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  5373. return this._projectionMatrix;
  5374. };
  5375. Camera.prototype.dispose = function () {
  5376. var index = this.getScene().cameras.indexOf(this);
  5377. this.getScene().cameras.splice(index, 1);
  5378. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5379. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  5380. }
  5381. };
  5382. Camera.PERSPECTIVE_CAMERA = 0;
  5383. Camera.ORTHOGRAPHIC_CAMERA = 1;
  5384. return Camera;
  5385. })(BABYLON.Node);
  5386. BABYLON.Camera = Camera;
  5387. })(BABYLON || (BABYLON = {}));
  5388. var __extends = this.__extends || function (d, b) {
  5389. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5390. function __() { this.constructor = d; }
  5391. __.prototype = b.prototype;
  5392. d.prototype = new __();
  5393. };
  5394. var BABYLON;
  5395. (function (BABYLON) {
  5396. var TargetCamera = (function (_super) {
  5397. __extends(TargetCamera, _super);
  5398. function TargetCamera(name, position, scene) {
  5399. _super.call(this, name, position, scene);
  5400. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5401. this.cameraRotation = new BABYLON.Vector2(0, 0);
  5402. this.rotation = new BABYLON.Vector3(0, 0, 0);
  5403. this.speed = 2.0;
  5404. this.noRotationConstraint = false;
  5405. this.lockedTarget = null;
  5406. this._currentTarget = BABYLON.Vector3.Zero();
  5407. this._viewMatrix = BABYLON.Matrix.Zero();
  5408. this._camMatrix = BABYLON.Matrix.Zero();
  5409. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  5410. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  5411. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  5412. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  5413. this._lookAtTemp = BABYLON.Matrix.Zero();
  5414. this._tempMatrix = BABYLON.Matrix.Zero();
  5415. }
  5416. TargetCamera.prototype._getLockedTargetPosition = function () {
  5417. if (!this.lockedTarget) {
  5418. return null;
  5419. }
  5420. return this.lockedTarget.position || this.lockedTarget;
  5421. };
  5422. TargetCamera.prototype._initCache = function () {
  5423. _super.prototype._initCache.call(this);
  5424. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5425. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5426. };
  5427. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  5428. if (!ignoreParentClass) {
  5429. _super.prototype._updateCache.call(this);
  5430. }
  5431. var lockedTargetPosition = this._getLockedTargetPosition();
  5432. if (!lockedTargetPosition) {
  5433. this._cache.lockedTarget = null;
  5434. } else {
  5435. if (!this._cache.lockedTarget) {
  5436. this._cache.lockedTarget = lockedTargetPosition.clone();
  5437. } else {
  5438. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  5439. }
  5440. }
  5441. this._cache.rotation.copyFrom(this.rotation);
  5442. };
  5443. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  5444. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  5445. return false;
  5446. }
  5447. var lockedTargetPosition = this._getLockedTargetPosition();
  5448. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  5449. };
  5450. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  5451. return this.speed * ((BABYLON.Tools.GetDeltaTime() / (BABYLON.Tools.GetFps() * 10.0)));
  5452. };
  5453. TargetCamera.prototype.setTarget = function (target) {
  5454. this.upVector.normalize();
  5455. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  5456. this._camMatrix.invert();
  5457. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  5458. var vDir = target.subtract(this.position);
  5459. if (vDir.x >= 0.0) {
  5460. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5461. } else {
  5462. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5463. }
  5464. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5465. if (isNaN(this.rotation.x)) {
  5466. this.rotation.x = 0;
  5467. }
  5468. if (isNaN(this.rotation.y)) {
  5469. this.rotation.y = 0;
  5470. }
  5471. if (isNaN(this.rotation.z)) {
  5472. this.rotation.z = 0;
  5473. }
  5474. };
  5475. TargetCamera.prototype.getTarget = function () {
  5476. return this._currentTarget;
  5477. };
  5478. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5479. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5480. };
  5481. TargetCamera.prototype._updatePosition = function () {
  5482. this.position.addInPlace(this.cameraDirection);
  5483. };
  5484. TargetCamera.prototype._update = function () {
  5485. var needToMove = this._decideIfNeedsToMove();
  5486. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5487. if (needToMove) {
  5488. this._updatePosition();
  5489. }
  5490. if (needToRotate) {
  5491. this.rotation.x += this.cameraRotation.x;
  5492. this.rotation.y += this.cameraRotation.y;
  5493. if (!this.noRotationConstraint) {
  5494. var limit = (Math.PI / 2) * 0.95;
  5495. if (this.rotation.x > limit)
  5496. this.rotation.x = limit;
  5497. if (this.rotation.x < -limit)
  5498. this.rotation.x = -limit;
  5499. }
  5500. }
  5501. if (needToMove) {
  5502. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  5503. this.cameraDirection.x = 0;
  5504. }
  5505. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  5506. this.cameraDirection.y = 0;
  5507. }
  5508. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  5509. this.cameraDirection.z = 0;
  5510. }
  5511. this.cameraDirection.scaleInPlace(this.inertia);
  5512. }
  5513. if (needToRotate) {
  5514. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  5515. this.cameraRotation.x = 0;
  5516. }
  5517. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  5518. this.cameraRotation.y = 0;
  5519. }
  5520. this.cameraRotation.scaleInPlace(this.inertia);
  5521. }
  5522. };
  5523. TargetCamera.prototype._getViewMatrix = function () {
  5524. if (!this.lockedTarget) {
  5525. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  5526. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  5527. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5528. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  5529. this._lookAtTemp.invert();
  5530. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  5531. } else {
  5532. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5533. }
  5534. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  5535. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  5536. } else {
  5537. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  5538. }
  5539. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  5540. return this._viewMatrix;
  5541. };
  5542. return TargetCamera;
  5543. })(BABYLON.Camera);
  5544. BABYLON.TargetCamera = TargetCamera;
  5545. })(BABYLON || (BABYLON = {}));
  5546. var __extends = this.__extends || function (d, b) {
  5547. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5548. function __() { this.constructor = d; }
  5549. __.prototype = b.prototype;
  5550. d.prototype = new __();
  5551. };
  5552. var BABYLON;
  5553. (function (BABYLON) {
  5554. var FollowCamera = (function (_super) {
  5555. __extends(FollowCamera, _super);
  5556. function FollowCamera(name, position, scene) {
  5557. _super.call(this, name, position, scene);
  5558. this.radius = 12;
  5559. this.rotationOffset = 0;
  5560. this.heightOffset = 4;
  5561. this.cameraAcceleration = 0.05;
  5562. this.maxCameraSpeed = 20;
  5563. }
  5564. FollowCamera.prototype.getRadians = function (degrees) {
  5565. return degrees * Math.PI / 180;
  5566. };
  5567. FollowCamera.prototype.follow = function (cameraTarget) {
  5568. if (!cameraTarget)
  5569. return;
  5570. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  5571. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  5572. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  5573. var dx = targetX - this.position.x;
  5574. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  5575. var dz = (targetZ) - this.position.z;
  5576. var vx = dx * this.cameraAcceleration * 2;
  5577. var vy = dy * this.cameraAcceleration;
  5578. var vz = dz * this.cameraAcceleration * 2;
  5579. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  5580. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5581. }
  5582. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  5583. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5584. }
  5585. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  5586. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5587. }
  5588. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  5589. this.setTarget(cameraTarget.position);
  5590. };
  5591. FollowCamera.prototype._update = function () {
  5592. _super.prototype._update.call(this);
  5593. this.follow(this.target);
  5594. };
  5595. return FollowCamera;
  5596. })(BABYLON.TargetCamera);
  5597. BABYLON.FollowCamera = FollowCamera;
  5598. })(BABYLON || (BABYLON = {}));
  5599. var __extends = this.__extends || function (d, b) {
  5600. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5601. function __() { this.constructor = d; }
  5602. __.prototype = b.prototype;
  5603. d.prototype = new __();
  5604. };
  5605. var BABYLON;
  5606. (function (BABYLON) {
  5607. var FreeCamera = (function (_super) {
  5608. __extends(FreeCamera, _super);
  5609. function FreeCamera(name, position, scene) {
  5610. _super.call(this, name, position, scene);
  5611. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  5612. this.keysUp = [38];
  5613. this.keysDown = [40];
  5614. this.keysLeft = [37];
  5615. this.keysRight = [39];
  5616. this.checkCollisions = false;
  5617. this.applyGravity = false;
  5618. this.angularSensibility = 2000.0;
  5619. this._keys = [];
  5620. this._collider = new BABYLON.Collider();
  5621. this._needMoveForGravity = true;
  5622. this._oldPosition = BABYLON.Vector3.Zero();
  5623. this._diffPosition = BABYLON.Vector3.Zero();
  5624. this._newPosition = BABYLON.Vector3.Zero();
  5625. }
  5626. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  5627. var _this = this;
  5628. var previousPosition;
  5629. var engine = this.getEngine();
  5630. if (this._attachedElement) {
  5631. return;
  5632. }
  5633. this._attachedElement = element;
  5634. if (this._onMouseDown === undefined) {
  5635. this._onMouseDown = function (evt) {
  5636. previousPosition = {
  5637. x: evt.clientX,
  5638. y: evt.clientY
  5639. };
  5640. if (!noPreventDefault) {
  5641. evt.preventDefault();
  5642. }
  5643. };
  5644. this._onMouseUp = function (evt) {
  5645. previousPosition = null;
  5646. if (!noPreventDefault) {
  5647. evt.preventDefault();
  5648. }
  5649. };
  5650. this._onMouseOut = function (evt) {
  5651. previousPosition = null;
  5652. _this._keys = [];
  5653. if (!noPreventDefault) {
  5654. evt.preventDefault();
  5655. }
  5656. };
  5657. this._onMouseMove = function (evt) {
  5658. if (!previousPosition && !engine.isPointerLock) {
  5659. return;
  5660. }
  5661. var offsetX;
  5662. var offsetY;
  5663. if (!engine.isPointerLock) {
  5664. offsetX = evt.clientX - previousPosition.x;
  5665. offsetY = evt.clientY - previousPosition.y;
  5666. } else {
  5667. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5668. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5669. }
  5670. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  5671. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  5672. previousPosition = {
  5673. x: evt.clientX,
  5674. y: evt.clientY
  5675. };
  5676. if (!noPreventDefault) {
  5677. evt.preventDefault();
  5678. }
  5679. };
  5680. this._onKeyDown = function (evt) {
  5681. 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) {
  5682. var index = _this._keys.indexOf(evt.keyCode);
  5683. if (index === -1) {
  5684. _this._keys.push(evt.keyCode);
  5685. }
  5686. if (!noPreventDefault) {
  5687. evt.preventDefault();
  5688. }
  5689. }
  5690. };
  5691. this._onKeyUp = function (evt) {
  5692. 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) {
  5693. var index = _this._keys.indexOf(evt.keyCode);
  5694. if (index >= 0) {
  5695. _this._keys.splice(index, 1);
  5696. }
  5697. if (!noPreventDefault) {
  5698. evt.preventDefault();
  5699. }
  5700. }
  5701. };
  5702. this._onLostFocus = function () {
  5703. _this._keys = [];
  5704. };
  5705. this._reset = function () {
  5706. _this._keys = [];
  5707. previousPosition = null;
  5708. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5709. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  5710. };
  5711. }
  5712. element.addEventListener("mousedown", this._onMouseDown, false);
  5713. element.addEventListener("mouseup", this._onMouseUp, false);
  5714. element.addEventListener("mouseout", this._onMouseOut, false);
  5715. element.addEventListener("mousemove", this._onMouseMove, false);
  5716. BABYLON.Tools.RegisterTopRootEvents([
  5717. { name: "keydown", handler: this._onKeyDown },
  5718. { name: "keyup", handler: this._onKeyUp },
  5719. { name: "blur", handler: this._onLostFocus }
  5720. ]);
  5721. };
  5722. FreeCamera.prototype.detachControl = function (element) {
  5723. if (this._attachedElement != element) {
  5724. return;
  5725. }
  5726. element.removeEventListener("mousedown", this._onMouseDown);
  5727. element.removeEventListener("mouseup", this._onMouseUp);
  5728. element.removeEventListener("mouseout", this._onMouseOut);
  5729. element.removeEventListener("mousemove", this._onMouseMove);
  5730. BABYLON.Tools.UnregisterTopRootEvents([
  5731. { name: "keydown", handler: this._onKeyDown },
  5732. { name: "keyup", handler: this._onKeyUp },
  5733. { name: "blur", handler: this._onLostFocus }
  5734. ]);
  5735. this._attachedElement = null;
  5736. if (this._reset) {
  5737. this._reset();
  5738. }
  5739. };
  5740. FreeCamera.prototype._collideWithWorld = function (velocity) {
  5741. var globalPosition;
  5742. if (this.parent) {
  5743. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  5744. } else {
  5745. globalPosition = this.position;
  5746. }
  5747. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  5748. this._collider.radius = this.ellipsoid;
  5749. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  5750. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  5751. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  5752. this.position.addInPlace(this._diffPosition);
  5753. if (this.onCollide) {
  5754. this.onCollide(this._collider.collidedMesh);
  5755. }
  5756. }
  5757. };
  5758. FreeCamera.prototype._checkInputs = function () {
  5759. if (!this._localDirection) {
  5760. this._localDirection = BABYLON.Vector3.Zero();
  5761. this._transformedDirection = BABYLON.Vector3.Zero();
  5762. }
  5763. for (var index = 0; index < this._keys.length; index++) {
  5764. var keyCode = this._keys[index];
  5765. var speed = this._computeLocalCameraSpeed();
  5766. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5767. this._localDirection.copyFromFloats(-speed, 0, 0);
  5768. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5769. this._localDirection.copyFromFloats(0, 0, speed);
  5770. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5771. this._localDirection.copyFromFloats(speed, 0, 0);
  5772. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5773. this._localDirection.copyFromFloats(0, 0, -speed);
  5774. }
  5775. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  5776. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  5777. this.cameraDirection.addInPlace(this._transformedDirection);
  5778. }
  5779. };
  5780. FreeCamera.prototype._decideIfNeedsToMove = function () {
  5781. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5782. };
  5783. FreeCamera.prototype._updatePosition = function () {
  5784. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  5785. this._collideWithWorld(this.cameraDirection);
  5786. if (this.applyGravity) {
  5787. var oldPosition = this.position;
  5788. this._collideWithWorld(this.getScene().gravity);
  5789. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  5790. }
  5791. } else {
  5792. this.position.addInPlace(this.cameraDirection);
  5793. }
  5794. };
  5795. FreeCamera.prototype._update = function () {
  5796. this._checkInputs();
  5797. _super.prototype._update.call(this);
  5798. };
  5799. return FreeCamera;
  5800. })(BABYLON.TargetCamera);
  5801. BABYLON.FreeCamera = FreeCamera;
  5802. })(BABYLON || (BABYLON = {}));
  5803. var __extends = this.__extends || function (d, b) {
  5804. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5805. function __() { this.constructor = d; }
  5806. __.prototype = b.prototype;
  5807. d.prototype = new __();
  5808. };
  5809. var BABYLON;
  5810. (function (BABYLON) {
  5811. var TouchCamera = (function (_super) {
  5812. __extends(TouchCamera, _super);
  5813. function TouchCamera(name, position, scene) {
  5814. _super.call(this, name, position, scene);
  5815. this._offsetX = null;
  5816. this._offsetY = null;
  5817. this._pointerCount = 0;
  5818. this._pointerPressed = [];
  5819. this.angularSensibility = 200000.0;
  5820. this.moveSensibility = 500.0;
  5821. }
  5822. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5823. var _this = this;
  5824. var previousPosition;
  5825. if (this._attachedCanvas) {
  5826. return;
  5827. }
  5828. this._attachedCanvas = canvas;
  5829. if (this._onPointerDown === undefined) {
  5830. this._onPointerDown = function (evt) {
  5831. if (!noPreventDefault) {
  5832. evt.preventDefault();
  5833. }
  5834. _this._pointerPressed.push(evt.pointerId);
  5835. if (_this._pointerPressed.length !== 1) {
  5836. return;
  5837. }
  5838. previousPosition = {
  5839. x: evt.clientX,
  5840. y: evt.clientY
  5841. };
  5842. };
  5843. this._onPointerUp = function (evt) {
  5844. if (!noPreventDefault) {
  5845. evt.preventDefault();
  5846. }
  5847. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5848. if (index === -1) {
  5849. return;
  5850. }
  5851. _this._pointerPressed.splice(index, 1);
  5852. if (index != 0) {
  5853. return;
  5854. }
  5855. previousPosition = null;
  5856. _this._offsetX = null;
  5857. _this._offsetY = null;
  5858. };
  5859. this._onPointerMove = function (evt) {
  5860. if (!noPreventDefault) {
  5861. evt.preventDefault();
  5862. }
  5863. if (!previousPosition) {
  5864. return;
  5865. }
  5866. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5867. if (index != 0) {
  5868. return;
  5869. }
  5870. _this._offsetX = evt.clientX - previousPosition.x;
  5871. _this._offsetY = -(evt.clientY - previousPosition.y);
  5872. };
  5873. this._onLostFocus = function () {
  5874. _this._offsetX = null;
  5875. _this._offsetY = null;
  5876. };
  5877. }
  5878. canvas.addEventListener("pointerdown", this._onPointerDown);
  5879. canvas.addEventListener("pointerup", this._onPointerUp);
  5880. canvas.addEventListener("pointerout", this._onPointerUp);
  5881. canvas.addEventListener("pointermove", this._onPointerMove);
  5882. BABYLON.Tools.RegisterTopRootEvents([
  5883. { name: "blur", handler: this._onLostFocus }
  5884. ]);
  5885. };
  5886. TouchCamera.prototype.detachControl = function (canvas) {
  5887. if (this._attachedCanvas != canvas) {
  5888. return;
  5889. }
  5890. canvas.removeEventListener("pointerdown", this._onPointerDown);
  5891. canvas.removeEventListener("pointerup", this._onPointerUp);
  5892. canvas.removeEventListener("pointerout", this._onPointerUp);
  5893. canvas.removeEventListener("pointermove", this._onPointerMove);
  5894. BABYLON.Tools.UnregisterTopRootEvents([
  5895. { name: "blur", handler: this._onLostFocus }
  5896. ]);
  5897. this._attachedCanvas = null;
  5898. };
  5899. TouchCamera.prototype._checkInputs = function () {
  5900. if (!this._offsetX) {
  5901. return;
  5902. }
  5903. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  5904. if (this._pointerPressed.length > 1) {
  5905. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  5906. } else {
  5907. var speed = this._computeLocalCameraSpeed();
  5908. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5909. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5910. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5911. }
  5912. };
  5913. return TouchCamera;
  5914. })(BABYLON.FreeCamera);
  5915. BABYLON.TouchCamera = TouchCamera;
  5916. })(BABYLON || (BABYLON = {}));
  5917. var __extends = this.__extends || function (d, b) {
  5918. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5919. function __() { this.constructor = d; }
  5920. __.prototype = b.prototype;
  5921. d.prototype = new __();
  5922. };
  5923. var BABYLON;
  5924. (function (BABYLON) {
  5925. var DeviceOrientationCamera = (function (_super) {
  5926. __extends(DeviceOrientationCamera, _super);
  5927. function DeviceOrientationCamera(name, position, scene) {
  5928. var _this = this;
  5929. _super.call(this, name, position, scene);
  5930. this._offsetX = null;
  5931. this._offsetY = null;
  5932. this._orientationGamma = 0;
  5933. this._orientationBeta = 0;
  5934. this._initialOrientationGamma = 0;
  5935. this._initialOrientationBeta = 0;
  5936. this.angularSensibility = 10000.0;
  5937. this.moveSensibility = 50.0;
  5938. window.addEventListener("resize", function () {
  5939. _this._initialOrientationGamma = null;
  5940. }, false);
  5941. }
  5942. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5943. var _this = this;
  5944. if (this._attachedCanvas) {
  5945. return;
  5946. }
  5947. this._attachedCanvas = canvas;
  5948. if (!this._orientationChanged) {
  5949. this._orientationChanged = function (evt) {
  5950. if (!_this._initialOrientationGamma) {
  5951. _this._initialOrientationGamma = evt.gamma;
  5952. _this._initialOrientationBeta = evt.beta;
  5953. }
  5954. _this._orientationGamma = evt.gamma;
  5955. _this._orientationBeta = evt.beta;
  5956. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  5957. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  5958. };
  5959. }
  5960. window.addEventListener("deviceorientation", this._orientationChanged);
  5961. };
  5962. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  5963. if (this._attachedCanvas != canvas) {
  5964. return;
  5965. }
  5966. window.removeEventListener("deviceorientation", this._orientationChanged);
  5967. this._attachedCanvas = null;
  5968. this._orientationGamma = 0;
  5969. this._orientationBeta = 0;
  5970. this._initialOrientationGamma = 0;
  5971. this._initialOrientationBeta = 0;
  5972. };
  5973. DeviceOrientationCamera.prototype._checkInputs = function () {
  5974. if (!this._offsetX) {
  5975. return;
  5976. }
  5977. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  5978. var speed = this._computeLocalCameraSpeed();
  5979. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5980. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5981. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5982. };
  5983. return DeviceOrientationCamera;
  5984. })(BABYLON.FreeCamera);
  5985. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  5986. })(BABYLON || (BABYLON = {}));
  5987. var __extends = this.__extends || function (d, b) {
  5988. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5989. function __() { this.constructor = d; }
  5990. __.prototype = b.prototype;
  5991. d.prototype = new __();
  5992. };
  5993. var BABYLON;
  5994. (function (BABYLON) {
  5995. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  5996. var ArcRotateCamera = (function (_super) {
  5997. __extends(ArcRotateCamera, _super);
  5998. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  5999. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6000. this.alpha = alpha;
  6001. this.beta = beta;
  6002. this.radius = radius;
  6003. this.target = target;
  6004. this.inertialAlphaOffset = 0;
  6005. this.inertialBetaOffset = 0;
  6006. this.inertialRadiusOffset = 0;
  6007. this.lowerAlphaLimit = null;
  6008. this.upperAlphaLimit = null;
  6009. this.lowerBetaLimit = 0.01;
  6010. this.upperBetaLimit = Math.PI;
  6011. this.lowerRadiusLimit = null;
  6012. this.upperRadiusLimit = null;
  6013. this.angularSensibility = 1000.0;
  6014. this.wheelPrecision = 3.0;
  6015. this.keysUp = [38];
  6016. this.keysDown = [40];
  6017. this.keysLeft = [37];
  6018. this.keysRight = [39];
  6019. this.zoomOnFactor = 1;
  6020. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6021. this._keys = [];
  6022. this._viewMatrix = new BABYLON.Matrix();
  6023. this.checkCollisions = false;
  6024. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6025. this._collider = new BABYLON.Collider();
  6026. this._previousPosition = BABYLON.Vector3.Zero();
  6027. this._collisionVelocity = BABYLON.Vector3.Zero();
  6028. this._newPosition = BABYLON.Vector3.Zero();
  6029. this.pinchPrecision = 20;
  6030. this.getViewMatrix();
  6031. }
  6032. ArcRotateCamera.prototype._getTargetPosition = function () {
  6033. return this.target.position || this.target;
  6034. };
  6035. ArcRotateCamera.prototype._initCache = function () {
  6036. _super.prototype._initCache.call(this);
  6037. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6038. this._cache.alpha = undefined;
  6039. this._cache.beta = undefined;
  6040. this._cache.radius = undefined;
  6041. this._cache.targetScreenOffset = undefined;
  6042. };
  6043. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6044. if (!ignoreParentClass) {
  6045. _super.prototype._updateCache.call(this);
  6046. }
  6047. this._cache.target.copyFrom(this._getTargetPosition());
  6048. this._cache.alpha = this.alpha;
  6049. this._cache.beta = this.beta;
  6050. this._cache.radius = this.radius;
  6051. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  6052. };
  6053. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  6054. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  6055. return false;
  6056. 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);
  6057. };
  6058. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  6059. var _this = this;
  6060. var previousPosition;
  6061. var pointerId;
  6062. var pinchStarted = false;
  6063. var pinchPointX1, pinchPointX2;
  6064. if (this._attachedElement) {
  6065. return;
  6066. }
  6067. this._attachedElement = element;
  6068. var engine = this.getEngine();
  6069. if (this._onPointerDown === undefined) {
  6070. this._onPointerDown = function (evt) {
  6071. if (pointerId) {
  6072. return;
  6073. }
  6074. pointerId = evt.pointerId;
  6075. previousPosition = {
  6076. x: evt.clientX,
  6077. y: evt.clientY
  6078. };
  6079. if (!noPreventDefault) {
  6080. evt.preventDefault();
  6081. }
  6082. };
  6083. this._onPointerUp = function (evt) {
  6084. previousPosition = null;
  6085. pointerId = null;
  6086. if (!noPreventDefault) {
  6087. evt.preventDefault();
  6088. }
  6089. };
  6090. this._onPointerMove = function (evt) {
  6091. if (!previousPosition) {
  6092. return;
  6093. }
  6094. if (pointerId !== evt.pointerId) {
  6095. return;
  6096. }
  6097. if (pinchStarted) {
  6098. return;
  6099. }
  6100. var offsetX = evt.clientX - previousPosition.x;
  6101. var offsetY = evt.clientY - previousPosition.y;
  6102. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6103. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6104. previousPosition = {
  6105. x: evt.clientX,
  6106. y: evt.clientY
  6107. };
  6108. if (!noPreventDefault) {
  6109. evt.preventDefault();
  6110. }
  6111. };
  6112. this._onMouseMove = function (evt) {
  6113. if (!engine.isPointerLock) {
  6114. return;
  6115. }
  6116. if (pinchStarted) {
  6117. return;
  6118. }
  6119. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6120. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6121. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6122. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6123. if (!noPreventDefault) {
  6124. evt.preventDefault();
  6125. }
  6126. };
  6127. this._wheel = function (event) {
  6128. var delta = 0;
  6129. if (event.wheelDelta) {
  6130. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  6131. } else if (event.detail) {
  6132. delta = -event.detail / _this.wheelPrecision;
  6133. }
  6134. if (delta)
  6135. _this.inertialRadiusOffset += delta;
  6136. if (event.preventDefault) {
  6137. if (!noPreventDefault) {
  6138. event.preventDefault();
  6139. }
  6140. }
  6141. };
  6142. this._onKeyDown = function (evt) {
  6143. 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) {
  6144. var index = _this._keys.indexOf(evt.keyCode);
  6145. if (index === -1) {
  6146. _this._keys.push(evt.keyCode);
  6147. }
  6148. if (evt.preventDefault) {
  6149. if (!noPreventDefault) {
  6150. evt.preventDefault();
  6151. }
  6152. }
  6153. }
  6154. };
  6155. this._onKeyUp = function (evt) {
  6156. 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) {
  6157. var index = _this._keys.indexOf(evt.keyCode);
  6158. if (index >= 0) {
  6159. _this._keys.splice(index, 1);
  6160. }
  6161. if (evt.preventDefault) {
  6162. if (!noPreventDefault) {
  6163. evt.preventDefault();
  6164. }
  6165. }
  6166. }
  6167. };
  6168. this._onLostFocus = function () {
  6169. _this._keys = [];
  6170. pointerId = null;
  6171. };
  6172. this._onGestureStart = function (e) {
  6173. if (window.MSGesture === undefined) {
  6174. return;
  6175. }
  6176. if (!_this._MSGestureHandler) {
  6177. _this._MSGestureHandler = new MSGesture();
  6178. _this._MSGestureHandler.target = element;
  6179. }
  6180. _this._MSGestureHandler.addPointer(e.pointerId);
  6181. };
  6182. this._onGesture = function (e) {
  6183. _this.radius *= e.scale;
  6184. if (e.preventDefault) {
  6185. if (!noPreventDefault) {
  6186. e.stopPropagation();
  6187. e.preventDefault();
  6188. }
  6189. }
  6190. };
  6191. this._reset = function () {
  6192. _this._keys = [];
  6193. _this.inertialAlphaOffset = 0;
  6194. _this.inertialBetaOffset = 0;
  6195. _this.inertialRadiusOffset = 0;
  6196. previousPosition = null;
  6197. pointerId = null;
  6198. };
  6199. this._touchStart = function (event) {
  6200. if (event.touches.length == 2) {
  6201. pinchStarted = true;
  6202. _this._pinchStart(event);
  6203. }
  6204. };
  6205. this._touchMove = function (event) {
  6206. if (pinchStarted) {
  6207. _this._pinchMove(event);
  6208. }
  6209. };
  6210. this._touchEnd = function (event) {
  6211. if (pinchStarted) {
  6212. _this._pinchEnd(event);
  6213. }
  6214. };
  6215. this._pinchStart = function (event) {
  6216. pinchPointX1 = event.touches[0].clientX;
  6217. pinchPointX2 = event.touches[1].clientX;
  6218. pinchStarted = true;
  6219. };
  6220. this._pinchMove = function (event) {
  6221. var delta = 0;
  6222. var direction = 1;
  6223. var distanceXOrigine, distanceXNow;
  6224. if (event.touches.length != 2)
  6225. return;
  6226. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  6227. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  6228. if (distanceXNow < distanceXOrigine) {
  6229. direction = -1;
  6230. }
  6231. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  6232. _this.inertialRadiusOffset += delta;
  6233. pinchPointX1 = event.touches[0].clientX;
  6234. pinchPointX2 = event.touches[1].clientX;
  6235. };
  6236. this._pinchEnd = function (event) {
  6237. pinchStarted = false;
  6238. };
  6239. }
  6240. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6241. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  6242. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  6243. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6244. element.addEventListener("mousemove", this._onMouseMove, false);
  6245. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  6246. element.addEventListener("MSGestureChange", this._onGesture, false);
  6247. element.addEventListener('mousewheel', this._wheel, false);
  6248. element.addEventListener('DOMMouseScroll', this._wheel, false);
  6249. element.addEventListener('touchstart', this._touchStart, false);
  6250. element.addEventListener('touchmove', this._touchMove, false);
  6251. element.addEventListener('touchend', this._touchEnd, false);
  6252. BABYLON.Tools.RegisterTopRootEvents([
  6253. { name: "keydown", handler: this._onKeyDown },
  6254. { name: "keyup", handler: this._onKeyUp },
  6255. { name: "blur", handler: this._onLostFocus }
  6256. ]);
  6257. };
  6258. ArcRotateCamera.prototype.detachControl = function (element) {
  6259. if (this._attachedElement != element) {
  6260. return;
  6261. }
  6262. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  6263. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  6264. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  6265. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  6266. element.removeEventListener("mousemove", this._onMouseMove);
  6267. element.removeEventListener("MSPointerDown", this._onGestureStart);
  6268. element.removeEventListener("MSGestureChange", this._onGesture);
  6269. element.removeEventListener('mousewheel', this._wheel);
  6270. element.removeEventListener('DOMMouseScroll', this._wheel);
  6271. element.removeEventListener('touchstart', this._touchStart);
  6272. element.removeEventListener('touchmove', this._touchMove);
  6273. element.removeEventListener('touchend', this._touchEnd);
  6274. BABYLON.Tools.UnregisterTopRootEvents([
  6275. { name: "keydown", handler: this._onKeyDown },
  6276. { name: "keyup", handler: this._onKeyUp },
  6277. { name: "blur", handler: this._onLostFocus }
  6278. ]);
  6279. this._MSGestureHandler = null;
  6280. this._attachedElement = null;
  6281. if (this._reset) {
  6282. this._reset();
  6283. }
  6284. };
  6285. ArcRotateCamera.prototype._update = function () {
  6286. for (var index = 0; index < this._keys.length; index++) {
  6287. var keyCode = this._keys[index];
  6288. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6289. this.inertialAlphaOffset -= 0.01;
  6290. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6291. this.inertialBetaOffset -= 0.01;
  6292. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6293. this.inertialAlphaOffset += 0.01;
  6294. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6295. this.inertialBetaOffset += 0.01;
  6296. }
  6297. }
  6298. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  6299. this.alpha += this.inertialAlphaOffset;
  6300. this.beta += this.inertialBetaOffset;
  6301. this.radius -= this.inertialRadiusOffset;
  6302. this.inertialAlphaOffset *= this.inertia;
  6303. this.inertialBetaOffset *= this.inertia;
  6304. this.inertialRadiusOffset *= this.inertia;
  6305. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  6306. this.inertialAlphaOffset = 0;
  6307. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  6308. this.inertialBetaOffset = 0;
  6309. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  6310. this.inertialRadiusOffset = 0;
  6311. }
  6312. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  6313. this.alpha = this.lowerAlphaLimit;
  6314. }
  6315. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  6316. this.alpha = this.upperAlphaLimit;
  6317. }
  6318. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  6319. this.beta = this.lowerBetaLimit;
  6320. }
  6321. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  6322. this.beta = this.upperBetaLimit;
  6323. }
  6324. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  6325. this.radius = this.lowerRadiusLimit;
  6326. }
  6327. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  6328. this.radius = this.upperRadiusLimit;
  6329. }
  6330. };
  6331. ArcRotateCamera.prototype.setPosition = function (position) {
  6332. var radiusv3 = position.subtract(this._getTargetPosition());
  6333. this.radius = radiusv3.length();
  6334. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  6335. if (radiusv3.z < 0) {
  6336. this.alpha = 2 * Math.PI - this.alpha;
  6337. }
  6338. this.beta = Math.acos(radiusv3.y / this.radius);
  6339. };
  6340. ArcRotateCamera.prototype._getViewMatrix = function () {
  6341. var cosa = Math.cos(this.alpha);
  6342. var sina = Math.sin(this.alpha);
  6343. var cosb = Math.cos(this.beta);
  6344. var sinb = Math.sin(this.beta);
  6345. var target = this._getTargetPosition();
  6346. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  6347. if (this.checkCollisions) {
  6348. this._collider.radius = this.collisionRadius;
  6349. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  6350. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  6351. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  6352. this.position.copyFrom(this._previousPosition);
  6353. this.alpha = this._previousAlpha;
  6354. this.beta = this._previousBeta;
  6355. this.radius = this._previousRadius;
  6356. if (this.onCollide) {
  6357. this.onCollide(this._collider.collidedMesh);
  6358. }
  6359. }
  6360. }
  6361. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  6362. this._previousAlpha = this.alpha;
  6363. this._previousBeta = this.beta;
  6364. this._previousRadius = this.radius;
  6365. this._previousPosition.copyFrom(this.position);
  6366. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  6367. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  6368. return this._viewMatrix;
  6369. };
  6370. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  6371. meshes = meshes || this.getScene().meshes;
  6372. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  6373. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  6374. this.radius = distance * this.zoomOnFactor;
  6375. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  6376. };
  6377. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  6378. var meshesOrMinMaxVector;
  6379. var distance;
  6380. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  6381. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  6382. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  6383. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  6384. } else {
  6385. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  6386. distance = meshesOrMinMaxVectorAndDistance.distance;
  6387. }
  6388. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  6389. this.maxZ = distance * 2;
  6390. };
  6391. return ArcRotateCamera;
  6392. })(BABYLON.Camera);
  6393. BABYLON.ArcRotateCamera = ArcRotateCamera;
  6394. })(BABYLON || (BABYLON = {}));
  6395. var BABYLON;
  6396. (function (BABYLON) {
  6397. var Scene = (function () {
  6398. function Scene(engine) {
  6399. this.autoClear = true;
  6400. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6401. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  6402. this.forceWireframe = false;
  6403. this.cameraToUseForPointers = null;
  6404. this.fogMode = BABYLON.Scene.FOGMODE_NONE;
  6405. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6406. this.fogDensity = 0.1;
  6407. this.fogStart = 0;
  6408. this.fogEnd = 1000.0;
  6409. this.shadowsEnabled = true;
  6410. this.lightsEnabled = true;
  6411. this.lights = new Array();
  6412. this.cameras = new Array();
  6413. this.activeCameras = new Array();
  6414. this.meshes = new Array();
  6415. this._geometries = new Array();
  6416. this.materials = new Array();
  6417. this.multiMaterials = new Array();
  6418. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  6419. this.texturesEnabled = true;
  6420. this.textures = new Array();
  6421. this.particlesEnabled = true;
  6422. this.particleSystems = new Array();
  6423. this.spriteManagers = new Array();
  6424. this.layers = new Array();
  6425. this.skeletons = new Array();
  6426. this.lensFlaresEnabled = true;
  6427. this.lensFlareSystems = new Array();
  6428. this.collisionsEnabled = true;
  6429. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  6430. this.postProcessesEnabled = true;
  6431. this.renderTargetsEnabled = true;
  6432. this.customRenderTargets = new Array();
  6433. this.importedMeshesFiles = new Array();
  6434. this._actionManagers = new Array();
  6435. this._meshesForIntersections = new BABYLON.SmartArray(256);
  6436. this.proceduralTexturesEnabled = true;
  6437. this._proceduralTextures = new Array();
  6438. this._totalVertices = 0;
  6439. this._activeVertices = 0;
  6440. this._activeParticles = 0;
  6441. this._lastFrameDuration = 0;
  6442. this._evaluateActiveMeshesDuration = 0;
  6443. this._renderTargetsDuration = 0;
  6444. this._particlesDuration = 0;
  6445. this._renderDuration = 0;
  6446. this._spritesDuration = 0;
  6447. this._animationRatio = 0;
  6448. this._renderId = 0;
  6449. this._executeWhenReadyTimeoutId = -1;
  6450. this._toBeDisposed = new BABYLON.SmartArray(256);
  6451. this._onReadyCallbacks = new Array();
  6452. this._pendingData = [];
  6453. this._onBeforeRenderCallbacks = new Array();
  6454. this._activeMeshes = new BABYLON.SmartArray(256);
  6455. this._processedMaterials = new BABYLON.SmartArray(256);
  6456. this._renderTargets = new BABYLON.SmartArray(256);
  6457. this._activeParticleSystems = new BABYLON.SmartArray(256);
  6458. this._activeSkeletons = new BABYLON.SmartArray(32);
  6459. this._activeAnimatables = new Array();
  6460. this._transformMatrix = BABYLON.Matrix.Zero();
  6461. this._scaledPosition = BABYLON.Vector3.Zero();
  6462. this._scaledVelocity = BABYLON.Vector3.Zero();
  6463. this._engine = engine;
  6464. engine.scenes.push(this);
  6465. this._renderingManager = new BABYLON.RenderingManager(this);
  6466. this.postProcessManager = new BABYLON.PostProcessManager(this);
  6467. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  6468. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  6469. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  6470. this.attachControl();
  6471. }
  6472. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  6473. get: function () {
  6474. return this._meshUnderPointer;
  6475. },
  6476. enumerable: true,
  6477. configurable: true
  6478. });
  6479. Object.defineProperty(Scene.prototype, "pointerX", {
  6480. get: function () {
  6481. return this._pointerX;
  6482. },
  6483. enumerable: true,
  6484. configurable: true
  6485. });
  6486. Object.defineProperty(Scene.prototype, "pointerY", {
  6487. get: function () {
  6488. return this._pointerY;
  6489. },
  6490. enumerable: true,
  6491. configurable: true
  6492. });
  6493. Scene.prototype.getBoundingBoxRenderer = function () {
  6494. return this._boundingBoxRenderer;
  6495. };
  6496. Scene.prototype.getOutlineRenderer = function () {
  6497. return this._outlineRenderer;
  6498. };
  6499. Scene.prototype.getEngine = function () {
  6500. return this._engine;
  6501. };
  6502. Scene.prototype.getTotalVertices = function () {
  6503. return this._totalVertices;
  6504. };
  6505. Scene.prototype.getActiveVertices = function () {
  6506. return this._activeVertices;
  6507. };
  6508. Scene.prototype.getActiveParticles = function () {
  6509. return this._activeParticles;
  6510. };
  6511. Scene.prototype.getLastFrameDuration = function () {
  6512. return this._lastFrameDuration;
  6513. };
  6514. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  6515. return this._evaluateActiveMeshesDuration;
  6516. };
  6517. Scene.prototype.getActiveMeshes = function () {
  6518. return this._activeMeshes;
  6519. };
  6520. Scene.prototype.getRenderTargetsDuration = function () {
  6521. return this._renderTargetsDuration;
  6522. };
  6523. Scene.prototype.getRenderDuration = function () {
  6524. return this._renderDuration;
  6525. };
  6526. Scene.prototype.getParticlesDuration = function () {
  6527. return this._particlesDuration;
  6528. };
  6529. Scene.prototype.getSpritesDuration = function () {
  6530. return this._spritesDuration;
  6531. };
  6532. Scene.prototype.getAnimationRatio = function () {
  6533. return this._animationRatio;
  6534. };
  6535. Scene.prototype.getRenderId = function () {
  6536. return this._renderId;
  6537. };
  6538. Scene.prototype._updatePointerPosition = function (evt) {
  6539. var canvasRect = this._engine.getRenderingCanvasClientRect();
  6540. this._pointerX = evt.clientX - canvasRect.left;
  6541. this._pointerY = evt.clientY - canvasRect.top;
  6542. if (this.cameraToUseForPointers) {
  6543. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  6544. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  6545. }
  6546. };
  6547. Scene.prototype.attachControl = function () {
  6548. var _this = this;
  6549. this._onPointerMove = function (evt) {
  6550. var canvas = _this._engine.getRenderingCanvas();
  6551. _this._updatePointerPosition(evt);
  6552. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  6553. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  6554. }, false, _this.cameraToUseForPointers);
  6555. if (pickResult.hit) {
  6556. _this._meshUnderPointer = pickResult.pickedMesh;
  6557. _this.setPointerOverMesh(pickResult.pickedMesh);
  6558. canvas.style.cursor = "pointer";
  6559. } else {
  6560. _this.setPointerOverMesh(null);
  6561. canvas.style.cursor = "";
  6562. _this._meshUnderPointer = null;
  6563. }
  6564. };
  6565. this._onPointerDown = function (evt) {
  6566. var predicate = null;
  6567. if (!_this.onPointerDown) {
  6568. predicate = function (mesh) {
  6569. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  6570. };
  6571. }
  6572. _this._updatePointerPosition(evt);
  6573. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  6574. if (pickResult.hit) {
  6575. if (pickResult.pickedMesh.actionManager) {
  6576. switch (evt.button) {
  6577. case 0:
  6578. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6579. break;
  6580. case 1:
  6581. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6582. break;
  6583. case 2:
  6584. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6585. break;
  6586. }
  6587. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6588. }
  6589. }
  6590. if (_this.onPointerDown) {
  6591. _this.onPointerDown(evt, pickResult);
  6592. }
  6593. };
  6594. this._onKeyDown = function (evt) {
  6595. if (_this.actionManager) {
  6596. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6597. }
  6598. };
  6599. this._onKeyUp = function (evt) {
  6600. if (_this.actionManager) {
  6601. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6602. }
  6603. };
  6604. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6605. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6606. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6607. window.addEventListener("keydown", this._onKeyDown, false);
  6608. window.addEventListener("keyup", this._onKeyUp, false);
  6609. };
  6610. Scene.prototype.detachControl = function () {
  6611. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6612. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  6613. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  6614. window.removeEventListener("keydown", this._onKeyDown);
  6615. window.removeEventListener("keyup", this._onKeyUp);
  6616. };
  6617. Scene.prototype.isReady = function () {
  6618. if (this._pendingData.length > 0) {
  6619. return false;
  6620. }
  6621. for (var index = 0; index < this._geometries.length; index++) {
  6622. var geometry = this._geometries[index];
  6623. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  6624. return false;
  6625. }
  6626. }
  6627. for (index = 0; index < this.meshes.length; index++) {
  6628. var mesh = this.meshes[index];
  6629. if (!mesh.isReady()) {
  6630. return false;
  6631. }
  6632. var mat = mesh.material;
  6633. if (mat) {
  6634. if (!mat.isReady(mesh)) {
  6635. return false;
  6636. }
  6637. }
  6638. }
  6639. return true;
  6640. };
  6641. Scene.prototype.registerBeforeRender = function (func) {
  6642. this._onBeforeRenderCallbacks.push(func);
  6643. };
  6644. Scene.prototype.unregisterBeforeRender = function (func) {
  6645. var index = this._onBeforeRenderCallbacks.indexOf(func);
  6646. if (index > -1) {
  6647. this._onBeforeRenderCallbacks.splice(index, 1);
  6648. }
  6649. };
  6650. Scene.prototype._addPendingData = function (data) {
  6651. this._pendingData.push(data);
  6652. };
  6653. Scene.prototype._removePendingData = function (data) {
  6654. var index = this._pendingData.indexOf(data);
  6655. if (index !== -1) {
  6656. this._pendingData.splice(index, 1);
  6657. }
  6658. };
  6659. Scene.prototype.getWaitingItemsCount = function () {
  6660. return this._pendingData.length;
  6661. };
  6662. Scene.prototype.executeWhenReady = function (func) {
  6663. var _this = this;
  6664. this._onReadyCallbacks.push(func);
  6665. if (this._executeWhenReadyTimeoutId !== -1) {
  6666. return;
  6667. }
  6668. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6669. _this._checkIsReady();
  6670. }, 150);
  6671. };
  6672. Scene.prototype._checkIsReady = function () {
  6673. var _this = this;
  6674. if (this.isReady()) {
  6675. this._onReadyCallbacks.forEach(function (func) {
  6676. func();
  6677. });
  6678. this._onReadyCallbacks = [];
  6679. this._executeWhenReadyTimeoutId = -1;
  6680. return;
  6681. }
  6682. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6683. _this._checkIsReady();
  6684. }, 150);
  6685. };
  6686. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  6687. if (speedRatio === undefined) {
  6688. speedRatio = 1.0;
  6689. }
  6690. this.stopAnimation(target);
  6691. if (!animatable) {
  6692. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  6693. }
  6694. if (target.animations) {
  6695. animatable.appendAnimations(target, target.animations);
  6696. }
  6697. if (target.getAnimatables) {
  6698. var animatables = target.getAnimatables();
  6699. for (var index = 0; index < animatables.length; index++) {
  6700. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  6701. }
  6702. }
  6703. return animatable;
  6704. };
  6705. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  6706. if (speedRatio === undefined) {
  6707. speedRatio = 1.0;
  6708. }
  6709. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  6710. return animatable;
  6711. };
  6712. Scene.prototype.getAnimatableByTarget = function (target) {
  6713. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6714. if (this._activeAnimatables[index].target === target) {
  6715. return this._activeAnimatables[index];
  6716. }
  6717. }
  6718. return null;
  6719. };
  6720. Scene.prototype.stopAnimation = function (target) {
  6721. var animatable = this.getAnimatableByTarget(target);
  6722. if (animatable) {
  6723. animatable.stop();
  6724. }
  6725. };
  6726. Scene.prototype._animate = function () {
  6727. if (!this._animationStartDate) {
  6728. this._animationStartDate = BABYLON.Tools.Now;
  6729. }
  6730. var now = BABYLON.Tools.Now;
  6731. var delay = now - this._animationStartDate;
  6732. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6733. if (!this._activeAnimatables[index]._animate(delay)) {
  6734. this._activeAnimatables.splice(index, 1);
  6735. index--;
  6736. }
  6737. }
  6738. };
  6739. Scene.prototype.getViewMatrix = function () {
  6740. return this._viewMatrix;
  6741. };
  6742. Scene.prototype.getProjectionMatrix = function () {
  6743. return this._projectionMatrix;
  6744. };
  6745. Scene.prototype.getTransformMatrix = function () {
  6746. return this._transformMatrix;
  6747. };
  6748. Scene.prototype.setTransformMatrix = function (view, projection) {
  6749. this._viewMatrix = view;
  6750. this._projectionMatrix = projection;
  6751. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6752. };
  6753. Scene.prototype.setActiveCameraByID = function (id) {
  6754. var camera = this.getCameraByID(id);
  6755. if (camera) {
  6756. this.activeCamera = camera;
  6757. return camera;
  6758. }
  6759. return null;
  6760. };
  6761. Scene.prototype.setActiveCameraByName = function (name) {
  6762. var camera = this.getCameraByName(name);
  6763. if (camera) {
  6764. this.activeCamera = camera;
  6765. return camera;
  6766. }
  6767. return null;
  6768. };
  6769. Scene.prototype.getMaterialByID = function (id) {
  6770. for (var index = 0; index < this.materials.length; index++) {
  6771. if (this.materials[index].id === id) {
  6772. return this.materials[index];
  6773. }
  6774. }
  6775. return null;
  6776. };
  6777. Scene.prototype.getMaterialByName = function (name) {
  6778. for (var index = 0; index < this.materials.length; index++) {
  6779. if (this.materials[index].name === name) {
  6780. return this.materials[index];
  6781. }
  6782. }
  6783. return null;
  6784. };
  6785. Scene.prototype.getCameraByID = function (id) {
  6786. for (var index = 0; index < this.cameras.length; index++) {
  6787. if (this.cameras[index].id === id) {
  6788. return this.cameras[index];
  6789. }
  6790. }
  6791. return null;
  6792. };
  6793. Scene.prototype.getCameraByName = function (name) {
  6794. for (var index = 0; index < this.cameras.length; index++) {
  6795. if (this.cameras[index].name === name) {
  6796. return this.cameras[index];
  6797. }
  6798. }
  6799. return null;
  6800. };
  6801. Scene.prototype.getLightByName = function (name) {
  6802. for (var index = 0; index < this.lights.length; index++) {
  6803. if (this.lights[index].name === name) {
  6804. return this.lights[index];
  6805. }
  6806. }
  6807. return null;
  6808. };
  6809. Scene.prototype.getLightByID = function (id) {
  6810. for (var index = 0; index < this.lights.length; index++) {
  6811. if (this.lights[index].id === id) {
  6812. return this.lights[index];
  6813. }
  6814. }
  6815. return null;
  6816. };
  6817. Scene.prototype.getGeometryByID = function (id) {
  6818. for (var index = 0; index < this._geometries.length; index++) {
  6819. if (this._geometries[index].id === id) {
  6820. return this._geometries[index];
  6821. }
  6822. }
  6823. return null;
  6824. };
  6825. Scene.prototype.pushGeometry = function (geometry, force) {
  6826. if (!force && this.getGeometryByID(geometry.id)) {
  6827. return false;
  6828. }
  6829. this._geometries.push(geometry);
  6830. return true;
  6831. };
  6832. Scene.prototype.getGeometries = function () {
  6833. return this._geometries;
  6834. };
  6835. Scene.prototype.getMeshByID = function (id) {
  6836. for (var index = 0; index < this.meshes.length; index++) {
  6837. if (this.meshes[index].id === id) {
  6838. return this.meshes[index];
  6839. }
  6840. }
  6841. return null;
  6842. };
  6843. Scene.prototype.getLastMeshByID = function (id) {
  6844. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6845. if (this.meshes[index].id === id) {
  6846. return this.meshes[index];
  6847. }
  6848. }
  6849. return null;
  6850. };
  6851. Scene.prototype.getLastEntryByID = function (id) {
  6852. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6853. if (this.meshes[index].id === id) {
  6854. return this.meshes[index];
  6855. }
  6856. }
  6857. for (index = this.cameras.length - 1; index >= 0; index--) {
  6858. if (this.cameras[index].id === id) {
  6859. return this.cameras[index];
  6860. }
  6861. }
  6862. for (index = this.lights.length - 1; index >= 0; index--) {
  6863. if (this.lights[index].id === id) {
  6864. return this.lights[index];
  6865. }
  6866. }
  6867. return null;
  6868. };
  6869. Scene.prototype.getMeshByName = function (name) {
  6870. for (var index = 0; index < this.meshes.length; index++) {
  6871. if (this.meshes[index].name === name) {
  6872. return this.meshes[index];
  6873. }
  6874. }
  6875. return null;
  6876. };
  6877. Scene.prototype.getLastSkeletonByID = function (id) {
  6878. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  6879. if (this.skeletons[index].id === id) {
  6880. return this.skeletons[index];
  6881. }
  6882. }
  6883. return null;
  6884. };
  6885. Scene.prototype.getSkeletonById = function (id) {
  6886. for (var index = 0; index < this.skeletons.length; index++) {
  6887. if (this.skeletons[index].id === id) {
  6888. return this.skeletons[index];
  6889. }
  6890. }
  6891. return null;
  6892. };
  6893. Scene.prototype.getSkeletonByName = function (name) {
  6894. for (var index = 0; index < this.skeletons.length; index++) {
  6895. if (this.skeletons[index].name === name) {
  6896. return this.skeletons[index];
  6897. }
  6898. }
  6899. return null;
  6900. };
  6901. Scene.prototype.isActiveMesh = function (mesh) {
  6902. return (this._activeMeshes.indexOf(mesh) !== -1);
  6903. };
  6904. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  6905. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  6906. var material = subMesh.getMaterial();
  6907. if (mesh.showSubMeshesBoundingBox) {
  6908. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  6909. }
  6910. if (material) {
  6911. if (material.getRenderTargetTextures) {
  6912. if (this._processedMaterials.indexOf(material) === -1) {
  6913. this._processedMaterials.push(material);
  6914. this._renderTargets.concat(material.getRenderTargetTextures());
  6915. }
  6916. }
  6917. this._activeVertices += subMesh.verticesCount;
  6918. this._renderingManager.dispatch(subMesh);
  6919. }
  6920. }
  6921. };
  6922. Scene.prototype._evaluateActiveMeshes = function () {
  6923. this._activeMeshes.reset();
  6924. this._renderingManager.reset();
  6925. this._processedMaterials.reset();
  6926. this._activeParticleSystems.reset();
  6927. this._activeSkeletons.reset();
  6928. this._boundingBoxRenderer.reset();
  6929. if (!this._frustumPlanes) {
  6930. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  6931. } else {
  6932. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  6933. }
  6934. var meshes;
  6935. var len;
  6936. if (this._selectionOctree) {
  6937. var selection = this._selectionOctree.select(this._frustumPlanes);
  6938. meshes = selection.data;
  6939. len = selection.length;
  6940. } else {
  6941. len = this.meshes.length;
  6942. meshes = this.meshes;
  6943. }
  6944. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  6945. var mesh = meshes[meshIndex];
  6946. this._totalVertices += mesh.getTotalVertices();
  6947. if (!mesh.isReady()) {
  6948. continue;
  6949. }
  6950. mesh.computeWorldMatrix();
  6951. mesh._preActivate();
  6952. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  6953. this._meshesForIntersections.pushNoDuplicate(mesh);
  6954. }
  6955. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) != 0) && mesh.isInFrustum(this._frustumPlanes)) {
  6956. this._activeMeshes.push(mesh);
  6957. mesh._activate(this._renderId);
  6958. this._activeMesh(mesh);
  6959. }
  6960. }
  6961. var beforeParticlesDate = BABYLON.Tools.Now;
  6962. if (this.particlesEnabled) {
  6963. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  6964. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  6965. var particleSystem = this.particleSystems[particleIndex];
  6966. if (!particleSystem.isStarted()) {
  6967. continue;
  6968. }
  6969. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  6970. this._activeParticleSystems.push(particleSystem);
  6971. particleSystem.animate();
  6972. }
  6973. }
  6974. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  6975. }
  6976. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  6977. };
  6978. Scene.prototype._activeMesh = function (mesh) {
  6979. if (mesh.skeleton) {
  6980. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  6981. }
  6982. if (mesh.showBoundingBox) {
  6983. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  6984. }
  6985. if (mesh.subMeshes) {
  6986. var len;
  6987. var subMeshes;
  6988. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  6989. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  6990. len = intersections.length;
  6991. subMeshes = intersections.data;
  6992. } else {
  6993. subMeshes = mesh.subMeshes;
  6994. len = subMeshes.length;
  6995. }
  6996. for (var subIndex = 0; subIndex < len; subIndex++) {
  6997. var subMesh = subMeshes[subIndex];
  6998. this._evaluateSubMesh(subMesh, mesh);
  6999. }
  7000. }
  7001. };
  7002. Scene.prototype.updateTransformMatrix = function (force) {
  7003. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  7004. };
  7005. Scene.prototype._renderForCamera = function (camera) {
  7006. var engine = this._engine;
  7007. this.activeCamera = camera;
  7008. if (!this.activeCamera)
  7009. throw new Error("Active camera not set");
  7010. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7011. engine.setViewport(this.activeCamera.viewport);
  7012. this._renderId++;
  7013. this.updateTransformMatrix();
  7014. if (this.beforeCameraRender) {
  7015. this.beforeCameraRender(this.activeCamera);
  7016. }
  7017. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  7018. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  7019. this._evaluateActiveMeshes();
  7020. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  7021. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  7022. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  7023. var skeleton = this._activeSkeletons.data[skeletonIndex];
  7024. skeleton.prepare();
  7025. }
  7026. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7027. if (this.renderTargetsEnabled) {
  7028. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7029. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  7030. var renderTarget = this._renderTargets.data[renderIndex];
  7031. if (renderTarget._shouldRender()) {
  7032. this._renderId++;
  7033. renderTarget.render();
  7034. }
  7035. }
  7036. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7037. this._renderId++;
  7038. }
  7039. if (this._renderTargets.length > 0) {
  7040. engine.restoreDefaultFramebuffer();
  7041. }
  7042. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7043. this.postProcessManager._prepareFrame();
  7044. var beforeRenderDate = BABYLON.Tools.Now;
  7045. if (this.layers.length) {
  7046. engine.setDepthBuffer(false);
  7047. var layerIndex;
  7048. var layer;
  7049. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7050. layer = this.layers[layerIndex];
  7051. if (layer.isBackground) {
  7052. layer.render();
  7053. }
  7054. }
  7055. engine.setDepthBuffer(true);
  7056. }
  7057. BABYLON.Tools.StartPerformanceCounter("Main render");
  7058. this._renderingManager.render(null, null, true, true);
  7059. BABYLON.Tools.EndPerformanceCounter("Main render");
  7060. this._boundingBoxRenderer.render();
  7061. if (this.lensFlaresEnabled) {
  7062. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7063. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  7064. this.lensFlareSystems[lensFlareSystemIndex].render();
  7065. }
  7066. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7067. }
  7068. if (this.layers.length) {
  7069. engine.setDepthBuffer(false);
  7070. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7071. layer = this.layers[layerIndex];
  7072. if (!layer.isBackground) {
  7073. layer.render();
  7074. }
  7075. }
  7076. engine.setDepthBuffer(true);
  7077. }
  7078. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  7079. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  7080. this.activeCamera._updateFromScene();
  7081. this._renderTargets.reset();
  7082. if (this.afterCameraRender) {
  7083. this.afterCameraRender(this.activeCamera);
  7084. }
  7085. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7086. };
  7087. Scene.prototype._processSubCameras = function (camera) {
  7088. if (camera.subCameras.length == 0) {
  7089. this._renderForCamera(camera);
  7090. return;
  7091. }
  7092. for (var index = 0; index < camera.subCameras.length; index++) {
  7093. this._renderForCamera(camera.subCameras[index]);
  7094. }
  7095. this.activeCamera = camera;
  7096. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  7097. this.activeCamera._updateFromScene();
  7098. };
  7099. Scene.prototype._checkIntersections = function () {
  7100. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  7101. var sourceMesh = this._meshesForIntersections.data[index];
  7102. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  7103. var action = sourceMesh.actionManager.actions[actionIndex];
  7104. if (action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7105. var otherMesh = action.getTriggerParameter();
  7106. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  7107. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7108. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  7109. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  7110. sourceMesh._intersectionsInProgress.push(otherMesh);
  7111. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7112. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  7113. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7114. if (indexOfOther > -1) {
  7115. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  7116. }
  7117. }
  7118. }
  7119. }
  7120. }
  7121. };
  7122. Scene.prototype.render = function () {
  7123. var startDate = BABYLON.Tools.Now;
  7124. this._particlesDuration = 0;
  7125. this._spritesDuration = 0;
  7126. this._activeParticles = 0;
  7127. this._renderDuration = 0;
  7128. this._evaluateActiveMeshesDuration = 0;
  7129. this._totalVertices = 0;
  7130. this._activeVertices = 0;
  7131. this._meshesForIntersections.reset();
  7132. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  7133. if (this.actionManager) {
  7134. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  7135. }
  7136. if (this.beforeRender) {
  7137. this.beforeRender();
  7138. }
  7139. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  7140. this._onBeforeRenderCallbacks[callbackIndex]();
  7141. }
  7142. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  7143. this._animationRatio = deltaTime * (60.0 / 1000.0);
  7144. this._animate();
  7145. if (this._physicsEngine) {
  7146. BABYLON.Tools.StartPerformanceCounter("Physics");
  7147. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  7148. BABYLON.Tools.EndPerformanceCounter("Physics");
  7149. }
  7150. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7151. var engine = this.getEngine();
  7152. if (this.renderTargetsEnabled) {
  7153. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7154. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  7155. var renderTarget = this.customRenderTargets[customIndex];
  7156. if (renderTarget._shouldRender()) {
  7157. this._renderId++;
  7158. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  7159. if (!this.activeCamera)
  7160. throw new Error("Active camera not set");
  7161. engine.setViewport(this.activeCamera.viewport);
  7162. this.updateTransformMatrix();
  7163. renderTarget.render();
  7164. }
  7165. }
  7166. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7167. this._renderId++;
  7168. }
  7169. if (this.customRenderTargets.length > 0) {
  7170. engine.restoreDefaultFramebuffer();
  7171. }
  7172. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7173. if (this.proceduralTexturesEnabled) {
  7174. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7175. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  7176. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  7177. if (proceduralTexture._shouldRender()) {
  7178. proceduralTexture.render();
  7179. }
  7180. }
  7181. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7182. }
  7183. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  7184. if (this.shadowsEnabled) {
  7185. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  7186. var light = this.lights[lightIndex];
  7187. var shadowGenerator = light.getShadowGenerator();
  7188. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  7189. this._renderTargets.push(shadowGenerator.getShadowMap());
  7190. }
  7191. }
  7192. }
  7193. this.postProcessRenderPipelineManager.update();
  7194. if (this.activeCameras.length > 0) {
  7195. var currentRenderId = this._renderId;
  7196. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  7197. this._renderId = currentRenderId;
  7198. this._processSubCameras(this.activeCameras[cameraIndex]);
  7199. }
  7200. } else {
  7201. if (!this.activeCamera) {
  7202. throw new Error("No camera defined");
  7203. }
  7204. this._processSubCameras(this.activeCamera);
  7205. }
  7206. this._checkIntersections();
  7207. if (this.afterRender) {
  7208. this.afterRender();
  7209. }
  7210. for (var index = 0; index < this._toBeDisposed.length; index++) {
  7211. this._toBeDisposed.data[index].dispose();
  7212. this._toBeDisposed[index] = null;
  7213. }
  7214. this._toBeDisposed.reset();
  7215. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  7216. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  7217. };
  7218. Scene.prototype.dispose = function () {
  7219. this.beforeRender = null;
  7220. this.afterRender = null;
  7221. this.skeletons = [];
  7222. this._boundingBoxRenderer.dispose();
  7223. if (this.onDispose) {
  7224. this.onDispose();
  7225. }
  7226. this.detachControl();
  7227. var canvas = this._engine.getRenderingCanvas();
  7228. var index;
  7229. for (index = 0; index < this.cameras.length; index++) {
  7230. this.cameras[index].detachControl(canvas);
  7231. }
  7232. while (this.lights.length) {
  7233. this.lights[0].dispose();
  7234. }
  7235. while (this.meshes.length) {
  7236. this.meshes[0].dispose(true);
  7237. }
  7238. while (this.cameras.length) {
  7239. this.cameras[0].dispose();
  7240. }
  7241. while (this.materials.length) {
  7242. this.materials[0].dispose();
  7243. }
  7244. while (this.particleSystems.length) {
  7245. this.particleSystems[0].dispose();
  7246. }
  7247. while (this.spriteManagers.length) {
  7248. this.spriteManagers[0].dispose();
  7249. }
  7250. while (this.layers.length) {
  7251. this.layers[0].dispose();
  7252. }
  7253. while (this.textures.length) {
  7254. this.textures[0].dispose();
  7255. }
  7256. this.postProcessManager.dispose();
  7257. if (this._physicsEngine) {
  7258. this.disablePhysicsEngine();
  7259. }
  7260. index = this._engine.scenes.indexOf(this);
  7261. if (index > -1) {
  7262. this._engine.scenes.splice(index, 1);
  7263. }
  7264. this._engine.wipeCaches();
  7265. };
  7266. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7267. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7268. position.divideToRef(collider.radius, this._scaledPosition);
  7269. velocity.divideToRef(collider.radius, this._scaledVelocity);
  7270. collider.retry = 0;
  7271. collider.initialVelocity = this._scaledVelocity;
  7272. collider.initialPosition = this._scaledPosition;
  7273. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  7274. finalPosition.multiplyInPlace(collider.radius);
  7275. };
  7276. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7277. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7278. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  7279. if (collider.retry >= maximumRetry) {
  7280. finalPosition.copyFrom(position);
  7281. return;
  7282. }
  7283. collider._initialize(position, velocity, closeDistance);
  7284. for (var index = 0; index < this.meshes.length; index++) {
  7285. var mesh = this.meshes[index];
  7286. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  7287. mesh._checkCollision(collider);
  7288. }
  7289. }
  7290. if (!collider.collisionFound) {
  7291. position.addToRef(velocity, finalPosition);
  7292. return;
  7293. }
  7294. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  7295. collider._getResponse(position, velocity);
  7296. }
  7297. if (velocity.length() <= closeDistance) {
  7298. finalPosition.copyFrom(position);
  7299. return;
  7300. }
  7301. collider.retry++;
  7302. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  7303. };
  7304. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  7305. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7306. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7307. if (!this._selectionOctree) {
  7308. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  7309. }
  7310. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7311. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7312. for (var index = 0; index < this.meshes.length; index++) {
  7313. var mesh = this.meshes[index];
  7314. mesh.computeWorldMatrix(true);
  7315. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  7316. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  7317. BABYLON.Tools.CheckExtends(minBox, min, max);
  7318. BABYLON.Tools.CheckExtends(maxBox, min, max);
  7319. }
  7320. this._selectionOctree.update(min, max, this.meshes);
  7321. return this._selectionOctree;
  7322. };
  7323. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  7324. var engine = this._engine;
  7325. if (!camera) {
  7326. if (!this.activeCamera)
  7327. throw new Error("Active camera not set");
  7328. camera = this.activeCamera;
  7329. }
  7330. var cameraViewport = camera.viewport;
  7331. var viewport = cameraViewport.toGlobal(engine);
  7332. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  7333. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  7334. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  7335. };
  7336. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  7337. var pickingInfo = null;
  7338. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  7339. var mesh = this.meshes[meshIndex];
  7340. if (predicate) {
  7341. if (!predicate(mesh)) {
  7342. continue;
  7343. }
  7344. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  7345. continue;
  7346. }
  7347. var world = mesh.getWorldMatrix();
  7348. var ray = rayFunction(world);
  7349. var result = mesh.intersects(ray, fastCheck);
  7350. if (!result || !result.hit)
  7351. continue;
  7352. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  7353. continue;
  7354. pickingInfo = result;
  7355. if (fastCheck) {
  7356. break;
  7357. }
  7358. }
  7359. return pickingInfo || new BABYLON.PickingInfo();
  7360. };
  7361. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  7362. var _this = this;
  7363. return this._internalPick(function (world) {
  7364. return _this.createPickingRay(x, y, world, camera);
  7365. }, predicate, fastCheck);
  7366. };
  7367. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  7368. var _this = this;
  7369. return this._internalPick(function (world) {
  7370. if (!_this._pickWithRayInverseMatrix) {
  7371. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  7372. }
  7373. world.invertToRef(_this._pickWithRayInverseMatrix);
  7374. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  7375. }, predicate, fastCheck);
  7376. };
  7377. Scene.prototype.setPointerOverMesh = function (mesh) {
  7378. if (this._pointerOverMesh === mesh) {
  7379. return;
  7380. }
  7381. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  7382. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  7383. }
  7384. this._pointerOverMesh = mesh;
  7385. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  7386. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  7387. }
  7388. };
  7389. Scene.prototype.getPointerOverMesh = function () {
  7390. return this._pointerOverMesh;
  7391. };
  7392. Scene.prototype.getPhysicsEngine = function () {
  7393. return this._physicsEngine;
  7394. };
  7395. Scene.prototype.enablePhysics = function (gravity, plugin) {
  7396. if (this._physicsEngine) {
  7397. return true;
  7398. }
  7399. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  7400. if (!this._physicsEngine.isSupported()) {
  7401. this._physicsEngine = null;
  7402. return false;
  7403. }
  7404. this._physicsEngine._initialize(gravity);
  7405. return true;
  7406. };
  7407. Scene.prototype.disablePhysicsEngine = function () {
  7408. if (!this._physicsEngine) {
  7409. return;
  7410. }
  7411. this._physicsEngine.dispose();
  7412. this._physicsEngine = undefined;
  7413. };
  7414. Scene.prototype.isPhysicsEnabled = function () {
  7415. return this._physicsEngine !== undefined;
  7416. };
  7417. Scene.prototype.setGravity = function (gravity) {
  7418. if (!this._physicsEngine) {
  7419. return;
  7420. }
  7421. this._physicsEngine._setGravity(gravity);
  7422. };
  7423. Scene.prototype.createCompoundImpostor = function (parts, options) {
  7424. if (parts.parts) {
  7425. options = parts;
  7426. parts = parts.parts;
  7427. }
  7428. if (!this._physicsEngine) {
  7429. return null;
  7430. }
  7431. for (var index = 0; index < parts.length; index++) {
  7432. var mesh = parts[index].mesh;
  7433. mesh._physicImpostor = parts[index].impostor;
  7434. mesh._physicsMass = options.mass / parts.length;
  7435. mesh._physicsFriction = options.friction;
  7436. mesh._physicRestitution = options.restitution;
  7437. }
  7438. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  7439. };
  7440. Scene.prototype.deleteCompoundImpostor = function (compound) {
  7441. for (var index = 0; index < compound.parts.length; index++) {
  7442. var mesh = compound.parts[index].mesh;
  7443. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7444. this._physicsEngine._unregisterMesh(mesh);
  7445. }
  7446. };
  7447. Scene.prototype._getByTags = function (list, tagsQuery) {
  7448. if (tagsQuery === undefined) {
  7449. return list;
  7450. }
  7451. var listByTags = [];
  7452. for (var i in list) {
  7453. var item = list[i];
  7454. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  7455. listByTags.push(item);
  7456. }
  7457. }
  7458. return listByTags;
  7459. };
  7460. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  7461. return this._getByTags(this.meshes, tagsQuery);
  7462. };
  7463. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  7464. return this._getByTags(this.cameras, tagsQuery);
  7465. };
  7466. Scene.prototype.getLightsByTags = function (tagsQuery) {
  7467. return this._getByTags(this.lights, tagsQuery);
  7468. };
  7469. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  7470. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  7471. };
  7472. Scene.FOGMODE_NONE = 0;
  7473. Scene.FOGMODE_EXP = 1;
  7474. Scene.FOGMODE_EXP2 = 2;
  7475. Scene.FOGMODE_LINEAR = 3;
  7476. Scene.MinDeltaTime = 1.0;
  7477. Scene.MaxDeltaTime = 1000.0;
  7478. return Scene;
  7479. })();
  7480. BABYLON.Scene = Scene;
  7481. })(BABYLON || (BABYLON = {}));
  7482. var BABYLON;
  7483. (function (BABYLON) {
  7484. var VertexBuffer = (function () {
  7485. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation) {
  7486. if (engine instanceof BABYLON.Mesh) {
  7487. this._engine = engine.getScene().getEngine();
  7488. } else {
  7489. this._engine = engine;
  7490. }
  7491. this._updatable = updatable;
  7492. this._data = data;
  7493. if (!postponeInternalCreation) {
  7494. this.create();
  7495. }
  7496. this._kind = kind;
  7497. switch (kind) {
  7498. case VertexBuffer.PositionKind:
  7499. this._strideSize = 3;
  7500. break;
  7501. case VertexBuffer.NormalKind:
  7502. this._strideSize = 3;
  7503. break;
  7504. case VertexBuffer.UVKind:
  7505. this._strideSize = 2;
  7506. break;
  7507. case VertexBuffer.UV2Kind:
  7508. this._strideSize = 2;
  7509. break;
  7510. case VertexBuffer.ColorKind:
  7511. this._strideSize = 3;
  7512. break;
  7513. case VertexBuffer.MatricesIndicesKind:
  7514. this._strideSize = 4;
  7515. break;
  7516. case VertexBuffer.MatricesWeightsKind:
  7517. this._strideSize = 4;
  7518. break;
  7519. }
  7520. }
  7521. VertexBuffer.prototype.isUpdatable = function () {
  7522. return this._updatable;
  7523. };
  7524. VertexBuffer.prototype.getData = function () {
  7525. return this._data;
  7526. };
  7527. VertexBuffer.prototype.getBuffer = function () {
  7528. return this._buffer;
  7529. };
  7530. VertexBuffer.prototype.getStrideSize = function () {
  7531. return this._strideSize;
  7532. };
  7533. VertexBuffer.prototype.create = function (data) {
  7534. if (!data && this._buffer) {
  7535. return;
  7536. }
  7537. data = data || this._data;
  7538. if (!this._buffer) {
  7539. if (this._updatable) {
  7540. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  7541. } else {
  7542. this._buffer = this._engine.createVertexBuffer(data);
  7543. }
  7544. }
  7545. if (this._updatable) {
  7546. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7547. this._data = data;
  7548. }
  7549. };
  7550. VertexBuffer.prototype.update = function (data) {
  7551. this.create(data);
  7552. };
  7553. VertexBuffer.prototype.updateDirectly = function (data) {
  7554. if (!this._buffer) {
  7555. return;
  7556. }
  7557. if (this._updatable) {
  7558. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7559. this._data = null;
  7560. }
  7561. };
  7562. VertexBuffer.prototype.dispose = function () {
  7563. if (!this._buffer) {
  7564. return;
  7565. }
  7566. if (this._engine._releaseBuffer(this._buffer)) {
  7567. this._buffer = null;
  7568. }
  7569. };
  7570. Object.defineProperty(VertexBuffer, "PositionKind", {
  7571. get: function () {
  7572. return VertexBuffer._PositionKind;
  7573. },
  7574. enumerable: true,
  7575. configurable: true
  7576. });
  7577. Object.defineProperty(VertexBuffer, "NormalKind", {
  7578. get: function () {
  7579. return VertexBuffer._NormalKind;
  7580. },
  7581. enumerable: true,
  7582. configurable: true
  7583. });
  7584. Object.defineProperty(VertexBuffer, "UVKind", {
  7585. get: function () {
  7586. return VertexBuffer._UVKind;
  7587. },
  7588. enumerable: true,
  7589. configurable: true
  7590. });
  7591. Object.defineProperty(VertexBuffer, "UV2Kind", {
  7592. get: function () {
  7593. return VertexBuffer._UV2Kind;
  7594. },
  7595. enumerable: true,
  7596. configurable: true
  7597. });
  7598. Object.defineProperty(VertexBuffer, "ColorKind", {
  7599. get: function () {
  7600. return VertexBuffer._ColorKind;
  7601. },
  7602. enumerable: true,
  7603. configurable: true
  7604. });
  7605. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  7606. get: function () {
  7607. return VertexBuffer._MatricesIndicesKind;
  7608. },
  7609. enumerable: true,
  7610. configurable: true
  7611. });
  7612. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  7613. get: function () {
  7614. return VertexBuffer._MatricesWeightsKind;
  7615. },
  7616. enumerable: true,
  7617. configurable: true
  7618. });
  7619. VertexBuffer._PositionKind = "position";
  7620. VertexBuffer._NormalKind = "normal";
  7621. VertexBuffer._UVKind = "uv";
  7622. VertexBuffer._UV2Kind = "uv2";
  7623. VertexBuffer._ColorKind = "color";
  7624. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  7625. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  7626. return VertexBuffer;
  7627. })();
  7628. BABYLON.VertexBuffer = VertexBuffer;
  7629. })(BABYLON || (BABYLON = {}));
  7630. var __extends = this.__extends || function (d, b) {
  7631. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7632. function __() { this.constructor = d; }
  7633. __.prototype = b.prototype;
  7634. d.prototype = new __();
  7635. };
  7636. var BABYLON;
  7637. (function (BABYLON) {
  7638. var AbstractMesh = (function (_super) {
  7639. __extends(AbstractMesh, _super);
  7640. function AbstractMesh(name, scene) {
  7641. _super.call(this, name, scene);
  7642. this.position = new BABYLON.Vector3(0, 0, 0);
  7643. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7644. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7645. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  7646. this.visibility = 1.0;
  7647. this.infiniteDistance = false;
  7648. this.isVisible = true;
  7649. this.isPickable = true;
  7650. this.showBoundingBox = false;
  7651. this.showSubMeshesBoundingBox = false;
  7652. this.onDispose = null;
  7653. this.checkCollisions = false;
  7654. this.isBlocker = false;
  7655. this.renderingGroupId = 0;
  7656. this.receiveShadows = false;
  7657. this.renderOutline = false;
  7658. this.outlineColor = BABYLON.Color3.Red();
  7659. this.outlineWidth = 0.02;
  7660. this.useOctreeForRenderingSelection = true;
  7661. this.useOctreeForPicking = true;
  7662. this.useOctreeForCollisions = true;
  7663. this.layerMask = 0xFFFFFFFF;
  7664. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7665. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7666. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7667. this._collider = new BABYLON.Collider();
  7668. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7669. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7670. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7671. this._localScaling = BABYLON.Matrix.Zero();
  7672. this._localRotation = BABYLON.Matrix.Zero();
  7673. this._localTranslation = BABYLON.Matrix.Zero();
  7674. this._localBillboard = BABYLON.Matrix.Zero();
  7675. this._localPivotScaling = BABYLON.Matrix.Zero();
  7676. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7677. this._localWorld = BABYLON.Matrix.Zero();
  7678. this._worldMatrix = BABYLON.Matrix.Zero();
  7679. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7680. this._absolutePosition = BABYLON.Vector3.Zero();
  7681. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7682. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7683. this._isDirty = false;
  7684. this._pivotMatrix = BABYLON.Matrix.Identity();
  7685. this._isDisposed = false;
  7686. this._renderId = 0;
  7687. this._intersectionsInProgress = new Array();
  7688. scene.meshes.push(this);
  7689. }
  7690. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7691. get: function () {
  7692. return AbstractMesh._BILLBOARDMODE_NONE;
  7693. },
  7694. enumerable: true,
  7695. configurable: true
  7696. });
  7697. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7698. get: function () {
  7699. return AbstractMesh._BILLBOARDMODE_X;
  7700. },
  7701. enumerable: true,
  7702. configurable: true
  7703. });
  7704. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7705. get: function () {
  7706. return AbstractMesh._BILLBOARDMODE_Y;
  7707. },
  7708. enumerable: true,
  7709. configurable: true
  7710. });
  7711. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7712. get: function () {
  7713. return AbstractMesh._BILLBOARDMODE_Z;
  7714. },
  7715. enumerable: true,
  7716. configurable: true
  7717. });
  7718. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7719. get: function () {
  7720. return AbstractMesh._BILLBOARDMODE_ALL;
  7721. },
  7722. enumerable: true,
  7723. configurable: true
  7724. });
  7725. AbstractMesh.prototype.getTotalVertices = function () {
  7726. return 0;
  7727. };
  7728. AbstractMesh.prototype.getIndices = function () {
  7729. return null;
  7730. };
  7731. AbstractMesh.prototype.getVerticesData = function (kind) {
  7732. return null;
  7733. };
  7734. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7735. return false;
  7736. };
  7737. AbstractMesh.prototype.getBoundingInfo = function () {
  7738. if (!this._boundingInfo) {
  7739. this._updateBoundingInfo();
  7740. }
  7741. return this._boundingInfo;
  7742. };
  7743. AbstractMesh.prototype._preActivate = function () {
  7744. };
  7745. AbstractMesh.prototype._activate = function (renderId) {
  7746. this._renderId = renderId;
  7747. };
  7748. AbstractMesh.prototype.getWorldMatrix = function () {
  7749. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7750. this.computeWorldMatrix();
  7751. }
  7752. return this._worldMatrix;
  7753. };
  7754. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7755. get: function () {
  7756. return this._worldMatrix;
  7757. },
  7758. enumerable: true,
  7759. configurable: true
  7760. });
  7761. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7762. get: function () {
  7763. return this._absolutePosition;
  7764. },
  7765. enumerable: true,
  7766. configurable: true
  7767. });
  7768. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7769. if (!this.rotationQuaternion) {
  7770. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7771. this.rotation = BABYLON.Vector3.Zero();
  7772. }
  7773. if (!space || space == 0 /* LOCAL */) {
  7774. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7775. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7776. } else {
  7777. if (this.parent) {
  7778. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7779. invertParentWorldMatrix.invert();
  7780. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7781. }
  7782. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7783. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7784. }
  7785. };
  7786. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7787. var displacementVector = axis.scale(distance);
  7788. if (!space || space == 0 /* LOCAL */) {
  7789. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7790. this.setPositionWithLocalVector(tempV3);
  7791. } else {
  7792. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7793. }
  7794. };
  7795. AbstractMesh.prototype.getAbsolutePosition = function () {
  7796. this.computeWorldMatrix();
  7797. return this._absolutePosition;
  7798. };
  7799. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7800. if (!absolutePosition) {
  7801. return;
  7802. }
  7803. var absolutePositionX;
  7804. var absolutePositionY;
  7805. var absolutePositionZ;
  7806. if (absolutePosition.x === undefined) {
  7807. if (arguments.length < 3) {
  7808. return;
  7809. }
  7810. absolutePositionX = arguments[0];
  7811. absolutePositionY = arguments[1];
  7812. absolutePositionZ = arguments[2];
  7813. } else {
  7814. absolutePositionX = absolutePosition.x;
  7815. absolutePositionY = absolutePosition.y;
  7816. absolutePositionZ = absolutePosition.z;
  7817. }
  7818. if (this.parent) {
  7819. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7820. invertParentWorldMatrix.invert();
  7821. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7822. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7823. } else {
  7824. this.position.x = absolutePositionX;
  7825. this.position.y = absolutePositionY;
  7826. this.position.z = absolutePositionZ;
  7827. }
  7828. };
  7829. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7830. this._pivotMatrix = matrix;
  7831. this._cache.pivotMatrixUpdated = true;
  7832. };
  7833. AbstractMesh.prototype.getPivotMatrix = function () {
  7834. return this._pivotMatrix;
  7835. };
  7836. AbstractMesh.prototype._isSynchronized = function () {
  7837. if (this._isDirty) {
  7838. return false;
  7839. }
  7840. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7841. return false;
  7842. if (this._cache.pivotMatrixUpdated) {
  7843. return false;
  7844. }
  7845. if (this.infiniteDistance) {
  7846. return false;
  7847. }
  7848. if (!this._cache.position.equals(this.position))
  7849. return false;
  7850. if (this.rotationQuaternion) {
  7851. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7852. return false;
  7853. } else {
  7854. if (!this._cache.rotation.equals(this.rotation))
  7855. return false;
  7856. }
  7857. if (!this._cache.scaling.equals(this.scaling))
  7858. return false;
  7859. return true;
  7860. };
  7861. AbstractMesh.prototype._initCache = function () {
  7862. _super.prototype._initCache.call(this);
  7863. this._cache.localMatrixUpdated = false;
  7864. this._cache.position = BABYLON.Vector3.Zero();
  7865. this._cache.scaling = BABYLON.Vector3.Zero();
  7866. this._cache.rotation = BABYLON.Vector3.Zero();
  7867. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7868. };
  7869. AbstractMesh.prototype.markAsDirty = function (property) {
  7870. if (property === "rotation") {
  7871. this.rotationQuaternion = null;
  7872. }
  7873. this._currentRenderId = Number.MAX_VALUE;
  7874. this._isDirty = true;
  7875. };
  7876. AbstractMesh.prototype._updateBoundingInfo = function () {
  7877. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7878. this._boundingInfo._update(this.worldMatrixFromCache);
  7879. if (!this.subMeshes) {
  7880. return;
  7881. }
  7882. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7883. var subMesh = this.subMeshes[subIndex];
  7884. subMesh.updateBoundingInfo(this.worldMatrixFromCache);
  7885. }
  7886. };
  7887. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7888. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  7889. return this._worldMatrix;
  7890. }
  7891. this._cache.position.copyFrom(this.position);
  7892. this._cache.scaling.copyFrom(this.scaling);
  7893. this._cache.pivotMatrixUpdated = false;
  7894. this._currentRenderId = this.getScene().getRenderId();
  7895. this._isDirty = false;
  7896. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7897. if (this.rotationQuaternion) {
  7898. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7899. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7900. } else {
  7901. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7902. this._cache.rotation.copyFrom(this.rotation);
  7903. }
  7904. if (this.infiniteDistance && !this.parent) {
  7905. var camera = this.getScene().activeCamera;
  7906. var cameraWorldMatrix = camera.getWorldMatrix();
  7907. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7908. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7909. } else {
  7910. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7911. }
  7912. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7913. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7914. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7915. var localPosition = this.position.clone();
  7916. var zero = this.getScene().activeCamera.position.clone();
  7917. if (this.parent && this.parent.position) {
  7918. localPosition.addInPlace(this.parent.position);
  7919. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7920. }
  7921. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  7922. zero = this.getScene().activeCamera.position;
  7923. } else {
  7924. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  7925. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7926. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  7927. zero.y = localPosition.y + 0.001;
  7928. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  7929. zero.z = localPosition.z + 0.001;
  7930. }
  7931. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7932. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7933. this._localBillboard.invert();
  7934. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7935. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7936. }
  7937. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7938. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  7939. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7940. } else {
  7941. this._worldMatrix.copyFrom(this._localWorld);
  7942. }
  7943. this._updateBoundingInfo();
  7944. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7945. return this._worldMatrix;
  7946. };
  7947. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7948. this.computeWorldMatrix();
  7949. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7950. };
  7951. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7952. this.computeWorldMatrix();
  7953. var invLocalWorldMatrix = this._localWorld.clone();
  7954. invLocalWorldMatrix.invert();
  7955. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7956. };
  7957. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7958. this.computeWorldMatrix();
  7959. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7960. };
  7961. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7962. yawCor = yawCor || 0;
  7963. pitchCor = pitchCor || 0;
  7964. rollCor = rollCor || 0;
  7965. var dv = targetPoint.subtract(this.position);
  7966. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7967. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7968. var pitch = Math.atan2(dv.y, len);
  7969. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7970. };
  7971. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7972. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  7973. return false;
  7974. }
  7975. return true;
  7976. };
  7977. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  7978. if (!camera) {
  7979. camera = this.getScene().activeCamera;
  7980. }
  7981. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  7982. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  7983. return false;
  7984. }
  7985. return true;
  7986. };
  7987. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7988. if (!this._boundingInfo || !mesh._boundingInfo) {
  7989. return false;
  7990. }
  7991. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7992. };
  7993. AbstractMesh.prototype.intersectsPoint = function (point) {
  7994. if (!this._boundingInfo) {
  7995. return false;
  7996. }
  7997. return this._boundingInfo.intersectsPoint(point);
  7998. };
  7999. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8000. var physicsEngine = this.getScene().getPhysicsEngine();
  8001. if (!physicsEngine) {
  8002. return;
  8003. }
  8004. if (impostor.impostor) {
  8005. options = impostor;
  8006. impostor = impostor.impostor;
  8007. }
  8008. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8009. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8010. physicsEngine._unregisterMesh(this);
  8011. return;
  8012. }
  8013. options.mass = options.mass || 0;
  8014. options.friction = options.friction || 0.2;
  8015. options.restitution = options.restitution || 0.2;
  8016. this._physicImpostor = impostor;
  8017. this._physicsMass = options.mass;
  8018. this._physicsFriction = options.friction;
  8019. this._physicRestitution = options.restitution;
  8020. physicsEngine._registerMesh(this, impostor, options);
  8021. };
  8022. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8023. if (!this._physicImpostor) {
  8024. return BABYLON.PhysicsEngine.NoImpostor;
  8025. }
  8026. return this._physicImpostor;
  8027. };
  8028. AbstractMesh.prototype.getPhysicsMass = function () {
  8029. if (!this._physicsMass) {
  8030. return 0;
  8031. }
  8032. return this._physicsMass;
  8033. };
  8034. AbstractMesh.prototype.getPhysicsFriction = function () {
  8035. if (!this._physicsFriction) {
  8036. return 0;
  8037. }
  8038. return this._physicsFriction;
  8039. };
  8040. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8041. if (!this._physicRestitution) {
  8042. return 0;
  8043. }
  8044. return this._physicRestitution;
  8045. };
  8046. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8047. if (!this._physicImpostor) {
  8048. return;
  8049. }
  8050. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8051. };
  8052. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8053. if (!this._physicImpostor) {
  8054. return;
  8055. }
  8056. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8057. };
  8058. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8059. if (!this._physicImpostor) {
  8060. return;
  8061. }
  8062. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8063. };
  8064. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8065. var globalPosition = this.getAbsolutePosition();
  8066. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8067. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8068. this._collider.radius = this.ellipsoid;
  8069. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  8070. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  8071. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8072. this.position.addInPlace(this._diffPositionForCollisions);
  8073. }
  8074. };
  8075. /**
  8076. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8077. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8078. */
  8079. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8080. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8081. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8082. if (!this._submeshesOctree) {
  8083. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8084. }
  8085. this.computeWorldMatrix(true);
  8086. var bbox = this.getBoundingInfo().boundingBox;
  8087. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8088. return this._submeshesOctree;
  8089. };
  8090. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8091. this._generatePointsArray();
  8092. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8093. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8094. subMesh._lastColliderWorldVertices = [];
  8095. subMesh._trianglePlanes = [];
  8096. var start = subMesh.verticesStart;
  8097. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8098. for (var i = start; i < end; i++) {
  8099. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8100. }
  8101. }
  8102. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  8103. };
  8104. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8105. var subMeshes;
  8106. var len;
  8107. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8108. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8109. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8110. len = intersections.length;
  8111. subMeshes = intersections.data;
  8112. } else {
  8113. subMeshes = this.subMeshes;
  8114. len = subMeshes.length;
  8115. }
  8116. for (var index = 0; index < len; index++) {
  8117. var subMesh = subMeshes[index];
  8118. if (len > 1 && !subMesh._checkCollision(collider))
  8119. continue;
  8120. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8121. }
  8122. };
  8123. AbstractMesh.prototype._checkCollision = function (collider) {
  8124. if (!this._boundingInfo._checkCollision(collider))
  8125. return;
  8126. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8127. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8128. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8129. };
  8130. AbstractMesh.prototype._generatePointsArray = function () {
  8131. return false;
  8132. };
  8133. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8134. var pickingInfo = new BABYLON.PickingInfo();
  8135. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8136. return pickingInfo;
  8137. }
  8138. if (!this._generatePointsArray()) {
  8139. return pickingInfo;
  8140. }
  8141. var intersectInfo = null;
  8142. var subMeshes;
  8143. var len;
  8144. if (this._submeshesOctree && this.useOctreeForPicking) {
  8145. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8146. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8147. len = intersections.length;
  8148. subMeshes = intersections.data;
  8149. } else {
  8150. subMeshes = this.subMeshes;
  8151. len = subMeshes.length;
  8152. }
  8153. for (var index = 0; index < len; index++) {
  8154. var subMesh = subMeshes[index];
  8155. if (len > 1 && !subMesh.canIntersects(ray))
  8156. continue;
  8157. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8158. if (currentIntersectInfo) {
  8159. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8160. intersectInfo = currentIntersectInfo;
  8161. if (fastCheck) {
  8162. break;
  8163. }
  8164. }
  8165. }
  8166. }
  8167. if (intersectInfo) {
  8168. var world = this.getWorldMatrix();
  8169. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8170. var direction = ray.direction.clone();
  8171. direction.normalize();
  8172. direction = direction.scale(intersectInfo.distance);
  8173. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8174. var pickedPoint = worldOrigin.add(worldDirection);
  8175. pickingInfo.hit = true;
  8176. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8177. pickingInfo.pickedPoint = pickedPoint;
  8178. pickingInfo.pickedMesh = this;
  8179. pickingInfo.bu = intersectInfo.bu;
  8180. pickingInfo.bv = intersectInfo.bv;
  8181. pickingInfo.faceId = intersectInfo.faceId;
  8182. return pickingInfo;
  8183. }
  8184. return pickingInfo;
  8185. };
  8186. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8187. return null;
  8188. };
  8189. AbstractMesh.prototype.releaseSubMeshes = function () {
  8190. if (this.subMeshes) {
  8191. while (this.subMeshes.length) {
  8192. this.subMeshes[0].dispose();
  8193. }
  8194. } else {
  8195. this.subMeshes = new Array();
  8196. }
  8197. };
  8198. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8199. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  8200. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8201. }
  8202. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8203. var other = this._intersectionsInProgress[index];
  8204. var pos = other._intersectionsInProgress.indexOf(this);
  8205. other._intersectionsInProgress.splice(pos, 1);
  8206. }
  8207. this._intersectionsInProgress = [];
  8208. this.releaseSubMeshes();
  8209. var index = this.getScene().meshes.indexOf(this);
  8210. if (index != -1) {
  8211. this.getScene().meshes.splice(index, 1);
  8212. }
  8213. if (!doNotRecurse) {
  8214. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8215. if (this.getScene().particleSystems[index].emitter == this) {
  8216. this.getScene().particleSystems[index].dispose();
  8217. index--;
  8218. }
  8219. }
  8220. var objects = this.getScene().meshes.slice(0);
  8221. for (index = 0; index < objects.length; index++) {
  8222. if (objects[index].parent == this) {
  8223. objects[index].dispose();
  8224. }
  8225. }
  8226. } else {
  8227. for (index = 0; index < this.getScene().meshes.length; index++) {
  8228. var obj = this.getScene().meshes[index];
  8229. if (obj.parent === this) {
  8230. obj.parent = null;
  8231. obj.computeWorldMatrix(true);
  8232. }
  8233. }
  8234. }
  8235. this._isDisposed = true;
  8236. if (this.onDispose) {
  8237. this.onDispose();
  8238. }
  8239. };
  8240. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8241. AbstractMesh._BILLBOARDMODE_X = 1;
  8242. AbstractMesh._BILLBOARDMODE_Y = 2;
  8243. AbstractMesh._BILLBOARDMODE_Z = 4;
  8244. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8245. return AbstractMesh;
  8246. })(BABYLON.Node);
  8247. BABYLON.AbstractMesh = AbstractMesh;
  8248. })(BABYLON || (BABYLON = {}));
  8249. var __extends = this.__extends || function (d, b) {
  8250. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8251. function __() { this.constructor = d; }
  8252. __.prototype = b.prototype;
  8253. d.prototype = new __();
  8254. };
  8255. var BABYLON;
  8256. (function (BABYLON) {
  8257. var _InstancesBatch = (function () {
  8258. function _InstancesBatch() {
  8259. this.mustReturn = false;
  8260. this.visibleInstances = new Array();
  8261. this.renderSelf = new Array();
  8262. }
  8263. return _InstancesBatch;
  8264. })();
  8265. BABYLON._InstancesBatch = _InstancesBatch;
  8266. var Mesh = (function (_super) {
  8267. __extends(Mesh, _super);
  8268. function Mesh(name, scene) {
  8269. _super.call(this, name, scene);
  8270. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  8271. this.instances = new Array();
  8272. this._onBeforeRenderCallbacks = new Array();
  8273. this._onAfterRenderCallbacks = new Array();
  8274. this._visibleInstances = {};
  8275. this._renderIdForInstances = new Array();
  8276. this._batchCache = new _InstancesBatch();
  8277. this._instancesBufferSize = 32 * 16 * 4;
  8278. }
  8279. Mesh.prototype.getTotalVertices = function () {
  8280. if (!this._geometry) {
  8281. return 0;
  8282. }
  8283. return this._geometry.getTotalVertices();
  8284. };
  8285. Mesh.prototype.getVerticesData = function (kind) {
  8286. if (!this._geometry) {
  8287. return null;
  8288. }
  8289. return this._geometry.getVerticesData(kind);
  8290. };
  8291. Mesh.prototype.getVertexBuffer = function (kind) {
  8292. if (!this._geometry) {
  8293. return undefined;
  8294. }
  8295. return this._geometry.getVertexBuffer(kind);
  8296. };
  8297. Mesh.prototype.isVerticesDataPresent = function (kind) {
  8298. if (!this._geometry) {
  8299. if (this._delayInfo) {
  8300. return this._delayInfo.indexOf(kind) !== -1;
  8301. }
  8302. return false;
  8303. }
  8304. return this._geometry.isVerticesDataPresent(kind);
  8305. };
  8306. Mesh.prototype.getVerticesDataKinds = function () {
  8307. if (!this._geometry) {
  8308. var result = [];
  8309. if (this._delayInfo) {
  8310. for (var kind in this._delayInfo) {
  8311. result.push(kind);
  8312. }
  8313. }
  8314. return result;
  8315. }
  8316. return this._geometry.getVerticesDataKinds();
  8317. };
  8318. Mesh.prototype.getTotalIndices = function () {
  8319. if (!this._geometry) {
  8320. return 0;
  8321. }
  8322. return this._geometry.getTotalIndices();
  8323. };
  8324. Mesh.prototype.getIndices = function () {
  8325. if (!this._geometry) {
  8326. return [];
  8327. }
  8328. return this._geometry.getIndices();
  8329. };
  8330. Mesh.prototype.isReady = function () {
  8331. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8332. return false;
  8333. }
  8334. return _super.prototype.isReady.call(this);
  8335. };
  8336. Mesh.prototype.isDisposed = function () {
  8337. return this._isDisposed;
  8338. };
  8339. Mesh.prototype._preActivate = function () {
  8340. var sceneRenderId = this.getScene().getRenderId();
  8341. if (this._preActivateId == sceneRenderId) {
  8342. return;
  8343. }
  8344. this._preActivateId = sceneRenderId;
  8345. this._visibleInstances = null;
  8346. };
  8347. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  8348. if (!this._visibleInstances) {
  8349. this._visibleInstances = {};
  8350. this._visibleInstances.defaultRenderId = renderId;
  8351. this._visibleInstances.selfDefaultRenderId = this._renderId;
  8352. }
  8353. if (!this._visibleInstances[renderId]) {
  8354. this._visibleInstances[renderId] = new Array();
  8355. }
  8356. this._visibleInstances[renderId].push(instance);
  8357. };
  8358. Mesh.prototype.refreshBoundingInfo = function () {
  8359. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8360. if (data) {
  8361. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  8362. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8363. }
  8364. if (this.subMeshes) {
  8365. for (var index = 0; index < this.subMeshes.length; index++) {
  8366. this.subMeshes[index].refreshBoundingInfo();
  8367. }
  8368. }
  8369. this._updateBoundingInfo();
  8370. };
  8371. Mesh.prototype._createGlobalSubMesh = function () {
  8372. var totalVertices = this.getTotalVertices();
  8373. if (!totalVertices || !this.getIndices()) {
  8374. return null;
  8375. }
  8376. this.releaseSubMeshes();
  8377. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  8378. };
  8379. Mesh.prototype.subdivide = function (count) {
  8380. if (count < 1) {
  8381. return;
  8382. }
  8383. var totalIndices = this.getTotalIndices();
  8384. var subdivisionSize = (totalIndices / count) | 0;
  8385. var offset = 0;
  8386. while (subdivisionSize % 3 != 0) {
  8387. subdivisionSize++;
  8388. }
  8389. this.releaseSubMeshes();
  8390. for (var index = 0; index < count; index++) {
  8391. if (offset >= totalIndices) {
  8392. break;
  8393. }
  8394. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  8395. offset += subdivisionSize;
  8396. }
  8397. this.synchronizeInstances();
  8398. };
  8399. Mesh.prototype.setVerticesData = function (kind, data, updatable) {
  8400. if (kind instanceof Array) {
  8401. var temp = data;
  8402. data = kind;
  8403. kind = temp;
  8404. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  8405. }
  8406. if (!this._geometry) {
  8407. var vertexData = new BABYLON.VertexData();
  8408. vertexData.set(data, kind);
  8409. var scene = this.getScene();
  8410. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  8411. } else {
  8412. this._geometry.setVerticesData(kind, data, updatable);
  8413. }
  8414. };
  8415. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  8416. if (!this._geometry) {
  8417. return;
  8418. }
  8419. if (!makeItUnique) {
  8420. this._geometry.updateVerticesData(kind, data, updateExtends);
  8421. } else {
  8422. this.makeGeometryUnique();
  8423. this.updateVerticesData(kind, data, updateExtends, false);
  8424. }
  8425. };
  8426. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, makeItUnique) {
  8427. if (!this._geometry) {
  8428. return;
  8429. }
  8430. if (!makeItUnique) {
  8431. this._geometry.updateVerticesDataDirectly(kind, data);
  8432. } else {
  8433. this.makeGeometryUnique();
  8434. this.updateVerticesDataDirectly(kind, data, false);
  8435. }
  8436. };
  8437. Mesh.prototype.makeGeometryUnique = function () {
  8438. if (!this._geometry) {
  8439. return;
  8440. }
  8441. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  8442. geometry.applyToMesh(this);
  8443. };
  8444. Mesh.prototype.setIndices = function (indices) {
  8445. if (!this._geometry) {
  8446. var vertexData = new BABYLON.VertexData();
  8447. vertexData.indices = indices;
  8448. var scene = this.getScene();
  8449. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  8450. } else {
  8451. this._geometry.setIndices(indices);
  8452. }
  8453. };
  8454. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  8455. var engine = this.getScene().getEngine();
  8456. var indexToBind;
  8457. switch (fillMode) {
  8458. case BABYLON.Material.TriangleFillMode:
  8459. indexToBind = this._geometry.getIndexBuffer();
  8460. break;
  8461. case BABYLON.Material.WireFrameFillMode:
  8462. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  8463. break;
  8464. default:
  8465. indexToBind = null;
  8466. break;
  8467. }
  8468. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  8469. };
  8470. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  8471. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8472. return;
  8473. }
  8474. var engine = this.getScene().getEngine();
  8475. switch (fillMode) {
  8476. case BABYLON.Material.PointFillMode:
  8477. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  8478. break;
  8479. case BABYLON.Material.WireFrameFillMode:
  8480. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  8481. break;
  8482. default:
  8483. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  8484. }
  8485. };
  8486. Mesh.prototype.registerBeforeRender = function (func) {
  8487. this._onBeforeRenderCallbacks.push(func);
  8488. };
  8489. Mesh.prototype.unregisterBeforeRender = function (func) {
  8490. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8491. if (index > -1) {
  8492. this._onBeforeRenderCallbacks.splice(index, 1);
  8493. }
  8494. };
  8495. Mesh.prototype.registerAfterRender = function (func) {
  8496. this._onAfterRenderCallbacks.push(func);
  8497. };
  8498. Mesh.prototype.unregisterAfterRender = function (func) {
  8499. var index = this._onAfterRenderCallbacks.indexOf(func);
  8500. if (index > -1) {
  8501. this._onAfterRenderCallbacks.splice(index, 1);
  8502. }
  8503. };
  8504. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  8505. var scene = this.getScene();
  8506. this._batchCache.mustReturn = false;
  8507. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  8508. this._batchCache.visibleInstances[subMeshId] = null;
  8509. if (this._visibleInstances) {
  8510. var currentRenderId = scene.getRenderId();
  8511. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  8512. var selfRenderId = this._renderId;
  8513. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  8514. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  8515. currentRenderId = this._visibleInstances.defaultRenderId;
  8516. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  8517. }
  8518. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  8519. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  8520. this._batchCache.mustReturn = true;
  8521. return this._batchCache;
  8522. }
  8523. if (currentRenderId !== selfRenderId) {
  8524. this._batchCache.renderSelf[subMeshId] = false;
  8525. }
  8526. }
  8527. this._renderIdForInstances[subMeshId] = currentRenderId;
  8528. }
  8529. return this._batchCache;
  8530. };
  8531. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  8532. var matricesCount = this.instances.length + 1;
  8533. var bufferSize = matricesCount * 16 * 4;
  8534. while (this._instancesBufferSize < bufferSize) {
  8535. this._instancesBufferSize *= 2;
  8536. }
  8537. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  8538. if (this._worldMatricesInstancesBuffer) {
  8539. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8540. }
  8541. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  8542. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  8543. }
  8544. var offset = 0;
  8545. var instancesCount = 0;
  8546. var world = this.getWorldMatrix();
  8547. if (batch.renderSelf[subMesh._id]) {
  8548. world.copyToArray(this._worldMatricesInstancesArray, offset);
  8549. offset += 16;
  8550. instancesCount++;
  8551. }
  8552. var visibleInstances = batch.visibleInstances[subMesh._id];
  8553. if (visibleInstances) {
  8554. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  8555. var instance = visibleInstances[instanceIndex];
  8556. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  8557. offset += 16;
  8558. instancesCount++;
  8559. }
  8560. }
  8561. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  8562. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  8563. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  8564. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  8565. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  8566. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  8567. this._draw(subMesh, fillMode, instancesCount);
  8568. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  8569. };
  8570. Mesh.prototype.render = function (subMesh) {
  8571. var scene = this.getScene();
  8572. var batch = this._getInstancesRenderList(subMesh._id);
  8573. if (batch.mustReturn) {
  8574. return;
  8575. }
  8576. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8577. return;
  8578. }
  8579. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8580. this._onBeforeRenderCallbacks[callbackIndex]();
  8581. }
  8582. var engine = scene.getEngine();
  8583. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8584. var effectiveMaterial = subMesh.getMaterial();
  8585. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  8586. return;
  8587. }
  8588. var savedDepthWrite = engine.getDepthWrite();
  8589. if (this.renderOutline) {
  8590. engine.setDepthWrite(false);
  8591. scene.getOutlineRenderer().render(subMesh, batch);
  8592. }
  8593. effectiveMaterial._preBind();
  8594. var effect = effectiveMaterial.getEffect();
  8595. var fillMode = engine.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode;
  8596. this._bind(subMesh, effect, fillMode);
  8597. var world = this.getWorldMatrix();
  8598. effectiveMaterial.bind(world, this);
  8599. if (hardwareInstancedRendering) {
  8600. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  8601. } else {
  8602. if (batch.renderSelf[subMesh._id]) {
  8603. this._draw(subMesh, fillMode);
  8604. }
  8605. if (batch.visibleInstances[subMesh._id]) {
  8606. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  8607. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  8608. world = instance.getWorldMatrix();
  8609. effectiveMaterial.bindOnlyWorldMatrix(world);
  8610. this._draw(subMesh, fillMode);
  8611. }
  8612. }
  8613. }
  8614. effectiveMaterial.unbind();
  8615. if (this.renderOutline && savedDepthWrite) {
  8616. engine.setDepthWrite(true);
  8617. engine.setColorWrite(false);
  8618. scene.getOutlineRenderer().render(subMesh, batch);
  8619. engine.setColorWrite(true);
  8620. }
  8621. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8622. this._onAfterRenderCallbacks[callbackIndex]();
  8623. }
  8624. };
  8625. Mesh.prototype.getEmittedParticleSystems = function () {
  8626. var results = new Array();
  8627. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8628. var particleSystem = this.getScene().particleSystems[index];
  8629. if (particleSystem.emitter === this) {
  8630. results.push(particleSystem);
  8631. }
  8632. }
  8633. return results;
  8634. };
  8635. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  8636. var results = new Array();
  8637. var descendants = this.getDescendants();
  8638. descendants.push(this);
  8639. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8640. var particleSystem = this.getScene().particleSystems[index];
  8641. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  8642. results.push(particleSystem);
  8643. }
  8644. }
  8645. return results;
  8646. };
  8647. Mesh.prototype.getChildren = function () {
  8648. var results = [];
  8649. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8650. var mesh = this.getScene().meshes[index];
  8651. if (mesh.parent == this) {
  8652. results.push(mesh);
  8653. }
  8654. }
  8655. return results;
  8656. };
  8657. Mesh.prototype._checkDelayState = function () {
  8658. var _this = this;
  8659. var that = this;
  8660. var scene = this.getScene();
  8661. if (this._geometry) {
  8662. this._geometry.load(scene);
  8663. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8664. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  8665. scene._addPendingData(that);
  8666. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  8667. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  8668. if (data instanceof ArrayBuffer) {
  8669. _this._delayLoadingFunction(data, _this);
  8670. } else {
  8671. _this._delayLoadingFunction(JSON.parse(data), _this);
  8672. }
  8673. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  8674. scene._removePendingData(_this);
  8675. }, function () {
  8676. }, scene.database, getBinaryData);
  8677. }
  8678. };
  8679. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  8680. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8681. return false;
  8682. }
  8683. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  8684. return false;
  8685. }
  8686. this._checkDelayState();
  8687. return true;
  8688. };
  8689. Mesh.prototype.setMaterialByID = function (id) {
  8690. var materials = this.getScene().materials;
  8691. for (var index = 0; index < materials.length; index++) {
  8692. if (materials[index].id == id) {
  8693. this.material = materials[index];
  8694. return;
  8695. }
  8696. }
  8697. var multiMaterials = this.getScene().multiMaterials;
  8698. for (index = 0; index < multiMaterials.length; index++) {
  8699. if (multiMaterials[index].id == id) {
  8700. this.material = multiMaterials[index];
  8701. return;
  8702. }
  8703. }
  8704. };
  8705. Mesh.prototype.getAnimatables = function () {
  8706. var results = [];
  8707. if (this.material) {
  8708. results.push(this.material);
  8709. }
  8710. if (this.skeleton) {
  8711. results.push(this.skeleton);
  8712. }
  8713. return results;
  8714. };
  8715. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  8716. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  8717. return;
  8718. }
  8719. this._resetPointsArrayCache();
  8720. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8721. var temp = [];
  8722. for (var index = 0; index < data.length; index += 3) {
  8723. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8724. }
  8725. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  8726. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8727. return;
  8728. }
  8729. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8730. for (index = 0; index < data.length; index += 3) {
  8731. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8732. }
  8733. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  8734. };
  8735. Mesh.prototype._resetPointsArrayCache = function () {
  8736. this._positions = null;
  8737. };
  8738. Mesh.prototype._generatePointsArray = function () {
  8739. if (this._positions)
  8740. return true;
  8741. this._positions = [];
  8742. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8743. if (!data) {
  8744. return false;
  8745. }
  8746. for (var index = 0; index < data.length; index += 3) {
  8747. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  8748. }
  8749. return true;
  8750. };
  8751. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8752. var result = new BABYLON.Mesh(name, this.getScene());
  8753. this._geometry.applyToMesh(result);
  8754. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  8755. result.material = this.material;
  8756. if (newParent) {
  8757. result.parent = newParent;
  8758. }
  8759. if (!doNotCloneChildren) {
  8760. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8761. var mesh = this.getScene().meshes[index];
  8762. if (mesh.parent == this) {
  8763. mesh.clone(mesh.name, result);
  8764. }
  8765. }
  8766. }
  8767. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8768. var system = this.getScene().particleSystems[index];
  8769. if (system.emitter == this) {
  8770. system.clone(system.name, result);
  8771. }
  8772. }
  8773. result.computeWorldMatrix(true);
  8774. return result;
  8775. };
  8776. Mesh.prototype.dispose = function (doNotRecurse) {
  8777. if (this._geometry) {
  8778. this._geometry.releaseForMesh(this, true);
  8779. }
  8780. if (this._worldMatricesInstancesBuffer) {
  8781. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8782. this._worldMatricesInstancesBuffer = null;
  8783. }
  8784. while (this.instances.length) {
  8785. this.instances[0].dispose();
  8786. }
  8787. _super.prototype.dispose.call(this, doNotRecurse);
  8788. };
  8789. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  8790. var _this = this;
  8791. var scene = this.getScene();
  8792. var onload = function (img) {
  8793. var canvas = document.createElement("canvas");
  8794. var context = canvas.getContext("2d");
  8795. var heightMapWidth = img.width;
  8796. var heightMapHeight = img.height;
  8797. canvas.width = heightMapWidth;
  8798. canvas.height = heightMapHeight;
  8799. context.drawImage(img, 0, 0);
  8800. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8801. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  8802. };
  8803. BABYLON.Tools.LoadImage(url, onload, function () {
  8804. }, scene.database);
  8805. };
  8806. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  8807. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8808. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  8809. return;
  8810. }
  8811. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8812. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8813. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8814. var position = BABYLON.Vector3.Zero();
  8815. var normal = BABYLON.Vector3.Zero();
  8816. var uv = BABYLON.Vector2.Zero();
  8817. for (var index = 0; index < positions.length; index += 3) {
  8818. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  8819. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  8820. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  8821. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  8822. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  8823. var pos = (u + v * heightMapWidth) * 4;
  8824. var r = buffer[pos] / 255.0;
  8825. var g = buffer[pos + 1] / 255.0;
  8826. var b = buffer[pos + 2] / 255.0;
  8827. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  8828. normal.normalize();
  8829. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  8830. position = position.add(normal);
  8831. position.toArray(positions, index);
  8832. }
  8833. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  8834. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  8835. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  8836. };
  8837. Mesh.prototype.convertToFlatShadedMesh = function () {
  8838. var kinds = this.getVerticesDataKinds();
  8839. var vbs = [];
  8840. var data = [];
  8841. var newdata = [];
  8842. var updatableNormals = false;
  8843. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8844. var kind = kinds[kindIndex];
  8845. var vertexBuffer = this.getVertexBuffer(kind);
  8846. if (kind === BABYLON.VertexBuffer.NormalKind) {
  8847. updatableNormals = vertexBuffer.isUpdatable();
  8848. kinds.splice(kindIndex, 1);
  8849. kindIndex--;
  8850. continue;
  8851. }
  8852. vbs[kind] = vertexBuffer;
  8853. data[kind] = vbs[kind].getData();
  8854. newdata[kind] = [];
  8855. }
  8856. var previousSubmeshes = this.subMeshes.slice(0);
  8857. var indices = this.getIndices();
  8858. var totalIndices = this.getTotalIndices();
  8859. for (index = 0; index < totalIndices; index++) {
  8860. var vertexIndex = indices[index];
  8861. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8862. kind = kinds[kindIndex];
  8863. var stride = vbs[kind].getStrideSize();
  8864. for (var offset = 0; offset < stride; offset++) {
  8865. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  8866. }
  8867. }
  8868. }
  8869. var normals = [];
  8870. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  8871. for (var index = 0; index < totalIndices; index += 3) {
  8872. indices[index] = index;
  8873. indices[index + 1] = index + 1;
  8874. indices[index + 2] = index + 2;
  8875. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  8876. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  8877. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  8878. var p1p2 = p1.subtract(p2);
  8879. var p3p2 = p3.subtract(p2);
  8880. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  8881. for (var localIndex = 0; localIndex < 3; localIndex++) {
  8882. normals.push(normal.x);
  8883. normals.push(normal.y);
  8884. normals.push(normal.z);
  8885. }
  8886. }
  8887. this.setIndices(indices);
  8888. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  8889. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8890. kind = kinds[kindIndex];
  8891. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  8892. }
  8893. this.releaseSubMeshes();
  8894. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  8895. var previousOne = previousSubmeshes[submeshIndex];
  8896. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  8897. }
  8898. this.synchronizeInstances();
  8899. };
  8900. Mesh.prototype.createInstance = function (name) {
  8901. return new BABYLON.InstancedMesh(name, this);
  8902. };
  8903. Mesh.prototype.synchronizeInstances = function () {
  8904. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  8905. var instance = this.instances[instanceIndex];
  8906. instance._syncSubMeshes();
  8907. }
  8908. };
  8909. Mesh.CreateBox = function (name, size, scene, updatable) {
  8910. var box = new BABYLON.Mesh(name, scene);
  8911. var vertexData = BABYLON.VertexData.CreateBox(size);
  8912. vertexData.applyToMesh(box, updatable);
  8913. return box;
  8914. };
  8915. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  8916. var sphere = new BABYLON.Mesh(name, scene);
  8917. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  8918. vertexData.applyToMesh(sphere, updatable);
  8919. return sphere;
  8920. };
  8921. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  8922. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  8923. if (scene !== undefined) {
  8924. updatable = scene;
  8925. }
  8926. scene = subdivisions;
  8927. subdivisions = 1;
  8928. }
  8929. var cylinder = new BABYLON.Mesh(name, scene);
  8930. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  8931. vertexData.applyToMesh(cylinder, updatable);
  8932. return cylinder;
  8933. };
  8934. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  8935. var torus = new BABYLON.Mesh(name, scene);
  8936. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  8937. vertexData.applyToMesh(torus, updatable);
  8938. return torus;
  8939. };
  8940. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  8941. var torusKnot = new BABYLON.Mesh(name, scene);
  8942. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  8943. vertexData.applyToMesh(torusKnot, updatable);
  8944. return torusKnot;
  8945. };
  8946. Mesh.CreateLines = function (name, points, scene, updatable) {
  8947. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  8948. var vertexData = BABYLON.VertexData.CreateLines(points);
  8949. vertexData.applyToMesh(lines, updatable);
  8950. return lines;
  8951. };
  8952. Mesh.CreatePlane = function (name, size, scene, updatable) {
  8953. var plane = new BABYLON.Mesh(name, scene);
  8954. var vertexData = BABYLON.VertexData.CreatePlane(size);
  8955. vertexData.applyToMesh(plane, updatable);
  8956. return plane;
  8957. };
  8958. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  8959. var ground = new BABYLON.GroundMesh(name, scene);
  8960. ground._setReady(false);
  8961. ground._subdivisions = subdivisions;
  8962. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  8963. vertexData.applyToMesh(ground, updatable);
  8964. ground._setReady(true);
  8965. return ground;
  8966. };
  8967. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  8968. var tiledGround = new BABYLON.Mesh(name, scene);
  8969. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  8970. vertexData.applyToMesh(tiledGround, updatable);
  8971. return tiledGround;
  8972. };
  8973. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  8974. var ground = new BABYLON.GroundMesh(name, scene);
  8975. ground._subdivisions = subdivisions;
  8976. ground._setReady(false);
  8977. var onload = function (img) {
  8978. var canvas = document.createElement("canvas");
  8979. var context = canvas.getContext("2d");
  8980. var heightMapWidth = img.width;
  8981. var heightMapHeight = img.height;
  8982. canvas.width = heightMapWidth;
  8983. canvas.height = heightMapHeight;
  8984. context.drawImage(img, 0, 0);
  8985. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8986. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  8987. vertexData.applyToMesh(ground, updatable);
  8988. ground._setReady(true);
  8989. };
  8990. BABYLON.Tools.LoadImage(url, onload, function () {
  8991. }, scene.database);
  8992. return ground;
  8993. };
  8994. Mesh.MinMax = function (meshes) {
  8995. var minVector = null;
  8996. var maxVector = null;
  8997. for (var i in meshes) {
  8998. var mesh = meshes[i];
  8999. var boundingBox = mesh.getBoundingInfo().boundingBox;
  9000. if (!minVector) {
  9001. minVector = boundingBox.minimumWorld;
  9002. maxVector = boundingBox.maximumWorld;
  9003. continue;
  9004. }
  9005. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  9006. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  9007. }
  9008. return {
  9009. min: minVector,
  9010. max: maxVector
  9011. };
  9012. };
  9013. Mesh.Center = function (meshesOrMinMaxVector) {
  9014. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  9015. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  9016. };
  9017. return Mesh;
  9018. })(BABYLON.AbstractMesh);
  9019. BABYLON.Mesh = Mesh;
  9020. })(BABYLON || (BABYLON = {}));
  9021. var __extends = this.__extends || function (d, b) {
  9022. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9023. function __() { this.constructor = d; }
  9024. __.prototype = b.prototype;
  9025. d.prototype = new __();
  9026. };
  9027. var BABYLON;
  9028. (function (BABYLON) {
  9029. var GroundMesh = (function (_super) {
  9030. __extends(GroundMesh, _super);
  9031. function GroundMesh(name, scene) {
  9032. _super.call(this, name, scene);
  9033. this.generateOctree = false;
  9034. this._worldInverse = new BABYLON.Matrix();
  9035. }
  9036. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  9037. get: function () {
  9038. return this._subdivisions;
  9039. },
  9040. enumerable: true,
  9041. configurable: true
  9042. });
  9043. GroundMesh.prototype.optimize = function (chunksCount) {
  9044. this.subdivide(this._subdivisions);
  9045. this.createOrUpdateSubmeshesOctree(32);
  9046. };
  9047. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  9048. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  9049. this.getWorldMatrix().invertToRef(this._worldInverse);
  9050. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  9051. var pickInfo = this.intersects(ray);
  9052. if (pickInfo.hit) {
  9053. return pickInfo.pickedPoint.y;
  9054. }
  9055. return 0;
  9056. };
  9057. return GroundMesh;
  9058. })(BABYLON.Mesh);
  9059. BABYLON.GroundMesh = GroundMesh;
  9060. })(BABYLON || (BABYLON = {}));
  9061. var __extends = this.__extends || function (d, b) {
  9062. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9063. function __() { this.constructor = d; }
  9064. __.prototype = b.prototype;
  9065. d.prototype = new __();
  9066. };
  9067. var BABYLON;
  9068. (function (BABYLON) {
  9069. var InstancedMesh = (function (_super) {
  9070. __extends(InstancedMesh, _super);
  9071. function InstancedMesh(name, source) {
  9072. _super.call(this, name, source.getScene());
  9073. source.instances.push(this);
  9074. this._sourceMesh = source;
  9075. this.position.copyFrom(source.position);
  9076. this.rotation.copyFrom(source.rotation);
  9077. this.scaling.copyFrom(source.scaling);
  9078. if (source.rotationQuaternion) {
  9079. this.rotationQuaternion = source.rotationQuaternion.clone();
  9080. }
  9081. this.infiniteDistance = source.infiniteDistance;
  9082. this.setPivotMatrix(source.getPivotMatrix());
  9083. this.refreshBoundingInfo();
  9084. this._syncSubMeshes();
  9085. }
  9086. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  9087. get: function () {
  9088. return this._sourceMesh.receiveShadows;
  9089. },
  9090. enumerable: true,
  9091. configurable: true
  9092. });
  9093. Object.defineProperty(InstancedMesh.prototype, "material", {
  9094. get: function () {
  9095. return this._sourceMesh.material;
  9096. },
  9097. enumerable: true,
  9098. configurable: true
  9099. });
  9100. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  9101. get: function () {
  9102. return this._sourceMesh.visibility;
  9103. },
  9104. enumerable: true,
  9105. configurable: true
  9106. });
  9107. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  9108. get: function () {
  9109. return this._sourceMesh.skeleton;
  9110. },
  9111. enumerable: true,
  9112. configurable: true
  9113. });
  9114. InstancedMesh.prototype.getTotalVertices = function () {
  9115. return this._sourceMesh.getTotalVertices();
  9116. };
  9117. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  9118. get: function () {
  9119. return this._sourceMesh;
  9120. },
  9121. enumerable: true,
  9122. configurable: true
  9123. });
  9124. InstancedMesh.prototype.getVerticesData = function (kind) {
  9125. return this._sourceMesh.getVerticesData(kind);
  9126. };
  9127. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  9128. return this._sourceMesh.isVerticesDataPresent(kind);
  9129. };
  9130. InstancedMesh.prototype.getIndices = function () {
  9131. return this._sourceMesh.getIndices();
  9132. };
  9133. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  9134. get: function () {
  9135. return this._sourceMesh._positions;
  9136. },
  9137. enumerable: true,
  9138. configurable: true
  9139. });
  9140. InstancedMesh.prototype.refreshBoundingInfo = function () {
  9141. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9142. if (data) {
  9143. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  9144. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9145. }
  9146. this._updateBoundingInfo();
  9147. };
  9148. InstancedMesh.prototype._preActivate = function () {
  9149. this.sourceMesh._preActivate();
  9150. };
  9151. InstancedMesh.prototype._activate = function (renderId) {
  9152. this.sourceMesh._registerInstanceForRenderId(this, renderId);
  9153. };
  9154. InstancedMesh.prototype._syncSubMeshes = function () {
  9155. this.releaseSubMeshes();
  9156. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  9157. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  9158. }
  9159. };
  9160. InstancedMesh.prototype._generatePointsArray = function () {
  9161. return this._sourceMesh._generatePointsArray();
  9162. };
  9163. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9164. var result = this._sourceMesh.createInstance(name);
  9165. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  9166. this.refreshBoundingInfo();
  9167. if (newParent) {
  9168. result.parent = newParent;
  9169. }
  9170. if (!doNotCloneChildren) {
  9171. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9172. var mesh = this.getScene().meshes[index];
  9173. if (mesh.parent == this) {
  9174. mesh.clone(mesh.name, result);
  9175. }
  9176. }
  9177. }
  9178. result.computeWorldMatrix(true);
  9179. return result;
  9180. };
  9181. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  9182. var index = this._sourceMesh.instances.indexOf(this);
  9183. this._sourceMesh.instances.splice(index, 1);
  9184. _super.prototype.dispose.call(this, doNotRecurse);
  9185. };
  9186. return InstancedMesh;
  9187. })(BABYLON.AbstractMesh);
  9188. BABYLON.InstancedMesh = InstancedMesh;
  9189. })(BABYLON || (BABYLON = {}));
  9190. var BABYLON;
  9191. (function (BABYLON) {
  9192. var SubMesh = (function () {
  9193. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  9194. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  9195. this.materialIndex = materialIndex;
  9196. this.verticesStart = verticesStart;
  9197. this.verticesCount = verticesCount;
  9198. this.indexStart = indexStart;
  9199. this.indexCount = indexCount;
  9200. this._renderId = 0;
  9201. this._mesh = mesh;
  9202. this._renderingMesh = renderingMesh || mesh;
  9203. mesh.subMeshes.push(this);
  9204. this._id = mesh.subMeshes.length - 1;
  9205. if (createBoundingBox) {
  9206. this.refreshBoundingInfo();
  9207. }
  9208. }
  9209. SubMesh.prototype.getBoundingInfo = function () {
  9210. return this._boundingInfo;
  9211. };
  9212. SubMesh.prototype.getMesh = function () {
  9213. return this._mesh;
  9214. };
  9215. SubMesh.prototype.getRenderingMesh = function () {
  9216. return this._renderingMesh;
  9217. };
  9218. SubMesh.prototype.getMaterial = function () {
  9219. var rootMaterial = this._renderingMesh.material;
  9220. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  9221. var multiMaterial = rootMaterial;
  9222. return multiMaterial.getSubMaterial(this.materialIndex);
  9223. }
  9224. if (!rootMaterial) {
  9225. return this._mesh.getScene().defaultMaterial;
  9226. }
  9227. return rootMaterial;
  9228. };
  9229. SubMesh.prototype.refreshBoundingInfo = function () {
  9230. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9231. if (!data) {
  9232. this._boundingInfo = this._mesh._boundingInfo;
  9233. return;
  9234. }
  9235. var indices = this._renderingMesh.getIndices();
  9236. var extend;
  9237. if (this.indexStart === 0 && this.indexCount === indices.length) {
  9238. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  9239. } else {
  9240. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  9241. }
  9242. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9243. };
  9244. SubMesh.prototype._checkCollision = function (collider) {
  9245. return this._boundingInfo._checkCollision(collider);
  9246. };
  9247. SubMesh.prototype.updateBoundingInfo = function (world) {
  9248. if (!this._boundingInfo) {
  9249. this.refreshBoundingInfo();
  9250. }
  9251. this._boundingInfo._update(world);
  9252. };
  9253. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  9254. return this._boundingInfo.isInFrustum(frustumPlanes);
  9255. };
  9256. SubMesh.prototype.render = function () {
  9257. this._renderingMesh.render(this);
  9258. };
  9259. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  9260. if (!this._linesIndexBuffer) {
  9261. var linesIndices = [];
  9262. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  9263. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  9264. }
  9265. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  9266. this.linesIndexCount = linesIndices.length;
  9267. }
  9268. return this._linesIndexBuffer;
  9269. };
  9270. SubMesh.prototype.canIntersects = function (ray) {
  9271. return ray.intersectsBox(this._boundingInfo.boundingBox);
  9272. };
  9273. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  9274. var intersectInfo = null;
  9275. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  9276. var p0 = positions[indices[index]];
  9277. var p1 = positions[indices[index + 1]];
  9278. var p2 = positions[indices[index + 2]];
  9279. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  9280. if (currentIntersectInfo) {
  9281. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9282. intersectInfo = currentIntersectInfo;
  9283. intersectInfo.faceId = index / 3;
  9284. if (fastCheck) {
  9285. break;
  9286. }
  9287. }
  9288. }
  9289. }
  9290. return intersectInfo;
  9291. };
  9292. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  9293. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  9294. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  9295. return result;
  9296. };
  9297. SubMesh.prototype.dispose = function () {
  9298. if (this._linesIndexBuffer) {
  9299. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  9300. this._linesIndexBuffer = null;
  9301. }
  9302. var index = this._mesh.subMeshes.indexOf(this);
  9303. this._mesh.subMeshes.splice(index, 1);
  9304. };
  9305. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  9306. var minVertexIndex = Number.MAX_VALUE;
  9307. var maxVertexIndex = -Number.MAX_VALUE;
  9308. renderingMesh = renderingMesh || mesh;
  9309. var indices = renderingMesh.getIndices();
  9310. for (var index = startIndex; index < startIndex + indexCount; index++) {
  9311. var vertexIndex = indices[index];
  9312. if (vertexIndex < minVertexIndex)
  9313. minVertexIndex = vertexIndex;
  9314. if (vertexIndex > maxVertexIndex)
  9315. maxVertexIndex = vertexIndex;
  9316. }
  9317. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  9318. };
  9319. return SubMesh;
  9320. })();
  9321. BABYLON.SubMesh = SubMesh;
  9322. })(BABYLON || (BABYLON = {}));
  9323. var BABYLON;
  9324. (function (BABYLON) {
  9325. var BaseTexture = (function () {
  9326. function BaseTexture(scene) {
  9327. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9328. this.hasAlpha = false;
  9329. this.getAlphaFromRGB = false;
  9330. this.level = 1;
  9331. this.isCube = false;
  9332. this.isRenderTarget = false;
  9333. this.animations = new Array();
  9334. this.coordinatesIndex = 0;
  9335. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  9336. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  9337. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  9338. this.anisotropicFilteringLevel = 4;
  9339. this._scene = scene;
  9340. this._scene.textures.push(this);
  9341. }
  9342. BaseTexture.prototype.getScene = function () {
  9343. return this._scene;
  9344. };
  9345. BaseTexture.prototype.getTextureMatrix = function () {
  9346. return null;
  9347. };
  9348. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  9349. return null;
  9350. };
  9351. BaseTexture.prototype.getInternalTexture = function () {
  9352. return this._texture;
  9353. };
  9354. BaseTexture.prototype.isReady = function () {
  9355. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9356. return true;
  9357. }
  9358. if (this._texture) {
  9359. return this._texture.isReady;
  9360. }
  9361. return false;
  9362. };
  9363. BaseTexture.prototype.getSize = function () {
  9364. if (this._texture._width) {
  9365. return { width: this._texture._width, height: this._texture._height };
  9366. }
  9367. if (this._texture._size) {
  9368. return { width: this._texture._size, height: this._texture._size };
  9369. }
  9370. return { width: 0, height: 0 };
  9371. };
  9372. BaseTexture.prototype.getBaseSize = function () {
  9373. if (!this.isReady())
  9374. return { width: 0, height: 0 };
  9375. if (this._texture._size) {
  9376. return { width: this._texture._size, height: this._texture._size };
  9377. }
  9378. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  9379. };
  9380. BaseTexture.prototype.scale = function (ratio) {
  9381. };
  9382. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  9383. get: function () {
  9384. return false;
  9385. },
  9386. enumerable: true,
  9387. configurable: true
  9388. });
  9389. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  9390. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9391. for (var index = 0; index < texturesCache.length; index++) {
  9392. var texturesCacheEntry = texturesCache[index];
  9393. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  9394. texturesCache.splice(index, 1);
  9395. return;
  9396. }
  9397. }
  9398. };
  9399. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  9400. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9401. for (var index = 0; index < texturesCache.length; index++) {
  9402. var texturesCacheEntry = texturesCache[index];
  9403. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  9404. texturesCacheEntry.references++;
  9405. return texturesCacheEntry;
  9406. }
  9407. }
  9408. return null;
  9409. };
  9410. BaseTexture.prototype.delayLoad = function () {
  9411. };
  9412. BaseTexture.prototype.releaseInternalTexture = function () {
  9413. if (!this._texture) {
  9414. return;
  9415. }
  9416. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9417. this._texture.references--;
  9418. if (this._texture.references == 0) {
  9419. var index = texturesCache.indexOf(this._texture);
  9420. texturesCache.splice(index, 1);
  9421. this._scene.getEngine()._releaseTexture(this._texture);
  9422. delete this._texture;
  9423. }
  9424. };
  9425. BaseTexture.prototype.clone = function () {
  9426. return null;
  9427. };
  9428. BaseTexture.prototype.dispose = function () {
  9429. var index = this._scene.textures.indexOf(this);
  9430. if (index >= 0) {
  9431. this._scene.textures.splice(index, 1);
  9432. }
  9433. if (this._texture === undefined) {
  9434. return;
  9435. }
  9436. this.releaseInternalTexture();
  9437. if (this.onDispose) {
  9438. this.onDispose();
  9439. }
  9440. };
  9441. return BaseTexture;
  9442. })();
  9443. BABYLON.BaseTexture = BaseTexture;
  9444. })(BABYLON || (BABYLON = {}));
  9445. var BABYLON;
  9446. (function (BABYLON) {
  9447. var RenderingGroup = (function () {
  9448. function RenderingGroup(index, scene) {
  9449. this.index = index;
  9450. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  9451. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  9452. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  9453. this._scene = scene;
  9454. }
  9455. RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
  9456. if (customRenderFunction) {
  9457. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
  9458. return true;
  9459. }
  9460. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  9461. return false;
  9462. }
  9463. var engine = this._scene.getEngine();
  9464. var subIndex;
  9465. var submesh;
  9466. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  9467. submesh = this._opaqueSubMeshes.data[subIndex];
  9468. this._activeVertices += submesh.verticesCount;
  9469. submesh.render();
  9470. }
  9471. engine.setAlphaTesting(true);
  9472. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  9473. submesh = this._alphaTestSubMeshes.data[subIndex];
  9474. this._activeVertices += submesh.verticesCount;
  9475. submesh.render();
  9476. }
  9477. engine.setAlphaTesting(false);
  9478. if (beforeTransparents) {
  9479. beforeTransparents();
  9480. }
  9481. if (this._transparentSubMeshes.length) {
  9482. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  9483. submesh = this._transparentSubMeshes.data[subIndex];
  9484. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  9485. }
  9486. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  9487. sortedArray.sort(function (a, b) {
  9488. if (a._distanceToCamera < b._distanceToCamera) {
  9489. return 1;
  9490. }
  9491. if (a._distanceToCamera > b._distanceToCamera) {
  9492. return -1;
  9493. }
  9494. return 0;
  9495. });
  9496. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9497. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  9498. submesh = sortedArray[subIndex];
  9499. this._activeVertices += submesh.verticesCount;
  9500. submesh.render();
  9501. }
  9502. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  9503. }
  9504. return true;
  9505. };
  9506. RenderingGroup.prototype.prepare = function () {
  9507. this._opaqueSubMeshes.reset();
  9508. this._transparentSubMeshes.reset();
  9509. this._alphaTestSubMeshes.reset();
  9510. };
  9511. RenderingGroup.prototype.dispatch = function (subMesh) {
  9512. var material = subMesh.getMaterial();
  9513. var mesh = subMesh.getMesh();
  9514. if (material.needAlphaBlending() || mesh.visibility < 1.0) {
  9515. if (material.alpha > 0 || mesh.visibility < 1.0) {
  9516. this._transparentSubMeshes.push(subMesh);
  9517. }
  9518. } else if (material.needAlphaTesting()) {
  9519. this._alphaTestSubMeshes.push(subMesh);
  9520. } else {
  9521. this._opaqueSubMeshes.push(subMesh);
  9522. }
  9523. };
  9524. return RenderingGroup;
  9525. })();
  9526. BABYLON.RenderingGroup = RenderingGroup;
  9527. })(BABYLON || (BABYLON = {}));
  9528. var BABYLON;
  9529. (function (BABYLON) {
  9530. var RenderingManager = (function () {
  9531. function RenderingManager(scene) {
  9532. this._renderingGroups = new Array();
  9533. this._scene = scene;
  9534. }
  9535. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  9536. if (this._scene._activeParticleSystems.length === 0) {
  9537. return;
  9538. }
  9539. var beforeParticlesDate = BABYLON.Tools.Now;
  9540. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  9541. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  9542. if (particleSystem.renderingGroupId !== index) {
  9543. continue;
  9544. }
  9545. this._clearDepthBuffer();
  9546. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  9547. this._scene._activeParticles += particleSystem.render();
  9548. }
  9549. }
  9550. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  9551. };
  9552. RenderingManager.prototype._renderSprites = function (index) {
  9553. if (this._scene.spriteManagers.length === 0) {
  9554. return;
  9555. }
  9556. var beforeSpritessDate = BABYLON.Tools.Now;
  9557. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  9558. var spriteManager = this._scene.spriteManagers[id];
  9559. if (spriteManager.renderingGroupId === index) {
  9560. this._clearDepthBuffer();
  9561. spriteManager.render();
  9562. }
  9563. }
  9564. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  9565. };
  9566. RenderingManager.prototype._clearDepthBuffer = function () {
  9567. if (this._depthBufferAlreadyCleaned) {
  9568. return;
  9569. }
  9570. this._scene.getEngine().clear(0, false, true);
  9571. this._depthBufferAlreadyCleaned = true;
  9572. };
  9573. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  9574. var _this = this;
  9575. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  9576. this._depthBufferAlreadyCleaned = false;
  9577. var renderingGroup = this._renderingGroups[index];
  9578. if (renderingGroup) {
  9579. this._clearDepthBuffer();
  9580. if (!renderingGroup.render(customRenderFunction, function () {
  9581. if (renderSprites) {
  9582. _this._renderSprites(index);
  9583. }
  9584. })) {
  9585. this._renderingGroups.splice(index, 1);
  9586. }
  9587. } else if (renderSprites) {
  9588. this._renderSprites(index);
  9589. }
  9590. if (renderParticles) {
  9591. this._renderParticles(index, activeMeshes);
  9592. }
  9593. }
  9594. };
  9595. RenderingManager.prototype.reset = function () {
  9596. for (var index in this._renderingGroups) {
  9597. var renderingGroup = this._renderingGroups[index];
  9598. renderingGroup.prepare();
  9599. }
  9600. };
  9601. RenderingManager.prototype.dispatch = function (subMesh) {
  9602. var mesh = subMesh.getMesh();
  9603. var renderingGroupId = mesh.renderingGroupId || 0;
  9604. if (!this._renderingGroups[renderingGroupId]) {
  9605. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  9606. }
  9607. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  9608. };
  9609. RenderingManager.MAX_RENDERINGGROUPS = 4;
  9610. return RenderingManager;
  9611. })();
  9612. BABYLON.RenderingManager = RenderingManager;
  9613. })(BABYLON || (BABYLON = {}));
  9614. var __extends = this.__extends || function (d, b) {
  9615. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9616. function __() { this.constructor = d; }
  9617. __.prototype = b.prototype;
  9618. d.prototype = new __();
  9619. };
  9620. var BABYLON;
  9621. (function (BABYLON) {
  9622. var Texture = (function (_super) {
  9623. __extends(Texture, _super);
  9624. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  9625. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  9626. if (typeof onLoad === "undefined") { onLoad = null; }
  9627. if (typeof onError === "undefined") { onError = null; }
  9628. if (typeof buffer === "undefined") { buffer = null; }
  9629. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  9630. _super.call(this, scene);
  9631. this.uOffset = 0;
  9632. this.vOffset = 0;
  9633. this.uScale = 1.0;
  9634. this.vScale = 1.0;
  9635. this.uAng = 0;
  9636. this.vAng = 0;
  9637. this.wAng = 0;
  9638. this.name = url;
  9639. this.url = url;
  9640. this._noMipmap = noMipmap;
  9641. this._invertY = invertY;
  9642. this._samplingMode = samplingMode;
  9643. this._buffer = buffer;
  9644. this._deleteBuffer = deleteBuffer;
  9645. if (!url) {
  9646. return;
  9647. }
  9648. this._texture = this._getFromCache(url, noMipmap);
  9649. if (!this._texture) {
  9650. if (!scene.useDelayedTextureLoading) {
  9651. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  9652. if (deleteBuffer) {
  9653. delete this._buffer;
  9654. }
  9655. } else {
  9656. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9657. }
  9658. }
  9659. }
  9660. Texture.prototype.delayLoad = function () {
  9661. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9662. return;
  9663. }
  9664. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9665. this._texture = this._getFromCache(this.url, this._noMipmap);
  9666. if (!this._texture) {
  9667. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  9668. if (this._deleteBuffer) {
  9669. delete this._buffer;
  9670. }
  9671. }
  9672. };
  9673. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  9674. x -= this.uOffset + 0.5;
  9675. y -= this.vOffset + 0.5;
  9676. z -= 0.5;
  9677. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  9678. t.x *= this.uScale;
  9679. t.y *= this.vScale;
  9680. t.x += 0.5;
  9681. t.y += 0.5;
  9682. t.z += 0.5;
  9683. };
  9684. Texture.prototype.getTextureMatrix = function () {
  9685. 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) {
  9686. return this._cachedTextureMatrix;
  9687. }
  9688. this._cachedUOffset = this.uOffset;
  9689. this._cachedVOffset = this.vOffset;
  9690. this._cachedUScale = this.uScale;
  9691. this._cachedVScale = this.vScale;
  9692. this._cachedUAng = this.uAng;
  9693. this._cachedVAng = this.vAng;
  9694. this._cachedWAng = this.wAng;
  9695. if (!this._cachedTextureMatrix) {
  9696. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9697. this._rowGenerationMatrix = new BABYLON.Matrix();
  9698. this._t0 = BABYLON.Vector3.Zero();
  9699. this._t1 = BABYLON.Vector3.Zero();
  9700. this._t2 = BABYLON.Vector3.Zero();
  9701. }
  9702. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  9703. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  9704. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  9705. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  9706. this._t1.subtractInPlace(this._t0);
  9707. this._t2.subtractInPlace(this._t0);
  9708. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9709. this._cachedTextureMatrix.m[0] = this._t1.x;
  9710. this._cachedTextureMatrix.m[1] = this._t1.y;
  9711. this._cachedTextureMatrix.m[2] = this._t1.z;
  9712. this._cachedTextureMatrix.m[4] = this._t2.x;
  9713. this._cachedTextureMatrix.m[5] = this._t2.y;
  9714. this._cachedTextureMatrix.m[6] = this._t2.z;
  9715. this._cachedTextureMatrix.m[8] = this._t0.x;
  9716. this._cachedTextureMatrix.m[9] = this._t0.y;
  9717. this._cachedTextureMatrix.m[10] = this._t0.z;
  9718. return this._cachedTextureMatrix;
  9719. };
  9720. Texture.prototype.getReflectionTextureMatrix = function () {
  9721. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  9722. return this._cachedTextureMatrix;
  9723. }
  9724. if (!this._cachedTextureMatrix) {
  9725. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9726. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  9727. }
  9728. switch (this.coordinatesMode) {
  9729. case BABYLON.Texture.SPHERICAL_MODE:
  9730. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9731. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  9732. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  9733. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  9734. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  9735. break;
  9736. case BABYLON.Texture.PLANAR_MODE:
  9737. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9738. this._cachedTextureMatrix[0] = this.uScale;
  9739. this._cachedTextureMatrix[5] = this.vScale;
  9740. this._cachedTextureMatrix[12] = this.uOffset;
  9741. this._cachedTextureMatrix[13] = this.vOffset;
  9742. break;
  9743. case BABYLON.Texture.PROJECTION_MODE:
  9744. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  9745. this._projectionModeMatrix.m[0] = 0.5;
  9746. this._projectionModeMatrix.m[5] = -0.5;
  9747. this._projectionModeMatrix.m[10] = 0.0;
  9748. this._projectionModeMatrix.m[12] = 0.5;
  9749. this._projectionModeMatrix.m[13] = 0.5;
  9750. this._projectionModeMatrix.m[14] = 1.0;
  9751. this._projectionModeMatrix.m[15] = 1.0;
  9752. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  9753. break;
  9754. default:
  9755. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9756. break;
  9757. }
  9758. return this._cachedTextureMatrix;
  9759. };
  9760. Texture.prototype.clone = function () {
  9761. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  9762. newTexture.hasAlpha = this.hasAlpha;
  9763. newTexture.level = this.level;
  9764. newTexture.wrapU = this.wrapU;
  9765. newTexture.wrapV = this.wrapV;
  9766. newTexture.coordinatesIndex = this.coordinatesIndex;
  9767. newTexture.coordinatesMode = this.coordinatesMode;
  9768. newTexture.uOffset = this.uOffset;
  9769. newTexture.vOffset = this.vOffset;
  9770. newTexture.uScale = this.uScale;
  9771. newTexture.vScale = this.vScale;
  9772. newTexture.uAng = this.uAng;
  9773. newTexture.vAng = this.vAng;
  9774. newTexture.wAng = this.wAng;
  9775. return newTexture;
  9776. };
  9777. Texture.NEAREST_SAMPLINGMODE = 1;
  9778. Texture.BILINEAR_SAMPLINGMODE = 2;
  9779. Texture.TRILINEAR_SAMPLINGMODE = 3;
  9780. Texture.EXPLICIT_MODE = 0;
  9781. Texture.SPHERICAL_MODE = 1;
  9782. Texture.PLANAR_MODE = 2;
  9783. Texture.CUBIC_MODE = 3;
  9784. Texture.PROJECTION_MODE = 4;
  9785. Texture.SKYBOX_MODE = 5;
  9786. Texture.CLAMP_ADDRESSMODE = 0;
  9787. Texture.WRAP_ADDRESSMODE = 1;
  9788. Texture.MIRROR_ADDRESSMODE = 2;
  9789. return Texture;
  9790. })(BABYLON.BaseTexture);
  9791. BABYLON.Texture = Texture;
  9792. })(BABYLON || (BABYLON = {}));
  9793. var __extends = this.__extends || function (d, b) {
  9794. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9795. function __() { this.constructor = d; }
  9796. __.prototype = b.prototype;
  9797. d.prototype = new __();
  9798. };
  9799. var BABYLON;
  9800. (function (BABYLON) {
  9801. var CubeTexture = (function (_super) {
  9802. __extends(CubeTexture, _super);
  9803. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  9804. _super.call(this, scene);
  9805. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  9806. this.name = rootUrl;
  9807. this.url = rootUrl;
  9808. this._noMipmap = noMipmap;
  9809. this.hasAlpha = false;
  9810. this._texture = this._getFromCache(rootUrl, noMipmap);
  9811. if (!extensions) {
  9812. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  9813. }
  9814. this._extensions = extensions;
  9815. if (!this._texture) {
  9816. if (!scene.useDelayedTextureLoading) {
  9817. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  9818. } else {
  9819. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9820. }
  9821. }
  9822. this.isCube = true;
  9823. this._textureMatrix = BABYLON.Matrix.Identity();
  9824. }
  9825. CubeTexture.prototype.clone = function () {
  9826. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  9827. newTexture.level = this.level;
  9828. newTexture.wrapU = this.wrapU;
  9829. newTexture.wrapV = this.wrapV;
  9830. newTexture.coordinatesIndex = this.coordinatesIndex;
  9831. newTexture.coordinatesMode = this.coordinatesMode;
  9832. return newTexture;
  9833. };
  9834. CubeTexture.prototype.delayLoad = function () {
  9835. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9836. return;
  9837. }
  9838. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9839. this._texture = this._getFromCache(this.url, this._noMipmap);
  9840. if (!this._texture) {
  9841. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  9842. }
  9843. };
  9844. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  9845. return this._textureMatrix;
  9846. };
  9847. return CubeTexture;
  9848. })(BABYLON.BaseTexture);
  9849. BABYLON.CubeTexture = CubeTexture;
  9850. })(BABYLON || (BABYLON = {}));
  9851. var __extends = this.__extends || function (d, b) {
  9852. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9853. function __() { this.constructor = d; }
  9854. __.prototype = b.prototype;
  9855. d.prototype = new __();
  9856. };
  9857. var BABYLON;
  9858. (function (BABYLON) {
  9859. var RenderTargetTexture = (function (_super) {
  9860. __extends(RenderTargetTexture, _super);
  9861. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  9862. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  9863. _super.call(this, null, scene, !generateMipMaps);
  9864. this.renderList = new Array();
  9865. this.renderParticles = true;
  9866. this.renderSprites = false;
  9867. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  9868. this._currentRefreshId = -1;
  9869. this._refreshRate = 1;
  9870. this.name = name;
  9871. this.isRenderTarget = true;
  9872. this._size = size;
  9873. this._generateMipMaps = generateMipMaps;
  9874. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  9875. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  9876. this._renderingManager = new BABYLON.RenderingManager(scene);
  9877. }
  9878. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  9879. this._currentRefreshId = -1;
  9880. };
  9881. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  9882. get: function () {
  9883. return this._refreshRate;
  9884. },
  9885. set: function (value) {
  9886. this._refreshRate = value;
  9887. this.resetRefreshCounter();
  9888. },
  9889. enumerable: true,
  9890. configurable: true
  9891. });
  9892. RenderTargetTexture.prototype._shouldRender = function () {
  9893. if (this._currentRefreshId === -1) {
  9894. this._currentRefreshId = 1;
  9895. return true;
  9896. }
  9897. if (this.refreshRate == this._currentRefreshId) {
  9898. this._currentRefreshId = 1;
  9899. return true;
  9900. }
  9901. this._currentRefreshId++;
  9902. return false;
  9903. };
  9904. RenderTargetTexture.prototype.isReady = function () {
  9905. if (!this.getScene().renderTargetsEnabled) {
  9906. return false;
  9907. }
  9908. return _super.prototype.isReady.call(this);
  9909. };
  9910. RenderTargetTexture.prototype.getRenderSize = function () {
  9911. return this._size;
  9912. };
  9913. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  9914. get: function () {
  9915. return true;
  9916. },
  9917. enumerable: true,
  9918. configurable: true
  9919. });
  9920. RenderTargetTexture.prototype.scale = function (ratio) {
  9921. var newSize = this._size * ratio;
  9922. this.resize(newSize, this._generateMipMaps);
  9923. };
  9924. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  9925. this.releaseInternalTexture();
  9926. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  9927. };
  9928. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  9929. var scene = this.getScene();
  9930. var engine = scene.getEngine();
  9931. if (this._waitingRenderList) {
  9932. this.renderList = [];
  9933. for (var index = 0; index < this._waitingRenderList.length; index++) {
  9934. var id = this._waitingRenderList[index];
  9935. this.renderList.push(scene.getMeshByID(id));
  9936. }
  9937. delete this._waitingRenderList;
  9938. }
  9939. if (!this.renderList) {
  9940. return;
  9941. }
  9942. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  9943. engine.bindFramebuffer(this._texture);
  9944. }
  9945. engine.clear(scene.clearColor, true, true);
  9946. this._renderingManager.reset();
  9947. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  9948. var mesh = this.renderList[meshIndex];
  9949. if (mesh) {
  9950. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  9951. this.resetRefreshCounter();
  9952. continue;
  9953. }
  9954. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  9955. mesh._activate(scene.getRenderId());
  9956. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  9957. var subMesh = mesh.subMeshes[subIndex];
  9958. scene._activeVertices += subMesh.verticesCount;
  9959. this._renderingManager.dispatch(subMesh);
  9960. }
  9961. }
  9962. }
  9963. }
  9964. if (!this._doNotChangeAspectRatio) {
  9965. scene.updateTransformMatrix(true);
  9966. }
  9967. if (this.onBeforeRender) {
  9968. this.onBeforeRender();
  9969. }
  9970. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  9971. if (useCameraPostProcess) {
  9972. scene.postProcessManager._finalizeFrame(false, this._texture);
  9973. }
  9974. if (this.onAfterRender) {
  9975. this.onAfterRender();
  9976. }
  9977. engine.unBindFramebuffer(this._texture);
  9978. if (!this._doNotChangeAspectRatio) {
  9979. scene.updateTransformMatrix(true);
  9980. }
  9981. };
  9982. RenderTargetTexture.prototype.clone = function () {
  9983. var textureSize = this.getSize();
  9984. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9985. newTexture.hasAlpha = this.hasAlpha;
  9986. newTexture.level = this.level;
  9987. newTexture.coordinatesMode = this.coordinatesMode;
  9988. newTexture.renderList = this.renderList.slice(0);
  9989. return newTexture;
  9990. };
  9991. return RenderTargetTexture;
  9992. })(BABYLON.Texture);
  9993. BABYLON.RenderTargetTexture = RenderTargetTexture;
  9994. })(BABYLON || (BABYLON = {}));
  9995. var __extends = this.__extends || function (d, b) {
  9996. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9997. function __() { this.constructor = d; }
  9998. __.prototype = b.prototype;
  9999. d.prototype = new __();
  10000. };
  10001. var BABYLON;
  10002. (function (BABYLON) {
  10003. var ProceduralTexture = (function (_super) {
  10004. __extends(ProceduralTexture, _super);
  10005. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  10006. _super.call(this, null, scene, !generateMipMaps);
  10007. this._currentRefreshId = -1;
  10008. this._refreshRate = 1;
  10009. this._vertexDeclaration = [2];
  10010. this._vertexStrideSize = 2 * 4;
  10011. this._uniforms = new Array();
  10012. this._samplers = new Array();
  10013. this._textures = new Array();
  10014. this._floats = new Array();
  10015. this._floatsArrays = {};
  10016. this._colors3 = new Array();
  10017. this._colors4 = new Array();
  10018. this._vectors2 = new Array();
  10019. this._vectors3 = new Array();
  10020. this._matrices = new Array();
  10021. scene._proceduralTextures.push(this);
  10022. this.name = name;
  10023. this.isRenderTarget = true;
  10024. this._size = size;
  10025. this._generateMipMaps = generateMipMaps;
  10026. this._fragment = fragment;
  10027. this._fallbackTexture = fallbackTexture;
  10028. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  10029. var vertices = [];
  10030. vertices.push(1, 1);
  10031. vertices.push(-1, 1);
  10032. vertices.push(-1, -1);
  10033. vertices.push(1, -1);
  10034. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  10035. var indices = [];
  10036. indices.push(0);
  10037. indices.push(1);
  10038. indices.push(2);
  10039. indices.push(0);
  10040. indices.push(2);
  10041. indices.push(3);
  10042. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  10043. }
  10044. ProceduralTexture.prototype.isReady = function () {
  10045. var _this = this;
  10046. var engine = this.getScene().getEngine();
  10047. this._effect = engine.createEffect({ vertex: "procedural", fragment: this._fragment }, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  10048. _this.releaseInternalTexture();
  10049. _this._texture = _this._fallbackTexture._texture;
  10050. _this._texture.references++;
  10051. });
  10052. return this._effect.isReady();
  10053. };
  10054. ProceduralTexture.prototype.resetRefreshCounter = function () {
  10055. this._currentRefreshId = -1;
  10056. };
  10057. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  10058. get: function () {
  10059. return this._refreshRate;
  10060. },
  10061. set: function (value) {
  10062. this._refreshRate = value;
  10063. this.resetRefreshCounter();
  10064. },
  10065. enumerable: true,
  10066. configurable: true
  10067. });
  10068. ProceduralTexture.prototype._shouldRender = function () {
  10069. if (!this.isReady() || !this._texture) {
  10070. return false;
  10071. }
  10072. if (this._currentRefreshId === -1) {
  10073. this._currentRefreshId = 1;
  10074. return true;
  10075. }
  10076. if (this.refreshRate == this._currentRefreshId) {
  10077. this._currentRefreshId = 1;
  10078. return true;
  10079. }
  10080. this._currentRefreshId++;
  10081. return false;
  10082. };
  10083. ProceduralTexture.prototype.getRenderSize = function () {
  10084. return this._size;
  10085. };
  10086. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  10087. this.releaseInternalTexture();
  10088. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  10089. };
  10090. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  10091. if (this._uniforms.indexOf(uniformName) === -1) {
  10092. this._uniforms.push(uniformName);
  10093. }
  10094. };
  10095. ProceduralTexture.prototype.setTexture = function (name, texture) {
  10096. if (this._samplers.indexOf(name) === -1) {
  10097. this._samplers.push(name);
  10098. }
  10099. this._textures[name] = texture;
  10100. return this;
  10101. };
  10102. ProceduralTexture.prototype.setFloat = function (name, value) {
  10103. this._checkUniform(name);
  10104. this._floats[name] = value;
  10105. return this;
  10106. };
  10107. ProceduralTexture.prototype.setFloats = function (name, value) {
  10108. this._checkUniform(name);
  10109. this._floatsArrays[name] = value;
  10110. return this;
  10111. };
  10112. ProceduralTexture.prototype.setColor3 = function (name, value) {
  10113. this._checkUniform(name);
  10114. this._colors3[name] = value;
  10115. return this;
  10116. };
  10117. ProceduralTexture.prototype.setColor4 = function (name, value) {
  10118. this._checkUniform(name);
  10119. this._colors4[name] = value;
  10120. return this;
  10121. };
  10122. ProceduralTexture.prototype.setVector2 = function (name, value) {
  10123. this._checkUniform(name);
  10124. this._vectors2[name] = value;
  10125. return this;
  10126. };
  10127. ProceduralTexture.prototype.setVector3 = function (name, value) {
  10128. this._checkUniform(name);
  10129. this._vectors3[name] = value;
  10130. return this;
  10131. };
  10132. ProceduralTexture.prototype.setMatrix = function (name, value) {
  10133. this._checkUniform(name);
  10134. this._matrices[name] = value;
  10135. return this;
  10136. };
  10137. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  10138. var scene = this.getScene();
  10139. var engine = scene.getEngine();
  10140. engine.bindFramebuffer(this._texture);
  10141. engine.clear(scene.clearColor, true, true);
  10142. engine.enableEffect(this._effect);
  10143. engine.setState(false);
  10144. for (var name in this._textures) {
  10145. this._effect.setTexture(name, this._textures[name]);
  10146. }
  10147. for (name in this._floats) {
  10148. this._effect.setFloat(name, this._floats[name]);
  10149. }
  10150. for (name in this._floatsArrays) {
  10151. this._effect.setArray(name, this._floatsArrays[name]);
  10152. }
  10153. for (name in this._colors3) {
  10154. this._effect.setColor3(name, this._colors3[name]);
  10155. }
  10156. for (name in this._colors4) {
  10157. var color = this._colors4[name];
  10158. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  10159. }
  10160. for (name in this._vectors2) {
  10161. this._effect.setVector2(name, this._vectors2[name]);
  10162. }
  10163. for (name in this._vectors3) {
  10164. this._effect.setVector3(name, this._vectors3[name]);
  10165. }
  10166. for (name in this._matrices) {
  10167. this._effect.setMatrix(name, this._matrices[name]);
  10168. }
  10169. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  10170. engine.draw(true, 0, 6);
  10171. engine.unBindFramebuffer(this._texture);
  10172. };
  10173. ProceduralTexture.prototype.clone = function () {
  10174. var textureSize = this.getSize();
  10175. var newTexture = new BABYLON.ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  10176. newTexture.hasAlpha = this.hasAlpha;
  10177. newTexture.level = this.level;
  10178. newTexture.coordinatesMode = this.coordinatesMode;
  10179. return newTexture;
  10180. };
  10181. ProceduralTexture.prototype.dispose = function () {
  10182. var index = this.getScene()._proceduralTextures.indexOf(this);
  10183. if (index >= 0) {
  10184. this.getScene()._proceduralTextures.splice(index, 1);
  10185. }
  10186. _super.prototype.dispose.call(this);
  10187. };
  10188. return ProceduralTexture;
  10189. })(BABYLON.Texture);
  10190. BABYLON.ProceduralTexture = ProceduralTexture;
  10191. })(BABYLON || (BABYLON = {}));
  10192. var __extends = this.__extends || function (d, b) {
  10193. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10194. function __() { this.constructor = d; }
  10195. __.prototype = b.prototype;
  10196. d.prototype = new __();
  10197. };
  10198. var BABYLON;
  10199. (function (BABYLON) {
  10200. var WoodProceduralTexture = (function (_super) {
  10201. __extends(WoodProceduralTexture, _super);
  10202. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10203. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  10204. this._ampScale = 0.03;
  10205. this._ringScale = 5;
  10206. this._woodColor1 = new BABYLON.Color3(0.80, 0.55, 0.01);
  10207. this._woodColor2 = new BABYLON.Color3(0.60, 0.41, 0.0);
  10208. this.updateShaderUniforms();
  10209. this.refreshRate = 0;
  10210. }
  10211. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  10212. this.setFloat("ampScale", this._ampScale);
  10213. this.setFloat("ringScale", this._ringScale);
  10214. this.setColor3("woodColor1", this._woodColor1);
  10215. this.setColor3("woodColor2", this._woodColor2);
  10216. };
  10217. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  10218. get: function () {
  10219. return this._ampScale;
  10220. },
  10221. set: function (value) {
  10222. this._ampScale = value;
  10223. this.updateShaderUniforms();
  10224. },
  10225. enumerable: true,
  10226. configurable: true
  10227. });
  10228. Object.defineProperty(WoodProceduralTexture.prototype, "ringScale", {
  10229. get: function () {
  10230. return this._ringScale;
  10231. },
  10232. set: function (value) {
  10233. this._ringScale = value;
  10234. this.updateShaderUniforms();
  10235. },
  10236. enumerable: true,
  10237. configurable: true
  10238. });
  10239. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor1", {
  10240. get: function () {
  10241. return this._woodColor1;
  10242. },
  10243. set: function (value) {
  10244. this._woodColor1 = value;
  10245. this.updateShaderUniforms();
  10246. },
  10247. enumerable: true,
  10248. configurable: true
  10249. });
  10250. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor2", {
  10251. get: function () {
  10252. return this._woodColor2;
  10253. },
  10254. set: function (value) {
  10255. this._woodColor2 = value;
  10256. this.updateShaderUniforms();
  10257. },
  10258. enumerable: true,
  10259. configurable: true
  10260. });
  10261. return WoodProceduralTexture;
  10262. })(BABYLON.ProceduralTexture);
  10263. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  10264. var FireProceduralTexture = (function (_super) {
  10265. __extends(FireProceduralTexture, _super);
  10266. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10267. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  10268. this._time = 0.0;
  10269. this._speed = new BABYLON.Vector2(0.5, 0.3);
  10270. this._shift = 1.6;
  10271. this._alpha = 1.0;
  10272. this._autoGenerateTime = true;
  10273. this._fireColors = FireProceduralTexture.RedFireColors;
  10274. this.updateShaderUniforms();
  10275. this.refreshRate = 1;
  10276. }
  10277. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  10278. this.setFloat("iGlobalTime", this._time);
  10279. this.setVector2("speed", this._speed);
  10280. this.setFloat("shift", this._shift);
  10281. this.setFloat("alpha", this._alpha);
  10282. this.setColor3("c1", new BABYLON.Color3(this._fireColors[0][0], this._fireColors[0][1], this._fireColors[0][2]));
  10283. this.setColor3("c2", new BABYLON.Color3(this._fireColors[1][0], this._fireColors[1][1], this._fireColors[1][2]));
  10284. this.setColor3("c3", new BABYLON.Color3(this._fireColors[2][0], this._fireColors[2][1], this._fireColors[2][2]));
  10285. this.setColor3("c4", new BABYLON.Color3(this._fireColors[3][0], this._fireColors[3][1], this._fireColors[3][2]));
  10286. this.setColor3("c5", new BABYLON.Color3(this._fireColors[4][0], this._fireColors[4][1], this._fireColors[4][2]));
  10287. this.setColor3("c6", new BABYLON.Color3(this._fireColors[5][0], this._fireColors[5][1], this._fireColors[5][2]));
  10288. };
  10289. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  10290. if (this._autoGenerateTime) {
  10291. this._time += this.getScene().getAnimationRatio() * 0.03;
  10292. this.updateShaderUniforms();
  10293. }
  10294. _super.prototype.render.call(this, useCameraPostProcess);
  10295. };
  10296. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  10297. get: function () {
  10298. return [
  10299. [0.5, 0.0, 1.0],
  10300. [0.9, 0.0, 1.0],
  10301. [0.2, 0.0, 1.0],
  10302. [1.0, 0.9, 1.0],
  10303. [0.1, 0.1, 1.0],
  10304. [0.9, 0.9, 1.0]
  10305. ];
  10306. },
  10307. enumerable: true,
  10308. configurable: true
  10309. });
  10310. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  10311. get: function () {
  10312. return [
  10313. [0.5, 1.0, 0.0],
  10314. [0.5, 1.0, 0.0],
  10315. [0.3, 0.4, 0.0],
  10316. [0.5, 1.0, 0.0],
  10317. [0.2, 0.0, 0.0],
  10318. [0.5, 1.0, 0.0]
  10319. ];
  10320. },
  10321. enumerable: true,
  10322. configurable: true
  10323. });
  10324. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  10325. get: function () {
  10326. return [
  10327. [0.5, 0.0, 0.1],
  10328. [0.9, 0.0, 0.0],
  10329. [0.2, 0.0, 0.0],
  10330. [1.0, 0.9, 0.0],
  10331. [0.1, 0.1, 0.1],
  10332. [0.9, 0.9, 0.9]
  10333. ];
  10334. },
  10335. enumerable: true,
  10336. configurable: true
  10337. });
  10338. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  10339. get: function () {
  10340. return [
  10341. [0.1, 0.0, 0.5],
  10342. [0.0, 0.0, 0.5],
  10343. [0.1, 0.0, 0.2],
  10344. [0.0, 0.0, 1.0],
  10345. [0.1, 0.2, 0.3],
  10346. [0.0, 0.2, 0.9]
  10347. ];
  10348. },
  10349. enumerable: true,
  10350. configurable: true
  10351. });
  10352. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  10353. get: function () {
  10354. return this._fireColors;
  10355. },
  10356. set: function (value) {
  10357. this._fireColors = value;
  10358. this.updateShaderUniforms();
  10359. },
  10360. enumerable: true,
  10361. configurable: true
  10362. });
  10363. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  10364. get: function () {
  10365. return this._time;
  10366. },
  10367. set: function (value) {
  10368. this._time = value;
  10369. this.updateShaderUniforms();
  10370. },
  10371. enumerable: true,
  10372. configurable: true
  10373. });
  10374. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  10375. get: function () {
  10376. return this._speed;
  10377. },
  10378. set: function (value) {
  10379. this._speed = value;
  10380. this.updateShaderUniforms();
  10381. },
  10382. enumerable: true,
  10383. configurable: true
  10384. });
  10385. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  10386. get: function () {
  10387. return this._shift;
  10388. },
  10389. set: function (value) {
  10390. this._shift = value;
  10391. this.updateShaderUniforms();
  10392. },
  10393. enumerable: true,
  10394. configurable: true
  10395. });
  10396. Object.defineProperty(FireProceduralTexture.prototype, "alpha", {
  10397. get: function () {
  10398. return this._alpha;
  10399. },
  10400. set: function (value) {
  10401. this._alpha = value;
  10402. this.updateShaderUniforms();
  10403. },
  10404. enumerable: true,
  10405. configurable: true
  10406. });
  10407. return FireProceduralTexture;
  10408. })(BABYLON.ProceduralTexture);
  10409. BABYLON.FireProceduralTexture = FireProceduralTexture;
  10410. var CloudProceduralTexture = (function (_super) {
  10411. __extends(CloudProceduralTexture, _super);
  10412. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10413. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  10414. this.refreshRate = 0;
  10415. }
  10416. return CloudProceduralTexture;
  10417. })(BABYLON.ProceduralTexture);
  10418. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  10419. })(BABYLON || (BABYLON = {}));
  10420. var __extends = this.__extends || function (d, b) {
  10421. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10422. function __() { this.constructor = d; }
  10423. __.prototype = b.prototype;
  10424. d.prototype = new __();
  10425. };
  10426. var BABYLON;
  10427. (function (BABYLON) {
  10428. var MirrorTexture = (function (_super) {
  10429. __extends(MirrorTexture, _super);
  10430. function MirrorTexture(name, size, scene, generateMipMaps) {
  10431. var _this = this;
  10432. _super.call(this, name, size, scene, generateMipMaps, true);
  10433. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  10434. this._transformMatrix = BABYLON.Matrix.Zero();
  10435. this._mirrorMatrix = BABYLON.Matrix.Zero();
  10436. this.onBeforeRender = function () {
  10437. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  10438. _this._savedViewMatrix = scene.getViewMatrix();
  10439. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  10440. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  10441. scene.clipPlane = _this.mirrorPlane;
  10442. scene.getEngine().cullBackFaces = false;
  10443. };
  10444. this.onAfterRender = function () {
  10445. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  10446. scene.getEngine().cullBackFaces = true;
  10447. delete scene.clipPlane;
  10448. };
  10449. }
  10450. MirrorTexture.prototype.clone = function () {
  10451. var textureSize = this.getSize();
  10452. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10453. newTexture.hasAlpha = this.hasAlpha;
  10454. newTexture.level = this.level;
  10455. newTexture.mirrorPlane = this.mirrorPlane.clone();
  10456. newTexture.renderList = this.renderList.slice(0);
  10457. return newTexture;
  10458. };
  10459. return MirrorTexture;
  10460. })(BABYLON.RenderTargetTexture);
  10461. BABYLON.MirrorTexture = MirrorTexture;
  10462. })(BABYLON || (BABYLON = {}));
  10463. var __extends = this.__extends || function (d, b) {
  10464. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10465. function __() { this.constructor = d; }
  10466. __.prototype = b.prototype;
  10467. d.prototype = new __();
  10468. };
  10469. var BABYLON;
  10470. (function (BABYLON) {
  10471. var DynamicTexture = (function (_super) {
  10472. __extends(DynamicTexture, _super);
  10473. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  10474. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10475. _super.call(this, null, scene, !generateMipMaps);
  10476. this.name = name;
  10477. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10478. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10479. this._generateMipMaps = generateMipMaps;
  10480. if (options.getContext) {
  10481. this._canvas = options;
  10482. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  10483. } else {
  10484. this._canvas = document.createElement("canvas");
  10485. if (options.width) {
  10486. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  10487. } else {
  10488. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  10489. }
  10490. }
  10491. var textureSize = this.getSize();
  10492. this._canvas.width = textureSize.width;
  10493. this._canvas.height = textureSize.height;
  10494. this._context = this._canvas.getContext("2d");
  10495. }
  10496. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  10497. get: function () {
  10498. return true;
  10499. },
  10500. enumerable: true,
  10501. configurable: true
  10502. });
  10503. DynamicTexture.prototype.scale = function (ratio) {
  10504. var textureSize = this.getSize();
  10505. textureSize.width *= ratio;
  10506. textureSize.height *= ratio;
  10507. this._canvas.width = textureSize.width;
  10508. this._canvas.height = textureSize.height;
  10509. this.releaseInternalTexture();
  10510. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  10511. };
  10512. DynamicTexture.prototype.getContext = function () {
  10513. return this._context;
  10514. };
  10515. DynamicTexture.prototype.update = function (invertY) {
  10516. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  10517. };
  10518. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  10519. var size = this.getSize();
  10520. if (clearColor) {
  10521. this._context.fillStyle = clearColor;
  10522. this._context.fillRect(0, 0, size.width, size.height);
  10523. }
  10524. this._context.font = font;
  10525. if (x === null) {
  10526. var textSize = this._context.measureText(text);
  10527. x = (size.width - textSize.width) / 2;
  10528. }
  10529. this._context.fillStyle = color;
  10530. this._context.fillText(text, x, y);
  10531. this.update(invertY);
  10532. };
  10533. DynamicTexture.prototype.clone = function () {
  10534. var textureSize = this.getSize();
  10535. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10536. newTexture.hasAlpha = this.hasAlpha;
  10537. newTexture.level = this.level;
  10538. newTexture.wrapU = this.wrapU;
  10539. newTexture.wrapV = this.wrapV;
  10540. return newTexture;
  10541. };
  10542. return DynamicTexture;
  10543. })(BABYLON.Texture);
  10544. BABYLON.DynamicTexture = DynamicTexture;
  10545. })(BABYLON || (BABYLON = {}));
  10546. var __extends = this.__extends || function (d, b) {
  10547. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10548. function __() { this.constructor = d; }
  10549. __.prototype = b.prototype;
  10550. d.prototype = new __();
  10551. };
  10552. var BABYLON;
  10553. (function (BABYLON) {
  10554. var VideoTexture = (function (_super) {
  10555. __extends(VideoTexture, _super);
  10556. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  10557. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10558. var _this = this;
  10559. _super.call(this, null, scene, !generateMipMaps, invertY);
  10560. this._autoLaunch = true;
  10561. this.name = name;
  10562. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  10563. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  10564. var requiredWidth = size.width || size;
  10565. var requiredHeight = size.height || size;
  10566. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  10567. var textureSize = this.getSize();
  10568. this.video = document.createElement("video");
  10569. this.video.width = textureSize.width;
  10570. this.video.height = textureSize.height;
  10571. this.video.autoplay = false;
  10572. this.video.loop = true;
  10573. this.video.addEventListener("canplaythrough", function () {
  10574. if (_this._texture) {
  10575. _this._texture.isReady = true;
  10576. }
  10577. });
  10578. urls.forEach(function (url) {
  10579. var source = document.createElement("source");
  10580. source.src = url;
  10581. _this.video.appendChild(source);
  10582. });
  10583. this._lastUpdate = BABYLON.Tools.Now;
  10584. }
  10585. VideoTexture.prototype.update = function () {
  10586. if (this._autoLaunch) {
  10587. this._autoLaunch = false;
  10588. this.video.play();
  10589. }
  10590. var now = BABYLON.Tools.Now;
  10591. if (now - this._lastUpdate < 15) {
  10592. return false;
  10593. }
  10594. this._lastUpdate = now;
  10595. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  10596. return true;
  10597. };
  10598. return VideoTexture;
  10599. })(BABYLON.Texture);
  10600. BABYLON.VideoTexture = VideoTexture;
  10601. })(BABYLON || (BABYLON = {}));
  10602. var BABYLON;
  10603. (function (BABYLON) {
  10604. var EffectFallbacks = (function () {
  10605. function EffectFallbacks() {
  10606. this._defines = {};
  10607. this._currentRank = 32;
  10608. this._maxRank = -1;
  10609. }
  10610. EffectFallbacks.prototype.addFallback = function (rank, define) {
  10611. if (!this._defines[rank]) {
  10612. if (rank < this._currentRank) {
  10613. this._currentRank = rank;
  10614. }
  10615. if (rank > this._maxRank) {
  10616. this._maxRank = rank;
  10617. }
  10618. this._defines[rank] = new Array();
  10619. }
  10620. this._defines[rank].push(define);
  10621. };
  10622. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  10623. get: function () {
  10624. return this._currentRank <= this._maxRank;
  10625. },
  10626. enumerable: true,
  10627. configurable: true
  10628. });
  10629. EffectFallbacks.prototype.reduce = function (currentDefines) {
  10630. var currentFallbacks = this._defines[this._currentRank];
  10631. for (var index = 0; index < currentFallbacks.length; index++) {
  10632. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  10633. }
  10634. this._currentRank++;
  10635. return currentDefines;
  10636. };
  10637. return EffectFallbacks;
  10638. })();
  10639. BABYLON.EffectFallbacks = EffectFallbacks;
  10640. var Effect = (function () {
  10641. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  10642. var _this = this;
  10643. this._isReady = false;
  10644. this._compilationError = "";
  10645. this._valueCache = [];
  10646. this._engine = engine;
  10647. this.name = baseName;
  10648. this.defines = defines;
  10649. this._uniformsNames = uniformsNames.concat(samplers);
  10650. this._samplers = samplers;
  10651. this._attributesNames = attributesNames;
  10652. this.onError = onError;
  10653. this.onCompiled = onCompiled;
  10654. var vertexSource;
  10655. var fragmentSource;
  10656. if (baseName.vertexElement) {
  10657. vertexSource = document.getElementById(baseName.vertexElement);
  10658. if (!vertexSource) {
  10659. vertexSource = baseName.vertexElement;
  10660. }
  10661. } else {
  10662. vertexSource = baseName.vertex || baseName;
  10663. }
  10664. if (baseName.fragmentElement) {
  10665. fragmentSource = document.getElementById(baseName.fragmentElement);
  10666. if (!fragmentSource) {
  10667. fragmentSource = baseName.fragmentElement;
  10668. }
  10669. } else {
  10670. fragmentSource = baseName.fragment || baseName;
  10671. }
  10672. this._loadVertexShader(vertexSource, function (vertexCode) {
  10673. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  10674. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  10675. });
  10676. });
  10677. }
  10678. Effect.prototype.isReady = function () {
  10679. return this._isReady;
  10680. };
  10681. Effect.prototype.getProgram = function () {
  10682. return this._program;
  10683. };
  10684. Effect.prototype.getAttributesNames = function () {
  10685. return this._attributesNames;
  10686. };
  10687. Effect.prototype.getAttributeLocation = function (index) {
  10688. return this._attributes[index];
  10689. };
  10690. Effect.prototype.getAttributeLocationByName = function (name) {
  10691. var index = this._attributesNames.indexOf(name);
  10692. return this._attributes[index];
  10693. };
  10694. Effect.prototype.getAttributesCount = function () {
  10695. return this._attributes.length;
  10696. };
  10697. Effect.prototype.getUniformIndex = function (uniformName) {
  10698. return this._uniformsNames.indexOf(uniformName);
  10699. };
  10700. Effect.prototype.getUniform = function (uniformName) {
  10701. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  10702. };
  10703. Effect.prototype.getSamplers = function () {
  10704. return this._samplers;
  10705. };
  10706. Effect.prototype.getCompilationError = function () {
  10707. return this._compilationError;
  10708. };
  10709. Effect.prototype._loadVertexShader = function (vertex, callback) {
  10710. if (vertex instanceof HTMLElement) {
  10711. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  10712. callback(vertexCode);
  10713. return;
  10714. }
  10715. if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
  10716. callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
  10717. return;
  10718. }
  10719. var vertexShaderUrl;
  10720. if (vertex[0] === ".") {
  10721. vertexShaderUrl = vertex;
  10722. } else {
  10723. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  10724. }
  10725. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  10726. };
  10727. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  10728. if (fragment instanceof HTMLElement) {
  10729. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  10730. callback(fragmentCode);
  10731. return;
  10732. }
  10733. if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
  10734. callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
  10735. return;
  10736. }
  10737. if (BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]) {
  10738. callback(BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]);
  10739. return;
  10740. }
  10741. var fragmentShaderUrl;
  10742. if (fragment[0] === ".") {
  10743. fragmentShaderUrl = fragment;
  10744. } else {
  10745. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  10746. }
  10747. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  10748. };
  10749. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  10750. try {
  10751. var engine = this._engine;
  10752. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  10753. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  10754. this._attributes = engine.getAttributes(this._program, attributesNames);
  10755. for (var index = 0; index < this._samplers.length; index++) {
  10756. var sampler = this.getUniform(this._samplers[index]);
  10757. if (sampler == null) {
  10758. this._samplers.splice(index, 1);
  10759. index--;
  10760. }
  10761. }
  10762. engine.bindSamplers(this);
  10763. this._isReady = true;
  10764. if (this.onCompiled) {
  10765. this.onCompiled(this);
  10766. }
  10767. } catch (e) {
  10768. if (fallbacks && fallbacks.isMoreFallbacks) {
  10769. defines = fallbacks.reduce(defines);
  10770. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  10771. } else {
  10772. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  10773. BABYLON.Tools.Error("Defines: " + defines);
  10774. BABYLON.Tools.Error("Error: " + e.message);
  10775. this._compilationError = e.message;
  10776. if (this.onError) {
  10777. this.onError(this, this._compilationError);
  10778. }
  10779. }
  10780. }
  10781. };
  10782. Effect.prototype._bindTexture = function (channel, texture) {
  10783. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  10784. };
  10785. Effect.prototype.setTexture = function (channel, texture) {
  10786. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  10787. };
  10788. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10789. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  10790. };
  10791. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  10792. if (!this._valueCache[uniformName]) {
  10793. this._valueCache[uniformName] = [x, y];
  10794. return;
  10795. }
  10796. this._valueCache[uniformName][0] = x;
  10797. this._valueCache[uniformName][1] = y;
  10798. };
  10799. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  10800. if (!this._valueCache[uniformName]) {
  10801. this._valueCache[uniformName] = [x, y, z];
  10802. return;
  10803. }
  10804. this._valueCache[uniformName][0] = x;
  10805. this._valueCache[uniformName][1] = y;
  10806. this._valueCache[uniformName][2] = z;
  10807. };
  10808. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  10809. if (!this._valueCache[uniformName]) {
  10810. this._valueCache[uniformName] = [x, y, z, w];
  10811. return;
  10812. }
  10813. this._valueCache[uniformName][0] = x;
  10814. this._valueCache[uniformName][1] = y;
  10815. this._valueCache[uniformName][2] = z;
  10816. this._valueCache[uniformName][3] = w;
  10817. };
  10818. Effect.prototype.setArray = function (uniformName, array) {
  10819. this._engine.setArray(this.getUniform(uniformName), array);
  10820. return this;
  10821. };
  10822. Effect.prototype.setMatrices = function (uniformName, matrices) {
  10823. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  10824. return this;
  10825. };
  10826. Effect.prototype.setMatrix = function (uniformName, matrix) {
  10827. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  10828. return this;
  10829. };
  10830. Effect.prototype.setFloat = function (uniformName, value) {
  10831. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  10832. return this;
  10833. this._valueCache[uniformName] = value;
  10834. this._engine.setFloat(this.getUniform(uniformName), value);
  10835. return this;
  10836. };
  10837. Effect.prototype.setBool = function (uniformName, bool) {
  10838. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  10839. return this;
  10840. this._valueCache[uniformName] = bool;
  10841. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  10842. return this;
  10843. };
  10844. Effect.prototype.setVector2 = function (uniformName, vector2) {
  10845. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector2.x && this._valueCache[uniformName][1] == vector2.y)
  10846. return this;
  10847. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  10848. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  10849. return this;
  10850. };
  10851. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  10852. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y)
  10853. return this;
  10854. this._cacheFloat2(uniformName, x, y);
  10855. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  10856. return this;
  10857. };
  10858. Effect.prototype.setVector3 = function (uniformName, vector3) {
  10859. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector3.x && this._valueCache[uniformName][1] == vector3.y && this._valueCache[uniformName][2] == vector3.z)
  10860. return this;
  10861. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  10862. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  10863. return this;
  10864. };
  10865. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  10866. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z)
  10867. return this;
  10868. this._cacheFloat3(uniformName, x, y, z);
  10869. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  10870. return this;
  10871. };
  10872. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  10873. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z && this._valueCache[uniformName][3] == w)
  10874. return this;
  10875. this._cacheFloat4(uniformName, x, y, z, w);
  10876. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  10877. return this;
  10878. };
  10879. Effect.prototype.setColor3 = function (uniformName, color3) {
  10880. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b)
  10881. return this;
  10882. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  10883. this._engine.setColor3(this.getUniform(uniformName), color3);
  10884. return this;
  10885. };
  10886. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  10887. 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)
  10888. return this;
  10889. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  10890. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  10891. return this;
  10892. };
  10893. 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}",
  10894. 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}",
  10895. 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}",
  10896. cloudPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform float iGlobalTime;\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 alpha;\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\n vec2 p = vUV * 12.0;\n vec3 c = mix(vec3(0.15, 0.68, 1.0), vec3(1,1,1), fbm(p));\n gl_FragColor = vec4(c, 1);\n\n}",
  10897. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  10898. 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}",
  10899. 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}",
  10900. 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 vec3 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform float darkness0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform float darkness1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform float darkness2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform float darkness3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / 1500.0)) < depth.z) visibility -= 0.2;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz * vBumpInfos.y;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW, -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 diffuseColor *= vColor;\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 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}",
  10901. 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 vec3 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 vec3 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 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#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n finalWorld = world;\n#endif\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}",
  10902. 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}",
  10903. 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}",
  10904. firePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform float iGlobalTime;\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 alpha;\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\n vec2 p = vUV * 8.0;\n float q = fbm(p - iGlobalTime * 0.1);\n vec2 r = vec2(fbm(p + q + iGlobalTime * speed.x - p.x - p.y), fbm(p + q - iGlobalTime * speed.y));\n vec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\n gl_FragColor = vec4(c * cos(shift * vUV.y), alpha);\n\n}",
  10905. 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}",
  10906. 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}",
  10907. 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}",
  10908. 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 vec3 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 diffuseColor *= vColor;\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 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}",
  10909. 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 vec3 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 vec3 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}",
  10910. 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}",
  10911. 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}",
  10912. 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}",
  10913. outlinePixelShader:"precision highp float;\n\nuniform vec3 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 = vec4(color, 1.);\n}",
  10914. 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}",
  10915. 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}",
  10916. 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}",
  10917. 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}",
  10918. 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}",
  10919. 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}",
  10920. 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}",
  10921. 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}",
  10922. 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}",
  10923. 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}",
  10924. 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}",
  10925. woodPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition; \nvarying vec2 vUV; \n\nuniform float ampScale;\nuniform float ringScale;\nuniform vec3 woodColor1;\nuniform vec3 woodColor2;\n\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\n vec2 positionWood = vPosition;\n float r = ringScale * sqrt(dot(positionWood.xy, positionWood.xy));\n r = r + fbm(vPosition);\n r = r - floor(r);\n r = smoothstep(0.0, 0.8, r) - smoothstep(0.8, 1.0, r);\n\n gl_FragColor = vec4(mix(woodColor1, woodColor2, r), 1.0);\n}",
  10926. };
  10927. return Effect;
  10928. })();
  10929. BABYLON.Effect = Effect;
  10930. })(BABYLON || (BABYLON = {}));
  10931. var BABYLON;
  10932. (function (BABYLON) {
  10933. var Material = (function () {
  10934. function Material(name, scene, doNotAdd) {
  10935. this.name = name;
  10936. this.checkReadyOnEveryCall = true;
  10937. this.checkReadyOnlyOnce = false;
  10938. this.state = "";
  10939. this.alpha = 1.0;
  10940. this.backFaceCulling = true;
  10941. this._wasPreviouslyReady = false;
  10942. this._fillMode = Material.TriangleFillMode;
  10943. this.pointSize = 1.0;
  10944. this.id = name;
  10945. this._scene = scene;
  10946. if (!doNotAdd) {
  10947. scene.materials.push(this);
  10948. }
  10949. }
  10950. Object.defineProperty(Material, "TriangleFillMode", {
  10951. get: function () {
  10952. return Material._TriangleFillMode;
  10953. },
  10954. enumerable: true,
  10955. configurable: true
  10956. });
  10957. Object.defineProperty(Material, "WireFrameFillMode", {
  10958. get: function () {
  10959. return Material._WireFrameFillMode;
  10960. },
  10961. enumerable: true,
  10962. configurable: true
  10963. });
  10964. Object.defineProperty(Material, "PointFillMode", {
  10965. get: function () {
  10966. return Material._PointFillMode;
  10967. },
  10968. enumerable: true,
  10969. configurable: true
  10970. });
  10971. Object.defineProperty(Material.prototype, "wireframe", {
  10972. get: function () {
  10973. return this._fillMode === Material.WireFrameFillMode;
  10974. },
  10975. set: function (value) {
  10976. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  10977. },
  10978. enumerable: true,
  10979. configurable: true
  10980. });
  10981. Object.defineProperty(Material.prototype, "pointsCloud", {
  10982. get: function () {
  10983. return this._fillMode === Material.PointFillMode;
  10984. },
  10985. set: function (value) {
  10986. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  10987. },
  10988. enumerable: true,
  10989. configurable: true
  10990. });
  10991. Object.defineProperty(Material.prototype, "fillMode", {
  10992. get: function () {
  10993. return this._fillMode;
  10994. },
  10995. set: function (value) {
  10996. this._fillMode = value;
  10997. },
  10998. enumerable: true,
  10999. configurable: true
  11000. });
  11001. Material.prototype.isReady = function (mesh, useInstances) {
  11002. return true;
  11003. };
  11004. Material.prototype.getEffect = function () {
  11005. return this._effect;
  11006. };
  11007. Material.prototype.getScene = function () {
  11008. return this._scene;
  11009. };
  11010. Material.prototype.needAlphaBlending = function () {
  11011. return (this.alpha < 1.0);
  11012. };
  11013. Material.prototype.needAlphaTesting = function () {
  11014. return false;
  11015. };
  11016. Material.prototype.getAlphaTestTexture = function () {
  11017. return null;
  11018. };
  11019. Material.prototype.trackCreation = function (onCompiled, onError) {
  11020. };
  11021. Material.prototype._preBind = function () {
  11022. var engine = this._scene.getEngine();
  11023. engine.enableEffect(this._effect);
  11024. engine.setState(this.backFaceCulling);
  11025. };
  11026. Material.prototype.bind = function (world, mesh) {
  11027. };
  11028. Material.prototype.bindOnlyWorldMatrix = function (world) {
  11029. };
  11030. Material.prototype.unbind = function () {
  11031. };
  11032. Material.prototype.dispose = function (forceDisposeEffect) {
  11033. var index = this._scene.materials.indexOf(this);
  11034. this._scene.materials.splice(index, 1);
  11035. if (forceDisposeEffect && this._effect) {
  11036. this._scene.getEngine()._releaseEffect(this._effect);
  11037. this._effect = null;
  11038. }
  11039. if (this.onDispose) {
  11040. this.onDispose();
  11041. }
  11042. };
  11043. Material._TriangleFillMode = 0;
  11044. Material._WireFrameFillMode = 1;
  11045. Material._PointFillMode = 2;
  11046. return Material;
  11047. })();
  11048. BABYLON.Material = Material;
  11049. })(BABYLON || (BABYLON = {}));
  11050. var __extends = this.__extends || function (d, b) {
  11051. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11052. function __() { this.constructor = d; }
  11053. __.prototype = b.prototype;
  11054. d.prototype = new __();
  11055. };
  11056. var BABYLON;
  11057. (function (BABYLON) {
  11058. var maxSimultaneousLights = 4;
  11059. var FresnelParameters = (function () {
  11060. function FresnelParameters() {
  11061. this.isEnabled = true;
  11062. this.leftColor = BABYLON.Color3.White();
  11063. this.rightColor = BABYLON.Color3.Black();
  11064. this.bias = 0;
  11065. this.power = 1;
  11066. }
  11067. return FresnelParameters;
  11068. })();
  11069. BABYLON.FresnelParameters = FresnelParameters;
  11070. var StandardMaterial = (function (_super) {
  11071. __extends(StandardMaterial, _super);
  11072. function StandardMaterial(name, scene) {
  11073. var _this = this;
  11074. _super.call(this, name, scene);
  11075. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11076. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  11077. this.specularColor = new BABYLON.Color3(1, 1, 1);
  11078. this.specularPower = 64;
  11079. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  11080. this.useAlphaFromDiffuseTexture = false;
  11081. this.useSpecularOverAlpha = true;
  11082. this.fogEnabled = true;
  11083. this._cachedDefines = null;
  11084. this._renderTargets = new BABYLON.SmartArray(16);
  11085. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  11086. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  11087. this._scaledDiffuse = new BABYLON.Color3();
  11088. this._scaledSpecular = new BABYLON.Color3();
  11089. this.getRenderTargetTextures = function () {
  11090. _this._renderTargets.reset();
  11091. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  11092. _this._renderTargets.push(_this.reflectionTexture);
  11093. }
  11094. return _this._renderTargets;
  11095. };
  11096. }
  11097. StandardMaterial.prototype.needAlphaBlending = function () {
  11098. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  11099. };
  11100. StandardMaterial.prototype.needAlphaTesting = function () {
  11101. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  11102. };
  11103. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  11104. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  11105. };
  11106. StandardMaterial.prototype.getAlphaTestTexture = function () {
  11107. return this.diffuseTexture;
  11108. };
  11109. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  11110. if (this.checkReadyOnlyOnce) {
  11111. if (this._wasPreviouslyReady) {
  11112. return true;
  11113. }
  11114. }
  11115. var scene = this.getScene();
  11116. if (!this.checkReadyOnEveryCall) {
  11117. if (this._renderId === scene.getRenderId()) {
  11118. return true;
  11119. }
  11120. }
  11121. var engine = scene.getEngine();
  11122. var defines = [];
  11123. var fallbacks = new BABYLON.EffectFallbacks();
  11124. if (scene.texturesEnabled) {
  11125. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  11126. if (!this.diffuseTexture.isReady()) {
  11127. return false;
  11128. } else {
  11129. defines.push("#define DIFFUSE");
  11130. }
  11131. }
  11132. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  11133. if (!this.ambientTexture.isReady()) {
  11134. return false;
  11135. } else {
  11136. defines.push("#define AMBIENT");
  11137. }
  11138. }
  11139. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  11140. if (!this.opacityTexture.isReady()) {
  11141. return false;
  11142. } else {
  11143. defines.push("#define OPACITY");
  11144. if (this.opacityTexture.getAlphaFromRGB) {
  11145. defines.push("#define OPACITYRGB");
  11146. }
  11147. }
  11148. }
  11149. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  11150. if (!this.reflectionTexture.isReady()) {
  11151. return false;
  11152. } else {
  11153. defines.push("#define REFLECTION");
  11154. fallbacks.addFallback(0, "REFLECTION");
  11155. }
  11156. }
  11157. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  11158. if (!this.emissiveTexture.isReady()) {
  11159. return false;
  11160. } else {
  11161. defines.push("#define EMISSIVE");
  11162. }
  11163. }
  11164. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  11165. if (!this.specularTexture.isReady()) {
  11166. return false;
  11167. } else {
  11168. defines.push("#define SPECULAR");
  11169. fallbacks.addFallback(0, "SPECULAR");
  11170. }
  11171. }
  11172. }
  11173. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  11174. if (!this.bumpTexture.isReady()) {
  11175. return false;
  11176. } else {
  11177. defines.push("#define BUMP");
  11178. fallbacks.addFallback(0, "BUMP");
  11179. }
  11180. }
  11181. if (this.useSpecularOverAlpha) {
  11182. defines.push("#define SPECULAROVERALPHA");
  11183. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  11184. }
  11185. if (scene.clipPlane) {
  11186. defines.push("#define CLIPPLANE");
  11187. }
  11188. if (engine.getAlphaTesting()) {
  11189. defines.push("#define ALPHATEST");
  11190. }
  11191. if (this._shouldUseAlphaFromDiffuseTexture()) {
  11192. defines.push("#define ALPHAFROMDIFFUSE");
  11193. }
  11194. if (this.pointsCloud) {
  11195. defines.push("#define POINTSIZE");
  11196. }
  11197. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  11198. defines.push("#define FOG");
  11199. fallbacks.addFallback(1, "FOG");
  11200. }
  11201. var shadowsActivated = false;
  11202. var lightIndex = 0;
  11203. if (scene.lightsEnabled) {
  11204. for (var index = 0; index < scene.lights.length; index++) {
  11205. var light = scene.lights[index];
  11206. if (!light.isEnabled()) {
  11207. continue;
  11208. }
  11209. if (light._excludedMeshesIds.length > 0) {
  11210. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  11211. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  11212. if (excludedMesh) {
  11213. light.excludedMeshes.push(excludedMesh);
  11214. }
  11215. }
  11216. light._excludedMeshesIds = [];
  11217. }
  11218. if (light._includedOnlyMeshesIds.length > 0) {
  11219. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  11220. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  11221. if (includedOnlyMesh) {
  11222. light.includedOnlyMeshes.push(includedOnlyMesh);
  11223. }
  11224. }
  11225. light._includedOnlyMeshesIds = [];
  11226. }
  11227. if (!light.canAffectMesh(mesh)) {
  11228. continue;
  11229. }
  11230. defines.push("#define LIGHT" + lightIndex);
  11231. if (lightIndex > 0) {
  11232. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  11233. }
  11234. var type;
  11235. if (light instanceof BABYLON.SpotLight) {
  11236. type = "#define SPOTLIGHT" + lightIndex;
  11237. } else if (light instanceof BABYLON.HemisphericLight) {
  11238. type = "#define HEMILIGHT" + lightIndex;
  11239. } else {
  11240. type = "#define POINTDIRLIGHT" + lightIndex;
  11241. }
  11242. defines.push(type);
  11243. if (lightIndex > 0) {
  11244. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  11245. }
  11246. if (scene.shadowsEnabled) {
  11247. var shadowGenerator = light.getShadowGenerator();
  11248. if (mesh && mesh.receiveShadows && shadowGenerator) {
  11249. defines.push("#define SHADOW" + lightIndex);
  11250. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  11251. if (!shadowsActivated) {
  11252. defines.push("#define SHADOWS");
  11253. shadowsActivated = true;
  11254. }
  11255. if (shadowGenerator.useVarianceShadowMap) {
  11256. defines.push("#define SHADOWVSM" + lightIndex);
  11257. if (lightIndex > 0) {
  11258. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  11259. }
  11260. }
  11261. if (shadowGenerator.usePoissonSampling) {
  11262. defines.push("#define SHADOWPCF" + lightIndex);
  11263. if (lightIndex > 0) {
  11264. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  11265. }
  11266. }
  11267. }
  11268. }
  11269. lightIndex++;
  11270. if (lightIndex == maxSimultaneousLights)
  11271. break;
  11272. }
  11273. }
  11274. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  11275. var fresnelRank = 1;
  11276. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  11277. defines.push("#define DIFFUSEFRESNEL");
  11278. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  11279. fresnelRank++;
  11280. }
  11281. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  11282. defines.push("#define OPACITYFRESNEL");
  11283. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  11284. fresnelRank++;
  11285. }
  11286. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  11287. defines.push("#define REFLECTIONFRESNEL");
  11288. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  11289. fresnelRank++;
  11290. }
  11291. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  11292. defines.push("#define EMISSIVEFRESNEL");
  11293. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  11294. fresnelRank++;
  11295. }
  11296. defines.push("#define FRESNEL");
  11297. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  11298. }
  11299. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  11300. if (mesh) {
  11301. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11302. attribs.push(BABYLON.VertexBuffer.UVKind);
  11303. defines.push("#define UV1");
  11304. }
  11305. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11306. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11307. defines.push("#define UV2");
  11308. }
  11309. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  11310. attribs.push(BABYLON.VertexBuffer.ColorKind);
  11311. defines.push("#define VERTEXCOLOR");
  11312. }
  11313. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  11314. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11315. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11316. defines.push("#define BONES");
  11317. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11318. defines.push("#define BONES4");
  11319. fallbacks.addFallback(0, "BONES4");
  11320. }
  11321. if (useInstances) {
  11322. defines.push("#define INSTANCES");
  11323. attribs.push("world0");
  11324. attribs.push("world1");
  11325. attribs.push("world2");
  11326. attribs.push("world3");
  11327. }
  11328. }
  11329. var join = defines.join("\n");
  11330. if (this._cachedDefines != join) {
  11331. this._cachedDefines = join;
  11332. var shaderName = "default";
  11333. if (!scene.getEngine().getCaps().standardDerivatives) {
  11334. shaderName = "legacydefault";
  11335. }
  11336. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  11337. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  11338. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  11339. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  11340. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  11341. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  11342. "vFogInfos", "vFogColor", "pointSize",
  11343. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  11344. "mBones",
  11345. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  11346. "darkness0", "darkness1", "darkness2", "darkness3",
  11347. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  11348. ], [
  11349. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  11350. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  11351. ], join, fallbacks, this.onCompiled, this.onError);
  11352. }
  11353. if (!this._effect.isReady()) {
  11354. return false;
  11355. }
  11356. this._renderId = scene.getRenderId();
  11357. this._wasPreviouslyReady = true;
  11358. return true;
  11359. };
  11360. StandardMaterial.prototype.unbind = function () {
  11361. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  11362. this._effect.setTexture("reflection2DSampler", null);
  11363. }
  11364. };
  11365. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  11366. this._effect.setMatrix("world", world);
  11367. };
  11368. StandardMaterial.prototype.bind = function (world, mesh) {
  11369. var scene = this.getScene();
  11370. this.bindOnlyWorldMatrix(world);
  11371. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  11372. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  11373. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  11374. }
  11375. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  11376. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  11377. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  11378. }
  11379. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  11380. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  11381. }
  11382. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  11383. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  11384. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  11385. }
  11386. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  11387. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  11388. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  11389. }
  11390. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  11391. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  11392. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  11393. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  11394. }
  11395. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  11396. this._effect.setTexture("ambientSampler", this.ambientTexture);
  11397. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  11398. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  11399. }
  11400. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  11401. this._effect.setTexture("opacitySampler", this.opacityTexture);
  11402. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  11403. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  11404. }
  11405. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  11406. if (this.reflectionTexture.isCube) {
  11407. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  11408. } else {
  11409. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  11410. }
  11411. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  11412. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  11413. }
  11414. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  11415. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  11416. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  11417. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  11418. }
  11419. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  11420. this._effect.setTexture("specularSampler", this.specularTexture);
  11421. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  11422. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  11423. }
  11424. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
  11425. this._effect.setTexture("bumpSampler", this.bumpTexture);
  11426. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
  11427. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  11428. }
  11429. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  11430. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  11431. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  11432. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  11433. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  11434. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  11435. if (scene.lightsEnabled) {
  11436. var lightIndex = 0;
  11437. for (var index = 0; index < scene.lights.length; index++) {
  11438. var light = scene.lights[index];
  11439. if (!light.isEnabled()) {
  11440. continue;
  11441. }
  11442. if (!light.canAffectMesh(mesh)) {
  11443. continue;
  11444. }
  11445. if (light instanceof BABYLON.PointLight) {
  11446. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  11447. } else if (light instanceof BABYLON.DirectionalLight) {
  11448. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  11449. } else if (light instanceof BABYLON.SpotLight) {
  11450. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  11451. } else if (light instanceof BABYLON.HemisphericLight) {
  11452. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  11453. }
  11454. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  11455. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  11456. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  11457. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  11458. if (scene.shadowsEnabled) {
  11459. var shadowGenerator = light.getShadowGenerator();
  11460. if (mesh.receiveShadows && shadowGenerator) {
  11461. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  11462. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  11463. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  11464. }
  11465. }
  11466. lightIndex++;
  11467. if (lightIndex == maxSimultaneousLights)
  11468. break;
  11469. }
  11470. }
  11471. if (scene.clipPlane) {
  11472. var clipPlane = scene.clipPlane;
  11473. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  11474. }
  11475. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  11476. this._effect.setMatrix("view", scene.getViewMatrix());
  11477. }
  11478. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11479. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  11480. this._effect.setColor3("vFogColor", scene.fogColor);
  11481. }
  11482. if (this.pointsCloud) {
  11483. this._effect.setFloat("pointSize", this.pointSize);
  11484. }
  11485. };
  11486. StandardMaterial.prototype.getAnimatables = function () {
  11487. var results = [];
  11488. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  11489. results.push(this.diffuseTexture);
  11490. }
  11491. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  11492. results.push(this.ambientTexture);
  11493. }
  11494. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  11495. results.push(this.opacityTexture);
  11496. }
  11497. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  11498. results.push(this.reflectionTexture);
  11499. }
  11500. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  11501. results.push(this.emissiveTexture);
  11502. }
  11503. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  11504. results.push(this.specularTexture);
  11505. }
  11506. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  11507. results.push(this.bumpTexture);
  11508. }
  11509. return results;
  11510. };
  11511. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  11512. if (this.diffuseTexture) {
  11513. this.diffuseTexture.dispose();
  11514. }
  11515. if (this.ambientTexture) {
  11516. this.ambientTexture.dispose();
  11517. }
  11518. if (this.opacityTexture) {
  11519. this.opacityTexture.dispose();
  11520. }
  11521. if (this.reflectionTexture) {
  11522. this.reflectionTexture.dispose();
  11523. }
  11524. if (this.emissiveTexture) {
  11525. this.emissiveTexture.dispose();
  11526. }
  11527. if (this.specularTexture) {
  11528. this.specularTexture.dispose();
  11529. }
  11530. if (this.bumpTexture) {
  11531. this.bumpTexture.dispose();
  11532. }
  11533. _super.prototype.dispose.call(this, forceDisposeEffect);
  11534. };
  11535. StandardMaterial.prototype.clone = function (name) {
  11536. var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
  11537. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  11538. newStandardMaterial.alpha = this.alpha;
  11539. newStandardMaterial.fillMode = this.fillMode;
  11540. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  11541. if (this.diffuseTexture && this.diffuseTexture.clone) {
  11542. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  11543. }
  11544. if (this.ambientTexture && this.ambientTexture.clone) {
  11545. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  11546. }
  11547. if (this.opacityTexture && this.opacityTexture.clone) {
  11548. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  11549. }
  11550. if (this.reflectionTexture && this.reflectionTexture.clone) {
  11551. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  11552. }
  11553. if (this.emissiveTexture && this.emissiveTexture.clone) {
  11554. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  11555. }
  11556. if (this.specularTexture && this.specularTexture.clone) {
  11557. newStandardMaterial.specularTexture = this.specularTexture.clone();
  11558. }
  11559. if (this.bumpTexture && this.bumpTexture.clone) {
  11560. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  11561. }
  11562. newStandardMaterial.ambientColor = this.ambientColor.clone();
  11563. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  11564. newStandardMaterial.specularColor = this.specularColor.clone();
  11565. newStandardMaterial.specularPower = this.specularPower;
  11566. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  11567. return newStandardMaterial;
  11568. };
  11569. StandardMaterial.DiffuseTextureEnabled = true;
  11570. StandardMaterial.AmbientTextureEnabled = true;
  11571. StandardMaterial.OpacityTextureEnabled = true;
  11572. StandardMaterial.ReflectionTextureEnabled = true;
  11573. StandardMaterial.EmissiveTextureEnabled = true;
  11574. StandardMaterial.SpecularTextureEnabled = true;
  11575. StandardMaterial.BumpTextureEnabled = true;
  11576. return StandardMaterial;
  11577. })(BABYLON.Material);
  11578. BABYLON.StandardMaterial = StandardMaterial;
  11579. })(BABYLON || (BABYLON = {}));
  11580. var __extends = this.__extends || function (d, b) {
  11581. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11582. function __() { this.constructor = d; }
  11583. __.prototype = b.prototype;
  11584. d.prototype = new __();
  11585. };
  11586. var BABYLON;
  11587. (function (BABYLON) {
  11588. var MultiMaterial = (function (_super) {
  11589. __extends(MultiMaterial, _super);
  11590. function MultiMaterial(name, scene) {
  11591. _super.call(this, name, scene, true);
  11592. this.subMaterials = new Array();
  11593. scene.multiMaterials.push(this);
  11594. }
  11595. MultiMaterial.prototype.getSubMaterial = function (index) {
  11596. if (index < 0 || index >= this.subMaterials.length) {
  11597. return this.getScene().defaultMaterial;
  11598. }
  11599. return this.subMaterials[index];
  11600. };
  11601. MultiMaterial.prototype.isReady = function (mesh) {
  11602. for (var index = 0; index < this.subMaterials.length; index++) {
  11603. var subMaterial = this.subMaterials[index];
  11604. if (subMaterial) {
  11605. if (!this.subMaterials[index].isReady(mesh)) {
  11606. return false;
  11607. }
  11608. }
  11609. }
  11610. return true;
  11611. };
  11612. return MultiMaterial;
  11613. })(BABYLON.Material);
  11614. BABYLON.MultiMaterial = MultiMaterial;
  11615. })(BABYLON || (BABYLON = {}));
  11616. var BABYLON;
  11617. (function (BABYLON) {
  11618. var Database = (function () {
  11619. function Database(urlToScene, callbackManifestChecked) {
  11620. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  11621. this.callbackManifestChecked = callbackManifestChecked;
  11622. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  11623. this.db = null;
  11624. this.enableSceneOffline = false;
  11625. this.enableTexturesOffline = false;
  11626. this.manifestVersionFound = 0;
  11627. this.mustUpdateRessources = false;
  11628. this.hasReachedQuota = false;
  11629. this.checkManifestFile();
  11630. }
  11631. Database.prototype.checkManifestFile = function () {
  11632. var _this = this;
  11633. function noManifestFile() {
  11634. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  11635. that.enableSceneOffline = false;
  11636. that.enableTexturesOffline = false;
  11637. that.callbackManifestChecked(false);
  11638. }
  11639. var that = this;
  11640. var manifestURL = this.currentSceneUrl + ".manifest";
  11641. var xhr = new XMLHttpRequest();
  11642. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  11643. xhr.open("GET", manifestURLTimeStamped, true);
  11644. xhr.addEventListener("load", function () {
  11645. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  11646. try {
  11647. var manifestFile = JSON.parse(xhr.response);
  11648. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  11649. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  11650. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  11651. _this.manifestVersionFound = manifestFile.version;
  11652. }
  11653. if (_this.callbackManifestChecked) {
  11654. _this.callbackManifestChecked(true);
  11655. }
  11656. } catch (ex) {
  11657. noManifestFile();
  11658. }
  11659. } else {
  11660. noManifestFile();
  11661. }
  11662. }, false);
  11663. xhr.addEventListener("error", function (event) {
  11664. noManifestFile();
  11665. }, false);
  11666. try {
  11667. xhr.send();
  11668. } catch (ex) {
  11669. BABYLON.Tools.Error("Error on XHR send request.");
  11670. that.callbackManifestChecked(false);
  11671. }
  11672. };
  11673. Database.prototype.openAsync = function (successCallback, errorCallback) {
  11674. var _this = this;
  11675. function handleError() {
  11676. that.isSupported = false;
  11677. if (errorCallback)
  11678. errorCallback();
  11679. }
  11680. var that = this;
  11681. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  11682. this.isSupported = false;
  11683. if (errorCallback)
  11684. errorCallback();
  11685. } else {
  11686. if (!this.db) {
  11687. this.hasReachedQuota = false;
  11688. this.isSupported = true;
  11689. var request = this.idbFactory.open("babylonjs", 1);
  11690. request.onerror = function (event) {
  11691. handleError();
  11692. };
  11693. request.onblocked = function (event) {
  11694. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  11695. handleError();
  11696. };
  11697. request.onsuccess = function (event) {
  11698. _this.db = request.result;
  11699. successCallback();
  11700. };
  11701. request.onupgradeneeded = function (event) {
  11702. _this.db = (event.target).result;
  11703. try {
  11704. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  11705. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  11706. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  11707. } catch (ex) {
  11708. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  11709. handleError();
  11710. }
  11711. };
  11712. } else {
  11713. if (successCallback)
  11714. successCallback();
  11715. }
  11716. }
  11717. };
  11718. Database.prototype.loadImageFromDB = function (url, image) {
  11719. var _this = this;
  11720. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  11721. var saveAndLoadImage = function () {
  11722. if (!_this.hasReachedQuota && _this.db !== null) {
  11723. _this._saveImageIntoDBAsync(completeURL, image);
  11724. } else {
  11725. image.src = url;
  11726. }
  11727. };
  11728. if (!this.mustUpdateRessources) {
  11729. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  11730. } else {
  11731. saveAndLoadImage();
  11732. }
  11733. };
  11734. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  11735. if (this.isSupported && this.db !== null) {
  11736. var texture;
  11737. var transaction = this.db.transaction(["textures"]);
  11738. transaction.onabort = function (event) {
  11739. image.src = url;
  11740. };
  11741. transaction.oncomplete = function (event) {
  11742. var blobTextureURL;
  11743. if (texture) {
  11744. var URL = window.URL || window.webkitURL;
  11745. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  11746. image.onerror = function () {
  11747. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  11748. image.src = url;
  11749. };
  11750. image.src = blobTextureURL;
  11751. } else {
  11752. notInDBCallback();
  11753. }
  11754. };
  11755. var getRequest = transaction.objectStore("textures").get(url);
  11756. getRequest.onsuccess = function (event) {
  11757. texture = (event.target).result;
  11758. };
  11759. getRequest.onerror = function (event) {
  11760. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  11761. image.src = url;
  11762. };
  11763. } else {
  11764. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11765. image.src = url;
  11766. }
  11767. };
  11768. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  11769. var _this = this;
  11770. if (this.isSupported) {
  11771. var generateBlobUrl = function () {
  11772. var blobTextureURL;
  11773. if (blob) {
  11774. var URL = window.URL || window.webkitURL;
  11775. try {
  11776. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  11777. } catch (ex) {
  11778. blobTextureURL = URL.createObjectURL(blob);
  11779. }
  11780. }
  11781. image.src = blobTextureURL;
  11782. };
  11783. if (BABYLON.Database.isUASupportingBlobStorage) {
  11784. var xhr = new XMLHttpRequest(), blob;
  11785. xhr.open("GET", url, true);
  11786. xhr.responseType = "blob";
  11787. xhr.addEventListener("load", function () {
  11788. if (xhr.status === 200) {
  11789. blob = xhr.response;
  11790. var transaction = _this.db.transaction(["textures"], "readwrite");
  11791. transaction.onabort = function (event) {
  11792. try {
  11793. if (event.srcElement.error.name === "QuotaExceededError") {
  11794. this.hasReachedQuota = true;
  11795. }
  11796. } catch (ex) {
  11797. }
  11798. generateBlobUrl();
  11799. };
  11800. transaction.oncomplete = function (event) {
  11801. generateBlobUrl();
  11802. };
  11803. var newTexture = { textureUrl: url, data: blob };
  11804. try {
  11805. var addRequest = transaction.objectStore("textures").put(newTexture);
  11806. addRequest.onsuccess = function (event) {
  11807. };
  11808. addRequest.onerror = function (event) {
  11809. generateBlobUrl();
  11810. };
  11811. } catch (ex) {
  11812. if (ex.code === 25) {
  11813. BABYLON.Database.isUASupportingBlobStorage = false;
  11814. }
  11815. image.src = url;
  11816. }
  11817. } else {
  11818. image.src = url;
  11819. }
  11820. }, false);
  11821. xhr.addEventListener("error", function (event) {
  11822. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  11823. image.src = url;
  11824. }, false);
  11825. xhr.send();
  11826. } else {
  11827. image.src = url;
  11828. }
  11829. } else {
  11830. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11831. image.src = url;
  11832. }
  11833. };
  11834. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  11835. var _this = this;
  11836. var updateVersion = function (event) {
  11837. _this._saveVersionIntoDBAsync(url, versionLoaded);
  11838. };
  11839. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  11840. };
  11841. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  11842. var _this = this;
  11843. if (this.isSupported) {
  11844. var version;
  11845. try {
  11846. var transaction = this.db.transaction(["versions"]);
  11847. transaction.oncomplete = function (event) {
  11848. if (version) {
  11849. if (_this.manifestVersionFound > version.data) {
  11850. _this.mustUpdateRessources = true;
  11851. updateInDBCallback();
  11852. } else {
  11853. callback(version.data);
  11854. }
  11855. } else {
  11856. _this.mustUpdateRessources = true;
  11857. updateInDBCallback();
  11858. }
  11859. };
  11860. transaction.onabort = function (event) {
  11861. callback(-1);
  11862. };
  11863. var getRequest = transaction.objectStore("versions").get(url);
  11864. getRequest.onsuccess = function (event) {
  11865. version = (event.target).result;
  11866. };
  11867. getRequest.onerror = function (event) {
  11868. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  11869. callback(-1);
  11870. };
  11871. } catch (ex) {
  11872. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  11873. callback(-1);
  11874. }
  11875. } else {
  11876. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11877. callback(-1);
  11878. }
  11879. };
  11880. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  11881. var _this = this;
  11882. if (this.isSupported && !this.hasReachedQuota) {
  11883. try {
  11884. var transaction = this.db.transaction(["versions"], "readwrite");
  11885. transaction.onabort = function (event) {
  11886. try {
  11887. if (event.srcElement.error.name === "QuotaExceededError") {
  11888. _this.hasReachedQuota = true;
  11889. }
  11890. } catch (ex) {
  11891. }
  11892. callback(-1);
  11893. };
  11894. transaction.oncomplete = function (event) {
  11895. callback(_this.manifestVersionFound);
  11896. };
  11897. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  11898. var addRequest = transaction.objectStore("versions").put(newVersion);
  11899. addRequest.onsuccess = function (event) {
  11900. };
  11901. addRequest.onerror = function (event) {
  11902. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  11903. };
  11904. } catch (ex) {
  11905. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  11906. callback(-1);
  11907. }
  11908. } else {
  11909. callback(-1);
  11910. }
  11911. };
  11912. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  11913. var _this = this;
  11914. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  11915. var saveAndLoadFile = function (event) {
  11916. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  11917. };
  11918. this._checkVersionFromDB(completeUrl, function (version) {
  11919. if (version !== -1) {
  11920. if (!_this.mustUpdateRessources) {
  11921. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  11922. } else {
  11923. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  11924. }
  11925. } else {
  11926. errorCallback();
  11927. }
  11928. });
  11929. };
  11930. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  11931. if (this.isSupported) {
  11932. var targetStore;
  11933. if (url.indexOf(".babylon") !== -1) {
  11934. targetStore = "scenes";
  11935. } else {
  11936. targetStore = "textures";
  11937. }
  11938. var file;
  11939. var transaction = this.db.transaction([targetStore]);
  11940. transaction.oncomplete = function (event) {
  11941. if (file) {
  11942. callback(file.data);
  11943. } else {
  11944. notInDBCallback();
  11945. }
  11946. };
  11947. transaction.onabort = function (event) {
  11948. notInDBCallback();
  11949. };
  11950. var getRequest = transaction.objectStore(targetStore).get(url);
  11951. getRequest.onsuccess = function (event) {
  11952. file = (event.target).result;
  11953. };
  11954. getRequest.onerror = function (event) {
  11955. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  11956. notInDBCallback();
  11957. };
  11958. } else {
  11959. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11960. callback();
  11961. }
  11962. };
  11963. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  11964. var _this = this;
  11965. if (this.isSupported) {
  11966. var targetStore;
  11967. if (url.indexOf(".babylon") !== -1) {
  11968. targetStore = "scenes";
  11969. } else {
  11970. targetStore = "textures";
  11971. }
  11972. var xhr = new XMLHttpRequest(), fileData;
  11973. xhr.open("GET", url, true);
  11974. if (useArrayBuffer) {
  11975. xhr.responseType = "arraybuffer";
  11976. }
  11977. xhr.onprogress = progressCallback;
  11978. xhr.addEventListener("load", function () {
  11979. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  11980. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  11981. if (!_this.hasReachedQuota) {
  11982. var transaction = _this.db.transaction([targetStore], "readwrite");
  11983. transaction.onabort = function (event) {
  11984. try {
  11985. if (event.srcElement.error.name === "QuotaExceededError") {
  11986. this.hasReachedQuota = true;
  11987. }
  11988. } catch (ex) {
  11989. }
  11990. callback(fileData);
  11991. };
  11992. transaction.oncomplete = function (event) {
  11993. callback(fileData);
  11994. };
  11995. var newFile;
  11996. if (targetStore === "scenes") {
  11997. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  11998. } else {
  11999. newFile = { textureUrl: url, data: fileData };
  12000. }
  12001. try {
  12002. var addRequest = transaction.objectStore(targetStore).put(newFile);
  12003. addRequest.onsuccess = function (event) {
  12004. };
  12005. addRequest.onerror = function (event) {
  12006. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  12007. };
  12008. } catch (ex) {
  12009. callback(fileData);
  12010. }
  12011. } else {
  12012. callback(fileData);
  12013. }
  12014. } else {
  12015. callback();
  12016. }
  12017. }, false);
  12018. xhr.addEventListener("error", function (event) {
  12019. BABYLON.Tools.Error("error on XHR request.");
  12020. callback();
  12021. }, false);
  12022. xhr.send();
  12023. } else {
  12024. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12025. callback();
  12026. }
  12027. };
  12028. Database.isUASupportingBlobStorage = true;
  12029. Database.parseURL = function (url) {
  12030. var a = document.createElement('a');
  12031. a.href = url;
  12032. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  12033. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  12034. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  12035. return absLocation;
  12036. };
  12037. Database.ReturnFullUrlLocation = function (url) {
  12038. if (url.indexOf("http:/") === -1) {
  12039. return (BABYLON.Database.parseURL(window.location.href) + url);
  12040. } else {
  12041. return url;
  12042. }
  12043. };
  12044. return Database;
  12045. })();
  12046. BABYLON.Database = Database;
  12047. })(BABYLON || (BABYLON = {}));
  12048. var BABYLON;
  12049. (function (BABYLON) {
  12050. var SpriteManager = (function () {
  12051. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  12052. this.name = name;
  12053. this.cellSize = cellSize;
  12054. this.sprites = new Array();
  12055. this.renderingGroupId = 0;
  12056. this.fogEnabled = true;
  12057. this._vertexDeclaration = [3, 4, 4, 4];
  12058. this._vertexStrideSize = 15 * 4;
  12059. this._capacity = capacity;
  12060. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  12061. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12062. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12063. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  12064. this._scene = scene;
  12065. this._scene.spriteManagers.push(this);
  12066. this._vertexDeclaration = [3, 4, 4, 4];
  12067. this._vertexStrideSize = 15 * 4;
  12068. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  12069. var indices = [];
  12070. var index = 0;
  12071. for (var count = 0; count < capacity; count++) {
  12072. indices.push(index);
  12073. indices.push(index + 1);
  12074. indices.push(index + 2);
  12075. indices.push(index);
  12076. indices.push(index + 2);
  12077. indices.push(index + 3);
  12078. index += 4;
  12079. }
  12080. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12081. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  12082. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  12083. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  12084. }
  12085. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  12086. var arrayOffset = index * 15;
  12087. if (offsetX == 0)
  12088. offsetX = this._epsilon;
  12089. else if (offsetX == 1)
  12090. offsetX = 1 - this._epsilon;
  12091. if (offsetY == 0)
  12092. offsetY = this._epsilon;
  12093. else if (offsetY == 1)
  12094. offsetY = 1 - this._epsilon;
  12095. this._vertices[arrayOffset] = sprite.position.x;
  12096. this._vertices[arrayOffset + 1] = sprite.position.y;
  12097. this._vertices[arrayOffset + 2] = sprite.position.z;
  12098. this._vertices[arrayOffset + 3] = sprite.angle;
  12099. this._vertices[arrayOffset + 4] = sprite.size;
  12100. this._vertices[arrayOffset + 5] = offsetX;
  12101. this._vertices[arrayOffset + 6] = offsetY;
  12102. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  12103. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  12104. var offset = (sprite.cellIndex / rowSize) >> 0;
  12105. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  12106. this._vertices[arrayOffset + 10] = offset;
  12107. this._vertices[arrayOffset + 11] = sprite.color.r;
  12108. this._vertices[arrayOffset + 12] = sprite.color.g;
  12109. this._vertices[arrayOffset + 13] = sprite.color.b;
  12110. this._vertices[arrayOffset + 14] = sprite.color.a;
  12111. };
  12112. SpriteManager.prototype.render = function () {
  12113. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  12114. return;
  12115. var engine = this._scene.getEngine();
  12116. var baseSize = this._spriteTexture.getBaseSize();
  12117. var deltaTime = BABYLON.Tools.GetDeltaTime();
  12118. var max = Math.min(this._capacity, this.sprites.length);
  12119. var rowSize = baseSize.width / this.cellSize;
  12120. var offset = 0;
  12121. for (var index = 0; index < max; index++) {
  12122. var sprite = this.sprites[index];
  12123. if (!sprite) {
  12124. continue;
  12125. }
  12126. sprite._animate(deltaTime);
  12127. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  12128. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  12129. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  12130. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  12131. }
  12132. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
  12133. var effect = this._effectBase;
  12134. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12135. effect = this._effectFog;
  12136. }
  12137. engine.enableEffect(effect);
  12138. var viewMatrix = this._scene.getViewMatrix();
  12139. effect.setTexture("diffuseSampler", this._spriteTexture);
  12140. effect.setMatrix("view", viewMatrix);
  12141. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  12142. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  12143. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12144. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  12145. effect.setColor3("vFogColor", this._scene.fogColor);
  12146. }
  12147. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12148. effect.setBool("alphaTest", true);
  12149. engine.setColorWrite(false);
  12150. engine.draw(true, 0, max * 6);
  12151. engine.setColorWrite(true);
  12152. effect.setBool("alphaTest", false);
  12153. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12154. engine.draw(true, 0, max * 6);
  12155. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12156. };
  12157. SpriteManager.prototype.dispose = function () {
  12158. if (this._vertexBuffer) {
  12159. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12160. this._vertexBuffer = null;
  12161. }
  12162. if (this._indexBuffer) {
  12163. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12164. this._indexBuffer = null;
  12165. }
  12166. if (this._spriteTexture) {
  12167. this._spriteTexture.dispose();
  12168. this._spriteTexture = null;
  12169. }
  12170. var index = this._scene.spriteManagers.indexOf(this);
  12171. this._scene.spriteManagers.splice(index, 1);
  12172. if (this.onDispose) {
  12173. this.onDispose();
  12174. }
  12175. };
  12176. return SpriteManager;
  12177. })();
  12178. BABYLON.SpriteManager = SpriteManager;
  12179. })(BABYLON || (BABYLON = {}));
  12180. var BABYLON;
  12181. (function (BABYLON) {
  12182. var Sprite = (function () {
  12183. function Sprite(name, manager) {
  12184. this.name = name;
  12185. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12186. this.size = 1.0;
  12187. this.angle = 0;
  12188. this.cellIndex = 0;
  12189. this.invertU = 0;
  12190. this.invertV = 0;
  12191. this.animations = new Array();
  12192. this._animationStarted = false;
  12193. this._loopAnimation = false;
  12194. this._fromIndex = 0;
  12195. this._toIndex = 0;
  12196. this._delay = 0;
  12197. this._direction = 1;
  12198. this._frameCount = 0;
  12199. this._time = 0;
  12200. this._manager = manager;
  12201. this._manager.sprites.push(this);
  12202. this.position = BABYLON.Vector3.Zero();
  12203. }
  12204. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  12205. this._fromIndex = from;
  12206. this._toIndex = to;
  12207. this._loopAnimation = loop;
  12208. this._delay = delay;
  12209. this._animationStarted = true;
  12210. this._direction = from < to ? 1 : -1;
  12211. this.cellIndex = from;
  12212. this._time = 0;
  12213. };
  12214. Sprite.prototype.stopAnimation = function () {
  12215. this._animationStarted = false;
  12216. };
  12217. Sprite.prototype._animate = function (deltaTime) {
  12218. if (!this._animationStarted)
  12219. return;
  12220. this._time += deltaTime;
  12221. if (this._time > this._delay) {
  12222. this._time = this._time % this._delay;
  12223. this.cellIndex += this._direction;
  12224. if (this.cellIndex == this._toIndex) {
  12225. if (this._loopAnimation) {
  12226. this.cellIndex = this._fromIndex;
  12227. } else {
  12228. this._animationStarted = false;
  12229. if (this.disposeWhenFinishedAnimating) {
  12230. this.dispose();
  12231. }
  12232. }
  12233. }
  12234. }
  12235. };
  12236. Sprite.prototype.dispose = function () {
  12237. for (var i = 0; i < this._manager.sprites.length; i++) {
  12238. if (this._manager.sprites[i] == this) {
  12239. this._manager.sprites.splice(i, 1);
  12240. }
  12241. }
  12242. };
  12243. return Sprite;
  12244. })();
  12245. BABYLON.Sprite = Sprite;
  12246. })(BABYLON || (BABYLON = {}));
  12247. var BABYLON;
  12248. (function (BABYLON) {
  12249. var Layer = (function () {
  12250. function Layer(name, imgUrl, scene, isBackground, color) {
  12251. this.name = name;
  12252. this._vertexDeclaration = [2];
  12253. this._vertexStrideSize = 2 * 4;
  12254. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  12255. this.isBackground = isBackground === undefined ? true : isBackground;
  12256. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  12257. this._scene = scene;
  12258. this._scene.layers.push(this);
  12259. var vertices = [];
  12260. vertices.push(1, 1);
  12261. vertices.push(-1, 1);
  12262. vertices.push(-1, -1);
  12263. vertices.push(1, -1);
  12264. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12265. var indices = [];
  12266. indices.push(0);
  12267. indices.push(1);
  12268. indices.push(2);
  12269. indices.push(0);
  12270. indices.push(2);
  12271. indices.push(3);
  12272. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12273. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  12274. }
  12275. Layer.prototype.render = function () {
  12276. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  12277. return;
  12278. var engine = this._scene.getEngine();
  12279. engine.enableEffect(this._effect);
  12280. engine.setState(false);
  12281. this._effect.setTexture("textureSampler", this.texture);
  12282. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  12283. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  12284. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12285. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12286. engine.draw(true, 0, 6);
  12287. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12288. };
  12289. Layer.prototype.dispose = function () {
  12290. if (this._vertexBuffer) {
  12291. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12292. this._vertexBuffer = null;
  12293. }
  12294. if (this._indexBuffer) {
  12295. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12296. this._indexBuffer = null;
  12297. }
  12298. if (this.texture) {
  12299. this.texture.dispose();
  12300. this.texture = null;
  12301. }
  12302. var index = this._scene.layers.indexOf(this);
  12303. this._scene.layers.splice(index, 1);
  12304. if (this.onDispose) {
  12305. this.onDispose();
  12306. }
  12307. };
  12308. return Layer;
  12309. })();
  12310. BABYLON.Layer = Layer;
  12311. })(BABYLON || (BABYLON = {}));
  12312. var BABYLON;
  12313. (function (BABYLON) {
  12314. var Particle = (function () {
  12315. function Particle() {
  12316. this.position = BABYLON.Vector3.Zero();
  12317. this.direction = BABYLON.Vector3.Zero();
  12318. this.color = new BABYLON.Color4(0, 0, 0, 0);
  12319. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  12320. this.lifeTime = 1.0;
  12321. this.age = 0;
  12322. this.size = 0;
  12323. this.angle = 0;
  12324. this.angularSpeed = 0;
  12325. }
  12326. return Particle;
  12327. })();
  12328. BABYLON.Particle = Particle;
  12329. })(BABYLON || (BABYLON = {}));
  12330. var BABYLON;
  12331. (function (BABYLON) {
  12332. var randomNumber = function (min, max) {
  12333. if (min == max) {
  12334. return (min);
  12335. }
  12336. var random = Math.random();
  12337. return ((random * (max - min)) + min);
  12338. };
  12339. var ParticleSystem = (function () {
  12340. function ParticleSystem(name, capacity, scene, customEffect) {
  12341. var _this = this;
  12342. this.name = name;
  12343. this.renderingGroupId = 0;
  12344. this.emitter = null;
  12345. this.emitRate = 10;
  12346. this.manualEmitCount = -1;
  12347. this.updateSpeed = 0.01;
  12348. this.targetStopDuration = 0;
  12349. this.disposeOnStop = false;
  12350. this.minEmitPower = 1;
  12351. this.maxEmitPower = 1;
  12352. this.minLifeTime = 1;
  12353. this.maxLifeTime = 1;
  12354. this.minSize = 1;
  12355. this.maxSize = 1;
  12356. this.minAngularSpeed = 0;
  12357. this.maxAngularSpeed = 0;
  12358. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  12359. this.forceDepthWrite = false;
  12360. this.gravity = BABYLON.Vector3.Zero();
  12361. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  12362. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  12363. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  12364. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  12365. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12366. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12367. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  12368. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12369. this.particles = new Array();
  12370. this._vertexDeclaration = [3, 4, 4];
  12371. this._vertexStrideSize = 11 * 4;
  12372. this._stockParticles = new Array();
  12373. this._newPartsExcess = 0;
  12374. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  12375. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  12376. this._scaledDirection = BABYLON.Vector3.Zero();
  12377. this._scaledGravity = BABYLON.Vector3.Zero();
  12378. this._currentRenderId = -1;
  12379. this._started = false;
  12380. this._stopped = false;
  12381. this._actualFrame = 0;
  12382. this.id = name;
  12383. this._capacity = capacity;
  12384. this._scene = scene;
  12385. this._customEffect = customEffect;
  12386. scene.particleSystems.push(this);
  12387. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  12388. var indices = [];
  12389. var index = 0;
  12390. for (var count = 0; count < capacity; count++) {
  12391. indices.push(index);
  12392. indices.push(index + 1);
  12393. indices.push(index + 2);
  12394. indices.push(index);
  12395. indices.push(index + 2);
  12396. indices.push(index + 3);
  12397. index += 4;
  12398. }
  12399. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12400. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  12401. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  12402. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  12403. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  12404. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  12405. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  12406. };
  12407. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  12408. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  12409. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  12410. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  12411. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  12412. };
  12413. }
  12414. ParticleSystem.prototype.getCapacity = function () {
  12415. return this._capacity;
  12416. };
  12417. ParticleSystem.prototype.isAlive = function () {
  12418. return this._alive;
  12419. };
  12420. ParticleSystem.prototype.isStarted = function () {
  12421. return this._started;
  12422. };
  12423. ParticleSystem.prototype.start = function () {
  12424. this._started = true;
  12425. this._stopped = false;
  12426. this._actualFrame = 0;
  12427. };
  12428. ParticleSystem.prototype.stop = function () {
  12429. this._stopped = true;
  12430. };
  12431. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  12432. var offset = index * 11;
  12433. this._vertices[offset] = particle.position.x;
  12434. this._vertices[offset + 1] = particle.position.y;
  12435. this._vertices[offset + 2] = particle.position.z;
  12436. this._vertices[offset + 3] = particle.color.r;
  12437. this._vertices[offset + 4] = particle.color.g;
  12438. this._vertices[offset + 5] = particle.color.b;
  12439. this._vertices[offset + 6] = particle.color.a;
  12440. this._vertices[offset + 7] = particle.angle;
  12441. this._vertices[offset + 8] = particle.size;
  12442. this._vertices[offset + 9] = offsetX;
  12443. this._vertices[offset + 10] = offsetY;
  12444. };
  12445. ParticleSystem.prototype._update = function (newParticles) {
  12446. this._alive = this.particles.length > 0;
  12447. for (var index = 0; index < this.particles.length; index++) {
  12448. var particle = this.particles[index];
  12449. particle.age += this._scaledUpdateSpeed;
  12450. if (particle.age >= particle.lifeTime) {
  12451. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  12452. index--;
  12453. continue;
  12454. } else {
  12455. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  12456. particle.color.addInPlace(this._scaledColorStep);
  12457. if (particle.color.a < 0)
  12458. particle.color.a = 0;
  12459. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  12460. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  12461. particle.position.addInPlace(this._scaledDirection);
  12462. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  12463. particle.direction.addInPlace(this._scaledGravity);
  12464. }
  12465. }
  12466. var worldMatrix;
  12467. if (this.emitter.position) {
  12468. worldMatrix = this.emitter.getWorldMatrix();
  12469. } else {
  12470. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  12471. }
  12472. for (index = 0; index < newParticles; index++) {
  12473. if (this.particles.length == this._capacity) {
  12474. break;
  12475. }
  12476. if (this._stockParticles.length !== 0) {
  12477. particle = this._stockParticles.pop();
  12478. particle.age = 0;
  12479. } else {
  12480. particle = new BABYLON.Particle();
  12481. }
  12482. this.particles.push(particle);
  12483. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  12484. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  12485. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  12486. particle.size = randomNumber(this.minSize, this.maxSize);
  12487. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  12488. this.startPositionFunction(worldMatrix, particle.position);
  12489. var step = randomNumber(0, 1.0);
  12490. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  12491. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  12492. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  12493. }
  12494. };
  12495. ParticleSystem.prototype._getEffect = function () {
  12496. if (this._customEffect) {
  12497. return this._customEffect;
  12498. }
  12499. ;
  12500. var defines = [];
  12501. if (this._scene.clipPlane) {
  12502. defines.push("#define CLIPPLANE");
  12503. }
  12504. var join = defines.join("\n");
  12505. if (this._cachedDefines != join) {
  12506. this._cachedDefines = join;
  12507. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  12508. }
  12509. return this._effect;
  12510. };
  12511. ParticleSystem.prototype.animate = function () {
  12512. if (!this._started)
  12513. return;
  12514. var effect = this._getEffect();
  12515. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  12516. return;
  12517. if (this._currentRenderId === this._scene.getRenderId()) {
  12518. return;
  12519. }
  12520. this._currentRenderId = this._scene.getRenderId();
  12521. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  12522. var emitCout;
  12523. if (this.manualEmitCount > -1) {
  12524. emitCout = this.manualEmitCount;
  12525. this.manualEmitCount = 0;
  12526. } else {
  12527. emitCout = this.emitRate;
  12528. }
  12529. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  12530. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  12531. if (this._newPartsExcess > 1.0) {
  12532. newParticles += this._newPartsExcess >> 0;
  12533. this._newPartsExcess -= this._newPartsExcess >> 0;
  12534. }
  12535. this._alive = false;
  12536. if (!this._stopped) {
  12537. this._actualFrame += this._scaledUpdateSpeed;
  12538. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  12539. this.stop();
  12540. } else {
  12541. newParticles = 0;
  12542. }
  12543. this._update(newParticles);
  12544. if (this._stopped) {
  12545. if (!this._alive) {
  12546. this._started = false;
  12547. if (this.disposeOnStop) {
  12548. this._scene._toBeDisposed.push(this);
  12549. }
  12550. }
  12551. }
  12552. var offset = 0;
  12553. for (var index = 0; index < this.particles.length; index++) {
  12554. var particle = this.particles[index];
  12555. this._appendParticleVertex(offset++, particle, 0, 0);
  12556. this._appendParticleVertex(offset++, particle, 1, 0);
  12557. this._appendParticleVertex(offset++, particle, 1, 1);
  12558. this._appendParticleVertex(offset++, particle, 0, 1);
  12559. }
  12560. var engine = this._scene.getEngine();
  12561. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  12562. };
  12563. ParticleSystem.prototype.render = function () {
  12564. var effect = this._getEffect();
  12565. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  12566. return 0;
  12567. var engine = this._scene.getEngine();
  12568. engine.enableEffect(effect);
  12569. var viewMatrix = this._scene.getViewMatrix();
  12570. effect.setTexture("diffuseSampler", this.particleTexture);
  12571. effect.setMatrix("view", viewMatrix);
  12572. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  12573. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  12574. if (this._scene.clipPlane) {
  12575. var clipPlane = this._scene.clipPlane;
  12576. var invView = viewMatrix.clone();
  12577. invView.invert();
  12578. effect.setMatrix("invView", invView);
  12579. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  12580. }
  12581. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12582. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  12583. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  12584. } else {
  12585. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12586. }
  12587. if (this.forceDepthWrite) {
  12588. engine.setDepthWrite(true);
  12589. }
  12590. engine.draw(true, 0, this.particles.length * 6);
  12591. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12592. return this.particles.length;
  12593. };
  12594. ParticleSystem.prototype.dispose = function () {
  12595. if (this._vertexBuffer) {
  12596. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12597. this._vertexBuffer = null;
  12598. }
  12599. if (this._indexBuffer) {
  12600. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12601. this._indexBuffer = null;
  12602. }
  12603. if (this.particleTexture) {
  12604. this.particleTexture.dispose();
  12605. this.particleTexture = null;
  12606. }
  12607. var index = this._scene.particleSystems.indexOf(this);
  12608. this._scene.particleSystems.splice(index, 1);
  12609. if (this.onDispose) {
  12610. this.onDispose();
  12611. }
  12612. };
  12613. ParticleSystem.prototype.clone = function (name, newEmitter) {
  12614. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  12615. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  12616. if (newEmitter === undefined) {
  12617. newEmitter = this.emitter;
  12618. }
  12619. result.emitter = newEmitter;
  12620. if (this.particleTexture) {
  12621. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  12622. }
  12623. result.start();
  12624. return result;
  12625. };
  12626. ParticleSystem.BLENDMODE_ONEONE = 0;
  12627. ParticleSystem.BLENDMODE_STANDARD = 1;
  12628. return ParticleSystem;
  12629. })();
  12630. BABYLON.ParticleSystem = ParticleSystem;
  12631. })(BABYLON || (BABYLON = {}));
  12632. var BABYLON;
  12633. (function (BABYLON) {
  12634. var Animation = (function () {
  12635. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  12636. this.name = name;
  12637. this.targetProperty = targetProperty;
  12638. this.framePerSecond = framePerSecond;
  12639. this.dataType = dataType;
  12640. this.loopMode = loopMode;
  12641. this._offsetsCache = {};
  12642. this._highLimitsCache = {};
  12643. this._stopped = false;
  12644. this.targetPropertyPath = targetProperty.split(".");
  12645. this.dataType = dataType;
  12646. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  12647. }
  12648. Animation.prototype.isStopped = function () {
  12649. return this._stopped;
  12650. };
  12651. Animation.prototype.getKeys = function () {
  12652. return this._keys;
  12653. };
  12654. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  12655. return startValue + (endValue - startValue) * gradient;
  12656. };
  12657. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  12658. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  12659. };
  12660. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  12661. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  12662. };
  12663. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  12664. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  12665. };
  12666. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  12667. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  12668. };
  12669. Animation.prototype.clone = function () {
  12670. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  12671. clone.setKeys(this._keys);
  12672. return clone;
  12673. };
  12674. Animation.prototype.setKeys = function (values) {
  12675. this._keys = values.slice(0);
  12676. this._offsetsCache = {};
  12677. this._highLimitsCache = {};
  12678. };
  12679. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  12680. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  12681. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  12682. }
  12683. this.currentFrame = currentFrame;
  12684. for (var key = 0; key < this._keys.length; key++) {
  12685. if (this._keys[key + 1].frame >= currentFrame) {
  12686. var startValue = this._keys[key].value;
  12687. var endValue = this._keys[key + 1].value;
  12688. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  12689. switch (this.dataType) {
  12690. case Animation.ANIMATIONTYPE_FLOAT:
  12691. switch (loopMode) {
  12692. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12693. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12694. return this.floatInterpolateFunction(startValue, endValue, gradient);
  12695. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12696. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  12697. }
  12698. break;
  12699. case Animation.ANIMATIONTYPE_QUATERNION:
  12700. var quaternion = null;
  12701. switch (loopMode) {
  12702. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12703. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12704. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  12705. break;
  12706. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12707. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12708. break;
  12709. }
  12710. return quaternion;
  12711. case Animation.ANIMATIONTYPE_VECTOR3:
  12712. switch (loopMode) {
  12713. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12714. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12715. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  12716. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12717. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12718. }
  12719. case Animation.ANIMATIONTYPE_VECTOR2:
  12720. switch (loopMode) {
  12721. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12722. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12723. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  12724. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12725. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12726. }
  12727. case Animation.ANIMATIONTYPE_COLOR3:
  12728. switch (loopMode) {
  12729. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12730. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12731. return this.color3InterpolateFunction(startValue, endValue, gradient);
  12732. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12733. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12734. }
  12735. case Animation.ANIMATIONTYPE_MATRIX:
  12736. switch (loopMode) {
  12737. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12738. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12739. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12740. return startValue;
  12741. }
  12742. default:
  12743. break;
  12744. }
  12745. break;
  12746. }
  12747. }
  12748. return this._keys[this._keys.length - 1].value;
  12749. };
  12750. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  12751. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  12752. this._stopped = true;
  12753. return false;
  12754. }
  12755. var returnValue = true;
  12756. if (this._keys[0].frame != 0) {
  12757. var newKey = {
  12758. frame: 0,
  12759. value: this._keys[0].value
  12760. };
  12761. this._keys.splice(0, 0, newKey);
  12762. }
  12763. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  12764. from = this._keys[0].frame;
  12765. }
  12766. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  12767. to = this._keys[this._keys.length - 1].frame;
  12768. }
  12769. var range = to - from;
  12770. var offsetValue;
  12771. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  12772. if (ratio > range && !loop) {
  12773. returnValue = false;
  12774. highLimitValue = this._keys[this._keys.length - 1].value;
  12775. } else {
  12776. var highLimitValue = 0;
  12777. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  12778. var keyOffset = to.toString() + from.toString();
  12779. if (!this._offsetsCache[keyOffset]) {
  12780. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  12781. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  12782. switch (this.dataType) {
  12783. case Animation.ANIMATIONTYPE_FLOAT:
  12784. this._offsetsCache[keyOffset] = toValue - fromValue;
  12785. break;
  12786. case Animation.ANIMATIONTYPE_QUATERNION:
  12787. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12788. break;
  12789. case Animation.ANIMATIONTYPE_VECTOR3:
  12790. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12791. case Animation.ANIMATIONTYPE_VECTOR2:
  12792. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12793. case Animation.ANIMATIONTYPE_COLOR3:
  12794. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12795. default:
  12796. break;
  12797. }
  12798. this._highLimitsCache[keyOffset] = toValue;
  12799. }
  12800. highLimitValue = this._highLimitsCache[keyOffset];
  12801. offsetValue = this._offsetsCache[keyOffset];
  12802. }
  12803. }
  12804. if (offsetValue === undefined) {
  12805. switch (this.dataType) {
  12806. case Animation.ANIMATIONTYPE_FLOAT:
  12807. offsetValue = 0;
  12808. break;
  12809. case Animation.ANIMATIONTYPE_QUATERNION:
  12810. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  12811. break;
  12812. case Animation.ANIMATIONTYPE_VECTOR3:
  12813. offsetValue = BABYLON.Vector3.Zero();
  12814. break;
  12815. case Animation.ANIMATIONTYPE_VECTOR2:
  12816. offsetValue = BABYLON.Vector2.Zero();
  12817. break;
  12818. case Animation.ANIMATIONTYPE_COLOR3:
  12819. offsetValue = BABYLON.Color3.Black();
  12820. }
  12821. }
  12822. var repeatCount = (ratio / range) >> 0;
  12823. var currentFrame = returnValue ? from + ratio % range : to;
  12824. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  12825. if (this.targetPropertyPath.length > 1) {
  12826. var property = this._target[this.targetPropertyPath[0]];
  12827. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  12828. property = property[this.targetPropertyPath[index]];
  12829. }
  12830. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  12831. } else {
  12832. this._target[this.targetPropertyPath[0]] = currentValue;
  12833. }
  12834. if (this._target.markAsDirty) {
  12835. this._target.markAsDirty(this.targetProperty);
  12836. }
  12837. if (!returnValue) {
  12838. this._stopped = true;
  12839. }
  12840. return returnValue;
  12841. };
  12842. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  12843. get: function () {
  12844. return Animation._ANIMATIONTYPE_FLOAT;
  12845. },
  12846. enumerable: true,
  12847. configurable: true
  12848. });
  12849. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  12850. get: function () {
  12851. return Animation._ANIMATIONTYPE_VECTOR3;
  12852. },
  12853. enumerable: true,
  12854. configurable: true
  12855. });
  12856. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  12857. get: function () {
  12858. return Animation._ANIMATIONTYPE_VECTOR2;
  12859. },
  12860. enumerable: true,
  12861. configurable: true
  12862. });
  12863. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  12864. get: function () {
  12865. return Animation._ANIMATIONTYPE_QUATERNION;
  12866. },
  12867. enumerable: true,
  12868. configurable: true
  12869. });
  12870. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  12871. get: function () {
  12872. return Animation._ANIMATIONTYPE_MATRIX;
  12873. },
  12874. enumerable: true,
  12875. configurable: true
  12876. });
  12877. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  12878. get: function () {
  12879. return Animation._ANIMATIONTYPE_COLOR3;
  12880. },
  12881. enumerable: true,
  12882. configurable: true
  12883. });
  12884. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  12885. get: function () {
  12886. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  12887. },
  12888. enumerable: true,
  12889. configurable: true
  12890. });
  12891. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  12892. get: function () {
  12893. return Animation._ANIMATIONLOOPMODE_CYCLE;
  12894. },
  12895. enumerable: true,
  12896. configurable: true
  12897. });
  12898. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  12899. get: function () {
  12900. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  12901. },
  12902. enumerable: true,
  12903. configurable: true
  12904. });
  12905. Animation._ANIMATIONTYPE_FLOAT = 0;
  12906. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  12907. Animation._ANIMATIONTYPE_QUATERNION = 2;
  12908. Animation._ANIMATIONTYPE_MATRIX = 3;
  12909. Animation._ANIMATIONTYPE_COLOR3 = 4;
  12910. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  12911. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  12912. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  12913. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  12914. return Animation;
  12915. })();
  12916. BABYLON.Animation = Animation;
  12917. })(BABYLON || (BABYLON = {}));
  12918. var BABYLON;
  12919. (function (BABYLON) {
  12920. var Animatable = (function () {
  12921. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  12922. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  12923. if (typeof toFrame === "undefined") { toFrame = 100; }
  12924. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  12925. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  12926. this.target = target;
  12927. this.fromFrame = fromFrame;
  12928. this.toFrame = toFrame;
  12929. this.loopAnimation = loopAnimation;
  12930. this.speedRatio = speedRatio;
  12931. this.onAnimationEnd = onAnimationEnd;
  12932. this._animations = new Array();
  12933. this._paused = false;
  12934. this.animationStarted = false;
  12935. if (animations) {
  12936. this.appendAnimations(target, animations);
  12937. }
  12938. this._scene = scene;
  12939. scene._activeAnimatables.push(this);
  12940. }
  12941. Animatable.prototype.appendAnimations = function (target, animations) {
  12942. for (var index = 0; index < animations.length; index++) {
  12943. var animation = animations[index];
  12944. animation._target = target;
  12945. this._animations.push(animation);
  12946. }
  12947. };
  12948. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  12949. var animations = this._animations;
  12950. for (var index = 0; index < animations.length; index++) {
  12951. if (animations[index].targetProperty === property) {
  12952. return animations[index];
  12953. }
  12954. }
  12955. return null;
  12956. };
  12957. Animatable.prototype.pause = function () {
  12958. if (this._paused) {
  12959. return;
  12960. }
  12961. this._paused = true;
  12962. };
  12963. Animatable.prototype.restart = function () {
  12964. this._paused = false;
  12965. };
  12966. Animatable.prototype.stop = function () {
  12967. var index = this._scene._activeAnimatables.indexOf(this);
  12968. if (index > -1) {
  12969. this._scene._activeAnimatables.splice(index, 1);
  12970. }
  12971. if (this.onAnimationEnd) {
  12972. this.onAnimationEnd();
  12973. }
  12974. };
  12975. Animatable.prototype._animate = function (delay) {
  12976. if (this._paused) {
  12977. if (!this._pausedDelay) {
  12978. this._pausedDelay = delay;
  12979. }
  12980. return true;
  12981. }
  12982. if (!this._localDelayOffset) {
  12983. this._localDelayOffset = delay;
  12984. } else if (this._pausedDelay) {
  12985. this._localDelayOffset += delay - this._pausedDelay;
  12986. this._pausedDelay = null;
  12987. }
  12988. var running = false;
  12989. var animations = this._animations;
  12990. for (var index = 0; index < animations.length; index++) {
  12991. var animation = animations[index];
  12992. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  12993. running = running || isRunning;
  12994. }
  12995. if (!running && this.onAnimationEnd) {
  12996. this.onAnimationEnd();
  12997. }
  12998. return running;
  12999. };
  13000. return Animatable;
  13001. })();
  13002. BABYLON.Animatable = Animatable;
  13003. })(BABYLON || (BABYLON = {}));
  13004. var BABYLON;
  13005. (function (BABYLON) {
  13006. var Octree = (function () {
  13007. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  13008. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  13009. this.maxDepth = maxDepth;
  13010. this.dynamicContent = new Array();
  13011. this._maxBlockCapacity = maxBlockCapacity || 64;
  13012. this._selectionContent = new BABYLON.SmartArray(1024);
  13013. this._creationFunc = creationFunc;
  13014. }
  13015. Octree.prototype.update = function (worldMin, worldMax, entries) {
  13016. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  13017. };
  13018. Octree.prototype.addMesh = function (entry) {
  13019. for (var index = 0; index < this.blocks.length; index++) {
  13020. var block = this.blocks[index];
  13021. block.addEntry(entry);
  13022. }
  13023. };
  13024. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  13025. this._selectionContent.reset();
  13026. for (var index = 0; index < this.blocks.length; index++) {
  13027. var block = this.blocks[index];
  13028. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  13029. }
  13030. if (allowDuplicate) {
  13031. this._selectionContent.concat(this.dynamicContent);
  13032. } else {
  13033. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  13034. }
  13035. return this._selectionContent;
  13036. };
  13037. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  13038. this._selectionContent.reset();
  13039. for (var index = 0; index < this.blocks.length; index++) {
  13040. var block = this.blocks[index];
  13041. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  13042. }
  13043. if (allowDuplicate) {
  13044. this._selectionContent.concat(this.dynamicContent);
  13045. } else {
  13046. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  13047. }
  13048. return this._selectionContent;
  13049. };
  13050. Octree.prototype.intersectsRay = function (ray) {
  13051. this._selectionContent.reset();
  13052. for (var index = 0; index < this.blocks.length; index++) {
  13053. var block = this.blocks[index];
  13054. block.intersectsRay(ray, this._selectionContent);
  13055. }
  13056. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  13057. return this._selectionContent;
  13058. };
  13059. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  13060. target.blocks = new Array();
  13061. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  13062. for (var x = 0; x < 2; x++) {
  13063. for (var y = 0; y < 2; y++) {
  13064. for (var z = 0; z < 2; z++) {
  13065. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  13066. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  13067. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  13068. block.addEntries(entries);
  13069. target.blocks.push(block);
  13070. }
  13071. }
  13072. }
  13073. };
  13074. Octree.CreationFuncForMeshes = function (entry, block) {
  13075. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  13076. block.entries.push(entry);
  13077. }
  13078. };
  13079. Octree.CreationFuncForSubMeshes = function (entry, block) {
  13080. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  13081. block.entries.push(entry);
  13082. }
  13083. };
  13084. return Octree;
  13085. })();
  13086. BABYLON.Octree = Octree;
  13087. })(BABYLON || (BABYLON = {}));
  13088. var BABYLON;
  13089. (function (BABYLON) {
  13090. var OctreeBlock = (function () {
  13091. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  13092. this.entries = new Array();
  13093. this._boundingVectors = new Array();
  13094. this._capacity = capacity;
  13095. this._depth = depth;
  13096. this._maxDepth = maxDepth;
  13097. this._creationFunc = creationFunc;
  13098. this._minPoint = minPoint;
  13099. this._maxPoint = maxPoint;
  13100. this._boundingVectors.push(minPoint.clone());
  13101. this._boundingVectors.push(maxPoint.clone());
  13102. this._boundingVectors.push(minPoint.clone());
  13103. this._boundingVectors[2].x = maxPoint.x;
  13104. this._boundingVectors.push(minPoint.clone());
  13105. this._boundingVectors[3].y = maxPoint.y;
  13106. this._boundingVectors.push(minPoint.clone());
  13107. this._boundingVectors[4].z = maxPoint.z;
  13108. this._boundingVectors.push(maxPoint.clone());
  13109. this._boundingVectors[5].z = minPoint.z;
  13110. this._boundingVectors.push(maxPoint.clone());
  13111. this._boundingVectors[6].x = minPoint.x;
  13112. this._boundingVectors.push(maxPoint.clone());
  13113. this._boundingVectors[7].y = minPoint.y;
  13114. }
  13115. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  13116. get: function () {
  13117. return this._capacity;
  13118. },
  13119. enumerable: true,
  13120. configurable: true
  13121. });
  13122. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  13123. get: function () {
  13124. return this._minPoint;
  13125. },
  13126. enumerable: true,
  13127. configurable: true
  13128. });
  13129. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  13130. get: function () {
  13131. return this._maxPoint;
  13132. },
  13133. enumerable: true,
  13134. configurable: true
  13135. });
  13136. OctreeBlock.prototype.addEntry = function (entry) {
  13137. if (this.blocks) {
  13138. for (var index = 0; index < this.blocks.length; index++) {
  13139. var block = this.blocks[index];
  13140. block.addEntry(entry);
  13141. }
  13142. return;
  13143. }
  13144. this._creationFunc(entry, this);
  13145. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  13146. this.createInnerBlocks();
  13147. }
  13148. };
  13149. OctreeBlock.prototype.addEntries = function (entries) {
  13150. for (var index = 0; index < entries.length; index++) {
  13151. var mesh = entries[index];
  13152. this.addEntry(mesh);
  13153. }
  13154. };
  13155. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  13156. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  13157. if (this.blocks) {
  13158. for (var index = 0; index < this.blocks.length; index++) {
  13159. var block = this.blocks[index];
  13160. block.select(frustumPlanes, selection, allowDuplicate);
  13161. }
  13162. return;
  13163. }
  13164. if (allowDuplicate) {
  13165. selection.concat(this.entries);
  13166. } else {
  13167. selection.concatWithNoDuplicate(this.entries);
  13168. }
  13169. }
  13170. };
  13171. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  13172. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  13173. if (this.blocks) {
  13174. for (var index = 0; index < this.blocks.length; index++) {
  13175. var block = this.blocks[index];
  13176. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  13177. }
  13178. return;
  13179. }
  13180. if (allowDuplicate) {
  13181. selection.concat(this.entries);
  13182. } else {
  13183. selection.concatWithNoDuplicate(this.entries);
  13184. }
  13185. }
  13186. };
  13187. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  13188. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  13189. if (this.blocks) {
  13190. for (var index = 0; index < this.blocks.length; index++) {
  13191. var block = this.blocks[index];
  13192. block.intersectsRay(ray, selection);
  13193. }
  13194. return;
  13195. }
  13196. selection.concatWithNoDuplicate(this.entries);
  13197. }
  13198. };
  13199. OctreeBlock.prototype.createInnerBlocks = function () {
  13200. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  13201. };
  13202. return OctreeBlock;
  13203. })();
  13204. BABYLON.OctreeBlock = OctreeBlock;
  13205. })(BABYLON || (BABYLON = {}));
  13206. var BABYLON;
  13207. (function (BABYLON) {
  13208. var Bone = (function () {
  13209. function Bone(name, skeleton, parentBone, matrix) {
  13210. this.name = name;
  13211. this.children = new Array();
  13212. this.animations = new Array();
  13213. this._worldTransform = new BABYLON.Matrix();
  13214. this._absoluteTransform = new BABYLON.Matrix();
  13215. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  13216. this._skeleton = skeleton;
  13217. this._matrix = matrix;
  13218. this._baseMatrix = matrix;
  13219. skeleton.bones.push(this);
  13220. if (parentBone) {
  13221. this._parent = parentBone;
  13222. parentBone.children.push(this);
  13223. } else {
  13224. this._parent = null;
  13225. }
  13226. this._updateDifferenceMatrix();
  13227. }
  13228. Bone.prototype.getParent = function () {
  13229. return this._parent;
  13230. };
  13231. Bone.prototype.getLocalMatrix = function () {
  13232. return this._matrix;
  13233. };
  13234. Bone.prototype.getBaseMatrix = function () {
  13235. return this._baseMatrix;
  13236. };
  13237. Bone.prototype.getWorldMatrix = function () {
  13238. return this._worldTransform;
  13239. };
  13240. Bone.prototype.getInvertedAbsoluteTransform = function () {
  13241. return this._invertedAbsoluteTransform;
  13242. };
  13243. Bone.prototype.getAbsoluteMatrix = function () {
  13244. var matrix = this._matrix.clone();
  13245. var parent = this._parent;
  13246. while (parent) {
  13247. matrix = matrix.multiply(parent.getLocalMatrix());
  13248. parent = parent.getParent();
  13249. }
  13250. return matrix;
  13251. };
  13252. Bone.prototype.updateMatrix = function (matrix) {
  13253. this._matrix = matrix;
  13254. this._skeleton._markAsDirty();
  13255. this._updateDifferenceMatrix();
  13256. };
  13257. Bone.prototype._updateDifferenceMatrix = function () {
  13258. if (this._parent) {
  13259. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  13260. } else {
  13261. this._absoluteTransform.copyFrom(this._matrix);
  13262. }
  13263. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  13264. for (var index = 0; index < this.children.length; index++) {
  13265. this.children[index]._updateDifferenceMatrix();
  13266. }
  13267. };
  13268. Bone.prototype.markAsDirty = function () {
  13269. this._skeleton._markAsDirty();
  13270. };
  13271. return Bone;
  13272. })();
  13273. BABYLON.Bone = Bone;
  13274. })(BABYLON || (BABYLON = {}));
  13275. var BABYLON;
  13276. (function (BABYLON) {
  13277. var Skeleton = (function () {
  13278. function Skeleton(name, id, scene) {
  13279. this.name = name;
  13280. this.id = id;
  13281. this.bones = new Array();
  13282. this._isDirty = true;
  13283. this._identity = BABYLON.Matrix.Identity();
  13284. this.bones = [];
  13285. this._scene = scene;
  13286. scene.skeletons.push(this);
  13287. }
  13288. Skeleton.prototype.getTransformMatrices = function () {
  13289. return this._transformMatrices;
  13290. };
  13291. Skeleton.prototype._markAsDirty = function () {
  13292. this._isDirty = true;
  13293. };
  13294. Skeleton.prototype.prepare = function () {
  13295. if (!this._isDirty) {
  13296. return;
  13297. }
  13298. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  13299. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  13300. }
  13301. for (var index = 0; index < this.bones.length; index++) {
  13302. var bone = this.bones[index];
  13303. var parentBone = bone.getParent();
  13304. if (parentBone) {
  13305. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  13306. } else {
  13307. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  13308. }
  13309. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  13310. }
  13311. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  13312. this._isDirty = false;
  13313. };
  13314. Skeleton.prototype.getAnimatables = function () {
  13315. if (!this._animatables || this._animatables.length != this.bones.length) {
  13316. this._animatables = [];
  13317. for (var index = 0; index < this.bones.length; index++) {
  13318. this._animatables.push(this.bones[index]);
  13319. }
  13320. }
  13321. return this._animatables;
  13322. };
  13323. Skeleton.prototype.clone = function (name, id) {
  13324. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  13325. for (var index = 0; index < this.bones.length; index++) {
  13326. var source = this.bones[index];
  13327. var parentBone = null;
  13328. if (source.getParent()) {
  13329. var parentIndex = this.bones.indexOf(source.getParent());
  13330. parentBone = result.bones[parentIndex];
  13331. }
  13332. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  13333. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  13334. }
  13335. return result;
  13336. };
  13337. return Skeleton;
  13338. })();
  13339. BABYLON.Skeleton = Skeleton;
  13340. })(BABYLON || (BABYLON = {}));
  13341. var BABYLON;
  13342. (function (BABYLON) {
  13343. var PostProcess = (function () {
  13344. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  13345. this.name = name;
  13346. this.width = -1;
  13347. this.height = -1;
  13348. this._reusable = false;
  13349. this._textures = new BABYLON.SmartArray(2);
  13350. this._currentRenderTextureInd = 0;
  13351. if (camera != null) {
  13352. this._camera = camera;
  13353. this._scene = camera.getScene();
  13354. camera.attachPostProcess(this);
  13355. this._engine = this._scene.getEngine();
  13356. } else {
  13357. this._engine = engine;
  13358. }
  13359. this._renderRatio = ratio;
  13360. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13361. this._reusable = reusable || false;
  13362. samplers = samplers || [];
  13363. samplers.push("textureSampler");
  13364. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  13365. }
  13366. PostProcess.prototype.isReusable = function () {
  13367. return this._reusable;
  13368. };
  13369. PostProcess.prototype.activate = function (camera, sourceTexture) {
  13370. camera = camera || this._camera;
  13371. var scene = camera.getScene();
  13372. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  13373. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  13374. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  13375. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  13376. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  13377. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  13378. if (this._textures.length > 0) {
  13379. for (var i = 0; i < this._textures.length; i++) {
  13380. this._engine._releaseTexture(this._textures.data[i]);
  13381. }
  13382. this._textures.reset();
  13383. }
  13384. this.width = desiredWidth;
  13385. this.height = desiredHeight;
  13386. 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 }));
  13387. if (this._reusable) {
  13388. 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 }));
  13389. }
  13390. if (this.onSizeChanged) {
  13391. this.onSizeChanged();
  13392. }
  13393. }
  13394. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  13395. if (this.onActivate) {
  13396. this.onActivate(camera);
  13397. }
  13398. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  13399. if (this._reusable) {
  13400. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  13401. }
  13402. };
  13403. PostProcess.prototype.apply = function () {
  13404. if (!this._effect.isReady())
  13405. return null;
  13406. this._engine.enableEffect(this._effect);
  13407. this._engine.setState(false);
  13408. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13409. this._engine.setDepthBuffer(false);
  13410. this._engine.setDepthWrite(false);
  13411. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  13412. if (this.onApply) {
  13413. this.onApply(this._effect);
  13414. }
  13415. return this._effect;
  13416. };
  13417. PostProcess.prototype.dispose = function (camera) {
  13418. camera = camera || this._camera;
  13419. if (this._textures.length > 0) {
  13420. for (var i = 0; i < this._textures.length; i++) {
  13421. this._engine._releaseTexture(this._textures.data[i]);
  13422. }
  13423. this._textures.reset();
  13424. }
  13425. camera.detachPostProcess(this);
  13426. var index = camera._postProcesses.indexOf(this);
  13427. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  13428. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  13429. }
  13430. };
  13431. return PostProcess;
  13432. })();
  13433. BABYLON.PostProcess = PostProcess;
  13434. })(BABYLON || (BABYLON = {}));
  13435. var BABYLON;
  13436. (function (BABYLON) {
  13437. var PostProcessManager = (function () {
  13438. function PostProcessManager(scene) {
  13439. this._vertexDeclaration = [2];
  13440. this._vertexStrideSize = 2 * 4;
  13441. this._scene = scene;
  13442. var vertices = [];
  13443. vertices.push(1, 1);
  13444. vertices.push(-1, 1);
  13445. vertices.push(-1, -1);
  13446. vertices.push(1, -1);
  13447. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13448. var indices = [];
  13449. indices.push(0);
  13450. indices.push(1);
  13451. indices.push(2);
  13452. indices.push(0);
  13453. indices.push(2);
  13454. indices.push(3);
  13455. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13456. }
  13457. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  13458. var postProcesses = this._scene.activeCamera._postProcesses;
  13459. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  13460. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  13461. return false;
  13462. }
  13463. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  13464. return true;
  13465. };
  13466. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  13467. var postProcesses = this._scene.activeCamera._postProcesses;
  13468. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  13469. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  13470. return;
  13471. }
  13472. var engine = this._scene.getEngine();
  13473. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  13474. if (index < postProcessesTakenIndices.length - 1) {
  13475. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  13476. } else {
  13477. if (targetTexture) {
  13478. engine.bindFramebuffer(targetTexture);
  13479. } else {
  13480. engine.restoreDefaultFramebuffer();
  13481. }
  13482. }
  13483. if (doNotPresent) {
  13484. break;
  13485. }
  13486. var pp = postProcesses[postProcessesTakenIndices[index]];
  13487. var effect = pp.apply();
  13488. if (effect) {
  13489. if (pp.onBeforeRender) {
  13490. pp.onBeforeRender(effect);
  13491. }
  13492. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13493. engine.draw(true, 0, 6);
  13494. }
  13495. }
  13496. engine.setDepthBuffer(true);
  13497. engine.setDepthWrite(true);
  13498. };
  13499. PostProcessManager.prototype.dispose = function () {
  13500. if (this._vertexBuffer) {
  13501. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13502. this._vertexBuffer = null;
  13503. }
  13504. if (this._indexBuffer) {
  13505. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13506. this._indexBuffer = null;
  13507. }
  13508. };
  13509. return PostProcessManager;
  13510. })();
  13511. BABYLON.PostProcessManager = PostProcessManager;
  13512. })(BABYLON || (BABYLON = {}));
  13513. var __extends = this.__extends || function (d, b) {
  13514. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13515. function __() { this.constructor = d; }
  13516. __.prototype = b.prototype;
  13517. d.prototype = new __();
  13518. };
  13519. var BABYLON;
  13520. (function (BABYLON) {
  13521. var PassPostProcess = (function (_super) {
  13522. __extends(PassPostProcess, _super);
  13523. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  13524. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  13525. }
  13526. return PassPostProcess;
  13527. })(BABYLON.PostProcess);
  13528. BABYLON.PassPostProcess = PassPostProcess;
  13529. })(BABYLON || (BABYLON = {}));
  13530. var __extends = this.__extends || function (d, b) {
  13531. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13532. function __() { this.constructor = d; }
  13533. __.prototype = b.prototype;
  13534. d.prototype = new __();
  13535. };
  13536. var BABYLON;
  13537. (function (BABYLON) {
  13538. var BlurPostProcess = (function (_super) {
  13539. __extends(BlurPostProcess, _super);
  13540. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  13541. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  13542. var _this = this;
  13543. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  13544. this.direction = direction;
  13545. this.blurWidth = blurWidth;
  13546. this.onApply = function (effect) {
  13547. effect.setFloat2("screenSize", _this.width, _this.height);
  13548. effect.setVector2("direction", _this.direction);
  13549. effect.setFloat("blurWidth", _this.blurWidth);
  13550. };
  13551. }
  13552. return BlurPostProcess;
  13553. })(BABYLON.PostProcess);
  13554. BABYLON.BlurPostProcess = BlurPostProcess;
  13555. })(BABYLON || (BABYLON = {}));
  13556. var __extends = this.__extends || function (d, b) {
  13557. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13558. function __() { this.constructor = d; }
  13559. __.prototype = b.prototype;
  13560. d.prototype = new __();
  13561. };
  13562. var BABYLON;
  13563. (function (BABYLON) {
  13564. var FilterPostProcess = (function (_super) {
  13565. __extends(FilterPostProcess, _super);
  13566. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  13567. var _this = this;
  13568. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  13569. this.kernelMatrix = kernelMatrix;
  13570. this.onApply = function (effect) {
  13571. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  13572. };
  13573. }
  13574. return FilterPostProcess;
  13575. })(BABYLON.PostProcess);
  13576. BABYLON.FilterPostProcess = FilterPostProcess;
  13577. })(BABYLON || (BABYLON = {}));
  13578. var __extends = this.__extends || function (d, b) {
  13579. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13580. function __() { this.constructor = d; }
  13581. __.prototype = b.prototype;
  13582. d.prototype = new __();
  13583. };
  13584. var BABYLON;
  13585. (function (BABYLON) {
  13586. var RefractionPostProcess = (function (_super) {
  13587. __extends(RefractionPostProcess, _super);
  13588. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  13589. var _this = this;
  13590. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  13591. this.color = color;
  13592. this.depth = depth;
  13593. this.colorLevel = colorLevel;
  13594. this.onActivate = function (cam) {
  13595. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  13596. };
  13597. this.onApply = function (effect) {
  13598. effect.setColor3("baseColor", _this.color);
  13599. effect.setFloat("depth", _this.depth);
  13600. effect.setFloat("colorLevel", _this.colorLevel);
  13601. effect.setTexture("refractionSampler", _this._refRexture);
  13602. };
  13603. }
  13604. RefractionPostProcess.prototype.dispose = function (camera) {
  13605. if (this._refRexture) {
  13606. this._refRexture.dispose();
  13607. }
  13608. _super.prototype.dispose.call(this, camera);
  13609. };
  13610. return RefractionPostProcess;
  13611. })(BABYLON.PostProcess);
  13612. BABYLON.RefractionPostProcess = RefractionPostProcess;
  13613. })(BABYLON || (BABYLON = {}));
  13614. var __extends = this.__extends || function (d, b) {
  13615. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13616. function __() { this.constructor = d; }
  13617. __.prototype = b.prototype;
  13618. d.prototype = new __();
  13619. };
  13620. var BABYLON;
  13621. (function (BABYLON) {
  13622. var BlackAndWhitePostProcess = (function (_super) {
  13623. __extends(BlackAndWhitePostProcess, _super);
  13624. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  13625. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  13626. }
  13627. return BlackAndWhitePostProcess;
  13628. })(BABYLON.PostProcess);
  13629. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  13630. })(BABYLON || (BABYLON = {}));
  13631. var __extends = this.__extends || function (d, b) {
  13632. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13633. function __() { this.constructor = d; }
  13634. __.prototype = b.prototype;
  13635. d.prototype = new __();
  13636. };
  13637. var BABYLON;
  13638. (function (BABYLON) {
  13639. var ConvolutionPostProcess = (function (_super) {
  13640. __extends(ConvolutionPostProcess, _super);
  13641. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  13642. var _this = this;
  13643. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  13644. this.kernel = kernel;
  13645. this.onApply = function (effect) {
  13646. effect.setFloat2("screenSize", _this.width, _this.height);
  13647. effect.setArray("kernel", _this.kernel);
  13648. };
  13649. }
  13650. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  13651. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  13652. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  13653. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  13654. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  13655. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  13656. return ConvolutionPostProcess;
  13657. })(BABYLON.PostProcess);
  13658. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  13659. })(BABYLON || (BABYLON = {}));
  13660. var __extends = this.__extends || function (d, b) {
  13661. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13662. function __() { this.constructor = d; }
  13663. __.prototype = b.prototype;
  13664. d.prototype = new __();
  13665. };
  13666. var BABYLON;
  13667. (function (BABYLON) {
  13668. var FxaaPostProcess = (function (_super) {
  13669. __extends(FxaaPostProcess, _super);
  13670. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  13671. var _this = this;
  13672. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  13673. this.onSizeChanged = function () {
  13674. _this.texelWidth = 1.0 / _this.width;
  13675. _this.texelHeight = 1.0 / _this.height;
  13676. };
  13677. this.onApply = function (effect) {
  13678. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  13679. };
  13680. }
  13681. return FxaaPostProcess;
  13682. })(BABYLON.PostProcess);
  13683. BABYLON.FxaaPostProcess = FxaaPostProcess;
  13684. })(BABYLON || (BABYLON = {}));
  13685. var BABYLON;
  13686. (function (BABYLON) {
  13687. var LensFlare = (function () {
  13688. function LensFlare(size, position, color, imgUrl, system) {
  13689. this.size = size;
  13690. this.position = position;
  13691. this.dispose = function () {
  13692. if (this.texture) {
  13693. this.texture.dispose();
  13694. }
  13695. var index = this._system.lensFlares.indexOf(this);
  13696. this._system.lensFlares.splice(index, 1);
  13697. };
  13698. this.color = color || new BABYLON.Color3(1, 1, 1);
  13699. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  13700. this._system = system;
  13701. system.lensFlares.push(this);
  13702. }
  13703. return LensFlare;
  13704. })();
  13705. BABYLON.LensFlare = LensFlare;
  13706. })(BABYLON || (BABYLON = {}));
  13707. var BABYLON;
  13708. (function (BABYLON) {
  13709. var LensFlareSystem = (function () {
  13710. function LensFlareSystem(name, emitter, scene) {
  13711. this.name = name;
  13712. this.lensFlares = new Array();
  13713. this.borderLimit = 300;
  13714. this._vertexDeclaration = [2];
  13715. this._vertexStrideSize = 2 * 4;
  13716. this._isEnabled = true;
  13717. this._scene = scene;
  13718. this._emitter = emitter;
  13719. scene.lensFlareSystems.push(this);
  13720. this.meshesSelectionPredicate = function (m) {
  13721. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  13722. };
  13723. var vertices = [];
  13724. vertices.push(1, 1);
  13725. vertices.push(-1, 1);
  13726. vertices.push(-1, -1);
  13727. vertices.push(1, -1);
  13728. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13729. var indices = [];
  13730. indices.push(0);
  13731. indices.push(1);
  13732. indices.push(2);
  13733. indices.push(0);
  13734. indices.push(2);
  13735. indices.push(3);
  13736. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13737. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  13738. }
  13739. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  13740. get: function () {
  13741. return this._isEnabled;
  13742. },
  13743. set: function (value) {
  13744. this._isEnabled = value;
  13745. },
  13746. enumerable: true,
  13747. configurable: true
  13748. });
  13749. LensFlareSystem.prototype.getScene = function () {
  13750. return this._scene;
  13751. };
  13752. LensFlareSystem.prototype.getEmitter = function () {
  13753. return this._emitter;
  13754. };
  13755. LensFlareSystem.prototype.getEmitterPosition = function () {
  13756. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  13757. };
  13758. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  13759. var position = this.getEmitterPosition();
  13760. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  13761. this._positionX = position.x;
  13762. this._positionY = position.y;
  13763. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  13764. if (position.z > 0) {
  13765. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  13766. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  13767. return true;
  13768. }
  13769. }
  13770. return false;
  13771. };
  13772. LensFlareSystem.prototype._isVisible = function () {
  13773. if (!this._isEnabled) {
  13774. return false;
  13775. }
  13776. var emitterPosition = this.getEmitterPosition();
  13777. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  13778. var distance = direction.length();
  13779. direction.normalize();
  13780. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  13781. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  13782. return !pickInfo.hit || pickInfo.distance > distance;
  13783. };
  13784. LensFlareSystem.prototype.render = function () {
  13785. if (!this._effect.isReady())
  13786. return false;
  13787. var engine = this._scene.getEngine();
  13788. var viewport = this._scene.activeCamera.viewport;
  13789. var globalViewport = viewport.toGlobal(engine);
  13790. if (!this.computeEffectivePosition(globalViewport)) {
  13791. return false;
  13792. }
  13793. if (!this._isVisible()) {
  13794. return false;
  13795. }
  13796. var awayX;
  13797. var awayY;
  13798. if (this._positionX < this.borderLimit + globalViewport.x) {
  13799. awayX = this.borderLimit + globalViewport.x - this._positionX;
  13800. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  13801. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  13802. } else {
  13803. awayX = 0;
  13804. }
  13805. if (this._positionY < this.borderLimit + globalViewport.y) {
  13806. awayY = this.borderLimit + globalViewport.y - this._positionY;
  13807. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  13808. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  13809. } else {
  13810. awayY = 0;
  13811. }
  13812. var away = (awayX > awayY) ? awayX : awayY;
  13813. if (away > this.borderLimit) {
  13814. away = this.borderLimit;
  13815. }
  13816. var intensity = 1.0 - (away / this.borderLimit);
  13817. if (intensity < 0) {
  13818. return false;
  13819. }
  13820. if (intensity > 1.0) {
  13821. intensity = 1.0;
  13822. }
  13823. var centerX = globalViewport.x + globalViewport.width / 2;
  13824. var centerY = globalViewport.y + globalViewport.height / 2;
  13825. var distX = centerX - this._positionX;
  13826. var distY = centerY - this._positionY;
  13827. engine.enableEffect(this._effect);
  13828. engine.setState(false);
  13829. engine.setDepthBuffer(false);
  13830. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  13831. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13832. for (var index = 0; index < this.lensFlares.length; index++) {
  13833. var flare = this.lensFlares[index];
  13834. var x = centerX - (distX * flare.position);
  13835. var y = centerY - (distY * flare.position);
  13836. var cw = flare.size;
  13837. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  13838. var cx = 2 * (x / globalViewport.width) - 1.0;
  13839. var cy = 1.0 - 2 * (y / globalViewport.height);
  13840. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  13841. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  13842. this._effect.setTexture("textureSampler", flare.texture);
  13843. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  13844. engine.draw(true, 0, 6);
  13845. }
  13846. engine.setDepthBuffer(true);
  13847. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13848. return true;
  13849. };
  13850. LensFlareSystem.prototype.dispose = function () {
  13851. if (this._vertexBuffer) {
  13852. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13853. this._vertexBuffer = null;
  13854. }
  13855. if (this._indexBuffer) {
  13856. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13857. this._indexBuffer = null;
  13858. }
  13859. while (this.lensFlares.length) {
  13860. this.lensFlares[0].dispose();
  13861. }
  13862. var index = this._scene.lensFlareSystems.indexOf(this);
  13863. this._scene.lensFlareSystems.splice(index, 1);
  13864. };
  13865. return LensFlareSystem;
  13866. })();
  13867. BABYLON.LensFlareSystem = LensFlareSystem;
  13868. })(BABYLON || (BABYLON = {}));
  13869. var BABYLON;
  13870. (function (BABYLON) {
  13871. var IntersectionInfo = (function () {
  13872. function IntersectionInfo(bu, bv, distance) {
  13873. this.bu = bu;
  13874. this.bv = bv;
  13875. this.distance = distance;
  13876. this.faceId = 0;
  13877. }
  13878. return IntersectionInfo;
  13879. })();
  13880. BABYLON.IntersectionInfo = IntersectionInfo;
  13881. var PickingInfo = (function () {
  13882. function PickingInfo() {
  13883. this.hit = false;
  13884. this.distance = 0;
  13885. this.pickedPoint = null;
  13886. this.pickedMesh = null;
  13887. this.bu = 0;
  13888. this.bv = 0;
  13889. this.faceId = -1;
  13890. }
  13891. PickingInfo.prototype.getNormal = function () {
  13892. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13893. return null;
  13894. }
  13895. var indices = this.pickedMesh.getIndices();
  13896. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13897. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  13898. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  13899. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  13900. normal0 = normal0.scale(this.bu);
  13901. normal1 = normal1.scale(this.bv);
  13902. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  13903. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  13904. };
  13905. PickingInfo.prototype.getTextureCoordinates = function () {
  13906. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13907. return null;
  13908. }
  13909. var indices = this.pickedMesh.getIndices();
  13910. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  13911. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  13912. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  13913. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  13914. uv0 = uv0.scale(this.bu);
  13915. uv1 = uv1.scale(this.bv);
  13916. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  13917. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  13918. };
  13919. return PickingInfo;
  13920. })();
  13921. BABYLON.PickingInfo = PickingInfo;
  13922. })(BABYLON || (BABYLON = {}));
  13923. var BABYLON;
  13924. (function (BABYLON) {
  13925. var FilesInput = (function () {
  13926. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  13927. this.engine = p_engine;
  13928. this.canvas = p_canvas;
  13929. this.currentScene = p_scene;
  13930. this.sceneLoadedCallback = p_sceneLoadedCallback;
  13931. this.progressCallback = p_progressCallback;
  13932. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  13933. this.textureLoadingCallback = p_textureLoadingCallback;
  13934. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  13935. }
  13936. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  13937. var _this = this;
  13938. if (p_elementToMonitor) {
  13939. this.elementToMonitor = p_elementToMonitor;
  13940. this.elementToMonitor.addEventListener("dragenter", function (e) {
  13941. _this.drag(e);
  13942. }, false);
  13943. this.elementToMonitor.addEventListener("dragover", function (e) {
  13944. _this.drag(e);
  13945. }, false);
  13946. this.elementToMonitor.addEventListener("drop", function (e) {
  13947. _this.drop(e);
  13948. }, false);
  13949. }
  13950. };
  13951. FilesInput.prototype.renderFunction = function () {
  13952. if (this.additionnalRenderLoopLogicCallback) {
  13953. this.additionnalRenderLoopLogicCallback();
  13954. }
  13955. if (this.currentScene) {
  13956. if (this.textureLoadingCallback) {
  13957. var remaining = this.currentScene.getWaitingItemsCount();
  13958. if (remaining > 0) {
  13959. this.textureLoadingCallback(remaining);
  13960. }
  13961. }
  13962. this.currentScene.render();
  13963. }
  13964. };
  13965. FilesInput.prototype.drag = function (e) {
  13966. e.stopPropagation();
  13967. e.preventDefault();
  13968. };
  13969. FilesInput.prototype.drop = function (eventDrop) {
  13970. eventDrop.stopPropagation();
  13971. eventDrop.preventDefault();
  13972. this.loadFiles(eventDrop);
  13973. };
  13974. FilesInput.prototype.loadFiles = function (event) {
  13975. var _this = this;
  13976. var that = this;
  13977. if (this.startingProcessingFilesCallback)
  13978. this.startingProcessingFilesCallback();
  13979. var sceneFileToLoad;
  13980. var filesToLoad;
  13981. if (event && event.dataTransfer && event.dataTransfer.files) {
  13982. filesToLoad = event.dataTransfer.files;
  13983. }
  13984. if (event && event.target && event.target.files) {
  13985. filesToLoad = event.target.files;
  13986. }
  13987. if (filesToLoad && filesToLoad.length > 0) {
  13988. for (var i = 0; i < filesToLoad.length; i++) {
  13989. switch (filesToLoad[i].type) {
  13990. case "image/jpeg":
  13991. case "image/png":
  13992. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  13993. break;
  13994. case "image/targa":
  13995. case "image/vnd.ms-dds":
  13996. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  13997. break;
  13998. default:
  13999. 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) {
  14000. sceneFileToLoad = filesToLoad[i];
  14001. }
  14002. break;
  14003. }
  14004. }
  14005. if (sceneFileToLoad) {
  14006. if (this.currentScene) {
  14007. this.engine.stopRenderLoop();
  14008. this.currentScene.dispose();
  14009. }
  14010. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  14011. that.currentScene = newScene;
  14012. that.currentScene.executeWhenReady(function () {
  14013. if (that.currentScene.activeCamera) {
  14014. that.currentScene.activeCamera.attachControl(that.canvas);
  14015. }
  14016. if (that.sceneLoadedCallback) {
  14017. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  14018. }
  14019. that.engine.runRenderLoop(function () {
  14020. that.renderFunction();
  14021. });
  14022. });
  14023. }, function (progress) {
  14024. if (_this.progressCallback) {
  14025. _this.progressCallback(progress);
  14026. }
  14027. });
  14028. } else {
  14029. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  14030. }
  14031. }
  14032. };
  14033. FilesInput.FilesTextures = new Array();
  14034. FilesInput.FilesToLoad = new Array();
  14035. return FilesInput;
  14036. })();
  14037. BABYLON.FilesInput = FilesInput;
  14038. })(BABYLON || (BABYLON = {}));
  14039. var BABYLON;
  14040. (function (BABYLON) {
  14041. var OimoJSPlugin = (function () {
  14042. function OimoJSPlugin() {
  14043. this._registeredMeshes = [];
  14044. /**
  14045. * Update the body position according to the mesh position
  14046. * @param mesh
  14047. */
  14048. this.updateBodyPosition = function (mesh) {
  14049. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14050. var registeredMesh = this._registeredMeshes[index];
  14051. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  14052. var body = registeredMesh.body.body;
  14053. mesh.computeWorldMatrix(true);
  14054. var center = mesh.getBoundingInfo().boundingBox.center;
  14055. body.setPosition(center.x, center.y, center.z);
  14056. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  14057. return;
  14058. }
  14059. if (registeredMesh.mesh.parent === mesh) {
  14060. mesh.computeWorldMatrix(true);
  14061. registeredMesh.mesh.computeWorldMatrix(true);
  14062. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  14063. var absoluteRotation = mesh.rotation;
  14064. body = registeredMesh.body.body;
  14065. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  14066. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  14067. return;
  14068. }
  14069. }
  14070. };
  14071. }
  14072. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  14073. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  14074. };
  14075. OimoJSPlugin.prototype.initialize = function (iterations) {
  14076. this._world = new OIMO.World();
  14077. this._world.clear();
  14078. };
  14079. OimoJSPlugin.prototype.setGravity = function (gravity) {
  14080. this._world.gravity = gravity;
  14081. };
  14082. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  14083. var body = null;
  14084. this.unregisterMesh(mesh);
  14085. mesh.computeWorldMatrix(true);
  14086. switch (impostor) {
  14087. case BABYLON.PhysicsEngine.SphereImpostor:
  14088. var bbox = mesh.getBoundingInfo().boundingBox;
  14089. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  14090. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  14091. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  14092. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  14093. var deltaPosition = mesh.position.subtract(bbox.center);
  14094. body = new OIMO.Body({
  14095. type: 'sphere',
  14096. size: [size],
  14097. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  14098. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  14099. move: options.mass != 0,
  14100. config: [options.mass, options.friction, options.restitution],
  14101. world: this._world
  14102. });
  14103. this._registeredMeshes.push({
  14104. mesh: mesh,
  14105. body: body,
  14106. delta: deltaPosition
  14107. });
  14108. break;
  14109. case BABYLON.PhysicsEngine.PlaneImpostor:
  14110. case BABYLON.PhysicsEngine.BoxImpostor:
  14111. bbox = mesh.getBoundingInfo().boundingBox;
  14112. var min = bbox.minimumWorld;
  14113. var max = bbox.maximumWorld;
  14114. var box = max.subtract(min);
  14115. var sizeX = this._checkWithEpsilon(box.x);
  14116. var sizeY = this._checkWithEpsilon(box.y);
  14117. var sizeZ = this._checkWithEpsilon(box.z);
  14118. var deltaPosition = mesh.position.subtract(bbox.center);
  14119. body = new OIMO.Body({
  14120. type: 'box',
  14121. size: [sizeX, sizeY, sizeZ],
  14122. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  14123. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  14124. move: options.mass != 0,
  14125. config: [options.mass, options.friction, options.restitution],
  14126. world: this._world
  14127. });
  14128. this._registeredMeshes.push({
  14129. mesh: mesh,
  14130. body: body,
  14131. delta: deltaPosition
  14132. });
  14133. break;
  14134. }
  14135. return body;
  14136. };
  14137. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  14138. var types = [], sizes = [], positions = [], rotations = [];
  14139. var initialMesh = parts[0].mesh;
  14140. for (var index = 0; index < parts.length; index++) {
  14141. var part = parts[index];
  14142. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  14143. types.push(bodyParameters.type);
  14144. sizes.push.apply(sizes, bodyParameters.size);
  14145. positions.push.apply(positions, bodyParameters.pos);
  14146. rotations.push.apply(rotations, bodyParameters.rot);
  14147. }
  14148. var body = new OIMO.Body({
  14149. type: types,
  14150. size: sizes,
  14151. pos: positions,
  14152. rot: rotations,
  14153. move: options.mass != 0,
  14154. config: [options.mass, options.friction, options.restitution],
  14155. world: this._world
  14156. });
  14157. this._registeredMeshes.push({
  14158. mesh: initialMesh,
  14159. body: body
  14160. });
  14161. return body;
  14162. };
  14163. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  14164. var bodyParameters = null;
  14165. var mesh = part.mesh;
  14166. switch (part.impostor) {
  14167. case BABYLON.PhysicsEngine.SphereImpostor:
  14168. var bbox = mesh.getBoundingInfo().boundingBox;
  14169. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  14170. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  14171. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  14172. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  14173. bodyParameters = {
  14174. type: 'sphere',
  14175. /* bug with oimo : sphere needs 3 sizes in this case */
  14176. size: [size, -1, -1],
  14177. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  14178. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  14179. };
  14180. break;
  14181. case BABYLON.PhysicsEngine.PlaneImpostor:
  14182. case BABYLON.PhysicsEngine.BoxImpostor:
  14183. bbox = mesh.getBoundingInfo().boundingBox;
  14184. var min = bbox.minimumWorld;
  14185. var max = bbox.maximumWorld;
  14186. var box = max.subtract(min);
  14187. var sizeX = this._checkWithEpsilon(box.x);
  14188. var sizeY = this._checkWithEpsilon(box.y);
  14189. var sizeZ = this._checkWithEpsilon(box.z);
  14190. var relativePosition = mesh.position;
  14191. bodyParameters = {
  14192. type: 'box',
  14193. size: [sizeX, sizeY, sizeZ],
  14194. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  14195. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  14196. };
  14197. break;
  14198. }
  14199. return bodyParameters;
  14200. };
  14201. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  14202. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14203. var registeredMesh = this._registeredMeshes[index];
  14204. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  14205. if (registeredMesh.body) {
  14206. this._world.removeRigidBody(registeredMesh.body.body);
  14207. this._unbindBody(registeredMesh.body);
  14208. }
  14209. this._registeredMeshes.splice(index, 1);
  14210. return;
  14211. }
  14212. }
  14213. };
  14214. OimoJSPlugin.prototype._unbindBody = function (body) {
  14215. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14216. var registeredMesh = this._registeredMeshes[index];
  14217. if (registeredMesh.body === body) {
  14218. registeredMesh.body = null;
  14219. }
  14220. }
  14221. };
  14222. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  14223. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14224. var registeredMesh = this._registeredMeshes[index];
  14225. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  14226. var mass = registeredMesh.body.body.massInfo.mass;
  14227. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  14228. return;
  14229. }
  14230. }
  14231. };
  14232. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  14233. var body1 = null, body2 = null;
  14234. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14235. var registeredMesh = this._registeredMeshes[index];
  14236. if (registeredMesh.mesh === mesh1) {
  14237. body1 = registeredMesh.body.body;
  14238. } else if (registeredMesh.mesh === mesh2) {
  14239. body2 = registeredMesh.body.body;
  14240. }
  14241. }
  14242. if (!body1 || !body2) {
  14243. return false;
  14244. }
  14245. if (!options) {
  14246. options = {};
  14247. }
  14248. new OIMO.Link({
  14249. type: options.type,
  14250. body1: body1,
  14251. body2: body2,
  14252. min: options.min,
  14253. max: options.max,
  14254. axe1: options.axe1,
  14255. axe2: options.axe2,
  14256. pos1: [pivot1.x, pivot1.y, pivot1.z],
  14257. pos2: [pivot2.x, pivot2.y, pivot2.z],
  14258. collision: options.collision,
  14259. spring: options.spring,
  14260. world: this._world
  14261. });
  14262. return true;
  14263. };
  14264. OimoJSPlugin.prototype.dispose = function () {
  14265. this._world.clear();
  14266. while (this._registeredMeshes.length) {
  14267. this.unregisterMesh(this._registeredMeshes[0].mesh);
  14268. }
  14269. };
  14270. OimoJSPlugin.prototype.isSupported = function () {
  14271. return OIMO !== undefined;
  14272. };
  14273. OimoJSPlugin.prototype._getLastShape = function (body) {
  14274. var lastShape = body.shapes;
  14275. while (lastShape.next) {
  14276. lastShape = lastShape.next;
  14277. }
  14278. return lastShape;
  14279. };
  14280. OimoJSPlugin.prototype.runOneStep = function (time) {
  14281. this._world.step();
  14282. var i = this._registeredMeshes.length;
  14283. var m;
  14284. while (i--) {
  14285. var body = this._registeredMeshes[i].body.body;
  14286. var mesh = this._registeredMeshes[i].mesh;
  14287. var delta = this._registeredMeshes[i].delta;
  14288. if (!body.sleeping) {
  14289. if (body.shapes.next) {
  14290. var parentShape = this._getLastShape(body);
  14291. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  14292. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  14293. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  14294. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  14295. if (!mesh.rotationQuaternion) {
  14296. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  14297. }
  14298. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  14299. } else {
  14300. m = body.getMatrix();
  14301. mtx = BABYLON.Matrix.FromArray(m);
  14302. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  14303. if (!delta) {
  14304. mesh.position.x = bodyX;
  14305. mesh.position.y = bodyY;
  14306. mesh.position.z = bodyZ;
  14307. } else {
  14308. mesh.position.x = bodyX + delta.x;
  14309. mesh.position.y = bodyY + delta.y;
  14310. mesh.position.z = bodyZ + delta.z;
  14311. }
  14312. if (!mesh.rotationQuaternion) {
  14313. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  14314. }
  14315. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  14316. }
  14317. }
  14318. }
  14319. };
  14320. return OimoJSPlugin;
  14321. })();
  14322. BABYLON.OimoJSPlugin = OimoJSPlugin;
  14323. })(BABYLON || (BABYLON = {}));
  14324. var BABYLON;
  14325. (function (BABYLON) {
  14326. var PhysicsEngine = (function () {
  14327. function PhysicsEngine(plugin) {
  14328. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  14329. }
  14330. PhysicsEngine.prototype._initialize = function (gravity) {
  14331. this._currentPlugin.initialize();
  14332. this._setGravity(gravity);
  14333. };
  14334. PhysicsEngine.prototype._runOneStep = function (delta) {
  14335. if (delta > 0.1) {
  14336. delta = 0.1;
  14337. } else if (delta <= 0) {
  14338. delta = 1.0 / 60.0;
  14339. }
  14340. this._currentPlugin.runOneStep(delta);
  14341. };
  14342. PhysicsEngine.prototype._setGravity = function (gravity) {
  14343. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  14344. this._currentPlugin.setGravity(this.gravity);
  14345. };
  14346. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  14347. return this._currentPlugin.registerMesh(mesh, impostor, options);
  14348. };
  14349. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  14350. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  14351. };
  14352. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  14353. this._currentPlugin.unregisterMesh(mesh);
  14354. };
  14355. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  14356. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  14357. };
  14358. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  14359. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  14360. };
  14361. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  14362. this._currentPlugin.updateBodyPosition(mesh);
  14363. };
  14364. PhysicsEngine.prototype.dispose = function () {
  14365. this._currentPlugin.dispose();
  14366. };
  14367. PhysicsEngine.prototype.isSupported = function () {
  14368. return this._currentPlugin.isSupported();
  14369. };
  14370. PhysicsEngine.NoImpostor = 0;
  14371. PhysicsEngine.SphereImpostor = 1;
  14372. PhysicsEngine.BoxImpostor = 2;
  14373. PhysicsEngine.PlaneImpostor = 3;
  14374. PhysicsEngine.MeshImpostor = 4;
  14375. PhysicsEngine.CapsuleImpostor = 5;
  14376. PhysicsEngine.ConeImpostor = 6;
  14377. PhysicsEngine.CylinderImpostor = 7;
  14378. PhysicsEngine.ConvexHullImpostor = 8;
  14379. PhysicsEngine.Epsilon = 0.001;
  14380. return PhysicsEngine;
  14381. })();
  14382. BABYLON.PhysicsEngine = PhysicsEngine;
  14383. })(BABYLON || (BABYLON = {}));
  14384. var BABYLON;
  14385. (function (BABYLON) {
  14386. var serializeLight = function (light) {
  14387. var serializationObject = {};
  14388. serializationObject.name = light.name;
  14389. serializationObject.id = light.id;
  14390. serializationObject.tags = BABYLON.Tags.GetTags(light);
  14391. if (light instanceof BABYLON.PointLight) {
  14392. serializationObject.type = 0;
  14393. serializationObject.position = light.position.asArray();
  14394. } else if (light instanceof BABYLON.DirectionalLight) {
  14395. serializationObject.type = 1;
  14396. var directionalLight = light;
  14397. serializationObject.position = directionalLight.position.asArray();
  14398. serializationObject.direction = directionalLight.direction.asArray();
  14399. } else if (light instanceof BABYLON.SpotLight) {
  14400. serializationObject.type = 2;
  14401. var spotLight = light;
  14402. serializationObject.position = spotLight.position.asArray();
  14403. serializationObject.direction = spotLight.position.asArray();
  14404. serializationObject.angle = spotLight.angle;
  14405. serializationObject.exponent = spotLight.exponent;
  14406. } else if (light instanceof BABYLON.HemisphericLight) {
  14407. serializationObject.type = 3;
  14408. var hemisphericLight = light;
  14409. serializationObject.direction = hemisphericLight.direction.asArray();
  14410. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  14411. }
  14412. if (light.intensity) {
  14413. serializationObject.intensity = light.intensity;
  14414. }
  14415. serializationObject.range = light.range;
  14416. serializationObject.diffuse = light.diffuse.asArray();
  14417. serializationObject.specular = light.specular.asArray();
  14418. return serializationObject;
  14419. };
  14420. var serializeFresnelParameter = function (fresnelParameter) {
  14421. var serializationObject = {};
  14422. serializationObject.isEnabled = fresnelParameter.isEnabled;
  14423. serializationObject.leftColor = fresnelParameter.leftColor;
  14424. serializationObject.rightColor = fresnelParameter.rightColor;
  14425. serializationObject.bias = fresnelParameter.bias;
  14426. serializationObject.power = fresnelParameter.power;
  14427. return serializationObject;
  14428. };
  14429. var serializeCamera = function (camera) {
  14430. var serializationObject = {};
  14431. serializationObject.name = camera.name;
  14432. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  14433. serializationObject.id = camera.id;
  14434. serializationObject.position = camera.position.asArray();
  14435. if (camera.parent) {
  14436. serializationObject.parentId = camera.parent.id;
  14437. }
  14438. serializationObject.rotation = camera.rotation.asArray();
  14439. if (camera.lockedTarget && camera.lockedTarget.id) {
  14440. serializationObject.lockedTargetId = camera.lockedTarget.id;
  14441. }
  14442. serializationObject.fov = camera.fov;
  14443. serializationObject.minZ = camera.minZ;
  14444. serializationObject.maxZ = camera.maxZ;
  14445. serializationObject.speed = camera.speed;
  14446. serializationObject.inertia = camera.inertia;
  14447. serializationObject.checkCollisions = camera.checkCollisions;
  14448. serializationObject.applyGravity = camera.applyGravity;
  14449. if (camera.ellipsoid) {
  14450. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  14451. }
  14452. appendAnimations(camera, serializationObject);
  14453. serializationObject.layerMask = camera.layerMask;
  14454. return serializationObject;
  14455. };
  14456. var appendAnimations = function (source, destination) {
  14457. if (source.animations) {
  14458. destination.animations = [];
  14459. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  14460. var animation = source.animations[animationIndex];
  14461. destination.animations.push(serializeAnimation(animation));
  14462. }
  14463. }
  14464. };
  14465. var serializeAnimation = function (animation) {
  14466. var serializationObject = {};
  14467. serializationObject.name = animation.name;
  14468. serializationObject.property = animation.targetProperty;
  14469. serializationObject.framePerSecond = animation.framePerSecond;
  14470. serializationObject.dataType = animation.dataType;
  14471. serializationObject.loopBehavior = animation.loopMode;
  14472. var dataType = animation.dataType;
  14473. serializationObject.keys = [];
  14474. var keys = animation.getKeys();
  14475. for (var index = 0; index < keys.length; index++) {
  14476. var animationKey = keys[index];
  14477. var key = {};
  14478. key.frame = animationKey.frame;
  14479. switch (dataType) {
  14480. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  14481. key.values = [animationKey.value];
  14482. break;
  14483. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  14484. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  14485. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  14486. key.values = animationKey.value.asArray();
  14487. break;
  14488. }
  14489. serializationObject.keys.push(key);
  14490. }
  14491. return serializationObject;
  14492. };
  14493. var serializeMultiMaterial = function (material) {
  14494. var serializationObject = {};
  14495. serializationObject.name = material.name;
  14496. serializationObject.id = material.id;
  14497. serializationObject.tags = BABYLON.Tags.GetTags(material);
  14498. serializationObject.materials = [];
  14499. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  14500. var subMat = material.subMaterials[matIndex];
  14501. if (subMat) {
  14502. serializationObject.materials.push(subMat.id);
  14503. } else {
  14504. serializationObject.materials.push(null);
  14505. }
  14506. }
  14507. return serializationObject;
  14508. };
  14509. var serializeMaterial = function (material) {
  14510. var serializationObject = {};
  14511. serializationObject.name = material.name;
  14512. serializationObject.ambient = material.ambientColor.asArray();
  14513. serializationObject.diffuse = material.diffuseColor.asArray();
  14514. serializationObject.specular = material.specularColor.asArray();
  14515. serializationObject.specularPower = material.specularPower;
  14516. serializationObject.emissive = material.emissiveColor.asArray();
  14517. serializationObject.alpha = material.alpha;
  14518. serializationObject.id = material.id;
  14519. serializationObject.tags = BABYLON.Tags.GetTags(material);
  14520. serializationObject.backFaceCulling = material.backFaceCulling;
  14521. if (material.diffuseTexture) {
  14522. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  14523. }
  14524. if (material.diffuseFresnelParameters) {
  14525. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  14526. }
  14527. if (material.ambientTexture) {
  14528. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  14529. }
  14530. if (material.opacityTexture) {
  14531. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  14532. }
  14533. if (material.opacityFresnelParameters) {
  14534. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  14535. }
  14536. if (material.reflectionTexture) {
  14537. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  14538. }
  14539. if (material.reflectionFresnelParameters) {
  14540. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  14541. }
  14542. if (material.emissiveTexture) {
  14543. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  14544. }
  14545. if (material.emissiveFresnelParameters) {
  14546. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  14547. }
  14548. if (material.specularTexture) {
  14549. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  14550. }
  14551. if (material.bumpTexture) {
  14552. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  14553. }
  14554. return serializationObject;
  14555. };
  14556. var serializeTexture = function (texture) {
  14557. var serializationObject = {};
  14558. if (!texture.name) {
  14559. return null;
  14560. }
  14561. if (texture instanceof BABYLON.CubeTexture) {
  14562. serializationObject.name = texture.name;
  14563. serializationObject.hasAlpha = texture.hasAlpha;
  14564. serializationObject.level = texture.level;
  14565. serializationObject.coordinatesMode = texture.coordinatesMode;
  14566. return serializationObject;
  14567. }
  14568. if (texture instanceof BABYLON.MirrorTexture) {
  14569. var mirrorTexture = texture;
  14570. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  14571. serializationObject.renderList = [];
  14572. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  14573. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  14574. }
  14575. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  14576. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  14577. var renderTargetTexture = texture;
  14578. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  14579. serializationObject.renderList = [];
  14580. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  14581. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  14582. }
  14583. }
  14584. var regularTexture = texture;
  14585. serializationObject.name = texture.name;
  14586. serializationObject.hasAlpha = texture.hasAlpha;
  14587. serializationObject.level = texture.level;
  14588. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  14589. serializationObject.coordinatesMode = texture.coordinatesMode;
  14590. serializationObject.uOffset = regularTexture.uOffset;
  14591. serializationObject.vOffset = regularTexture.vOffset;
  14592. serializationObject.uScale = regularTexture.uScale;
  14593. serializationObject.vScale = regularTexture.vScale;
  14594. serializationObject.uAng = regularTexture.uAng;
  14595. serializationObject.vAng = regularTexture.vAng;
  14596. serializationObject.wAng = regularTexture.wAng;
  14597. serializationObject.wrapU = texture.wrapU;
  14598. serializationObject.wrapV = texture.wrapV;
  14599. appendAnimations(texture, serializationObject);
  14600. return serializationObject;
  14601. };
  14602. var serializeSkeleton = function (skeleton) {
  14603. var serializationObject = {};
  14604. serializationObject.name = skeleton.name;
  14605. serializationObject.id = skeleton.id;
  14606. serializationObject.bones = [];
  14607. for (var index = 0; index < skeleton.bones.length; index++) {
  14608. var bone = skeleton.bones[index];
  14609. var serializedBone = {
  14610. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  14611. name: bone.name,
  14612. matrix: bone.getLocalMatrix().toArray()
  14613. };
  14614. serializationObject.bones.push(serializedBone);
  14615. if (bone.animations && bone.animations.length > 0) {
  14616. serializedBone.animation = serializeAnimation(bone.animations[0]);
  14617. }
  14618. }
  14619. return serializationObject;
  14620. };
  14621. var serializeParticleSystem = function (particleSystem) {
  14622. var serializationObject = {};
  14623. serializationObject.emitterId = particleSystem.emitter.id;
  14624. serializationObject.capacity = particleSystem.getCapacity();
  14625. if (particleSystem.particleTexture) {
  14626. serializationObject.textureName = particleSystem.particleTexture.name;
  14627. }
  14628. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  14629. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  14630. serializationObject.minSize = particleSystem.minSize;
  14631. serializationObject.maxSize = particleSystem.maxSize;
  14632. serializationObject.minLifeTime = particleSystem.minLifeTime;
  14633. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  14634. serializationObject.emitRate = particleSystem.emitRate;
  14635. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  14636. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  14637. serializationObject.gravity = particleSystem.gravity.asArray();
  14638. serializationObject.direction1 = particleSystem.direction1.asArray();
  14639. serializationObject.direction2 = particleSystem.direction2.asArray();
  14640. serializationObject.color1 = particleSystem.color1.asArray();
  14641. serializationObject.color2 = particleSystem.color2.asArray();
  14642. serializationObject.colorDead = particleSystem.colorDead.asArray();
  14643. serializationObject.updateSpeed = particleSystem.updateSpeed;
  14644. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  14645. serializationObject.textureMask = particleSystem.textureMask.asArray();
  14646. serializationObject.blendMode = particleSystem.blendMode;
  14647. return serializationObject;
  14648. };
  14649. var serializeLensFlareSystem = function (lensFlareSystem) {
  14650. var serializationObject = {};
  14651. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  14652. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  14653. serializationObject.flares = [];
  14654. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  14655. var flare = lensFlareSystem.lensFlares[index];
  14656. serializationObject.flares.push({
  14657. size: flare.size,
  14658. position: flare.position,
  14659. color: flare.color.asArray(),
  14660. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  14661. });
  14662. }
  14663. return serializationObject;
  14664. };
  14665. var serializeShadowGenerator = function (light) {
  14666. var serializationObject = {};
  14667. var shadowGenerator = light.getShadowGenerator();
  14668. serializationObject.lightId = light.id;
  14669. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  14670. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  14671. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  14672. serializationObject.renderList = [];
  14673. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  14674. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  14675. serializationObject.renderList.push(mesh.id);
  14676. }
  14677. return serializationObject;
  14678. };
  14679. var serializedGeometries = [];
  14680. var serializeGeometry = function (geometry, serializationGeometries) {
  14681. if (serializedGeometries[geometry.id]) {
  14682. return;
  14683. }
  14684. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  14685. serializationGeometries.boxes.push(serializeBox(geometry));
  14686. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  14687. serializationGeometries.spheres.push(serializeSphere(geometry));
  14688. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  14689. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  14690. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  14691. serializationGeometries.toruses.push(serializeTorus(geometry));
  14692. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  14693. serializationGeometries.grounds.push(serializeGround(geometry));
  14694. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  14695. serializationGeometries.planes.push(serializePlane(geometry));
  14696. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  14697. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  14698. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  14699. throw new Error("Unknow primitive type");
  14700. } else {
  14701. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  14702. }
  14703. serializedGeometries[geometry.id] = true;
  14704. };
  14705. var serializeGeometryBase = function (geometry) {
  14706. var serializationObject = {};
  14707. serializationObject.id = geometry.id;
  14708. if (BABYLON.Tags.HasTags(geometry)) {
  14709. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  14710. }
  14711. return serializationObject;
  14712. };
  14713. var serializeVertexData = function (vertexData) {
  14714. var serializationObject = serializeGeometryBase(vertexData);
  14715. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14716. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14717. }
  14718. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14719. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14720. }
  14721. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14722. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14723. }
  14724. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14725. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  14726. }
  14727. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14728. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  14729. }
  14730. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  14731. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  14732. serializationObject.matricesIndices._isExpanded = true;
  14733. }
  14734. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  14735. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  14736. }
  14737. serializationObject.indices = vertexData.getIndices();
  14738. return serializationObject;
  14739. };
  14740. var serializePrimitive = function (primitive) {
  14741. var serializationObject = serializeGeometryBase(primitive);
  14742. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  14743. return serializationObject;
  14744. };
  14745. var serializeBox = function (box) {
  14746. var serializationObject = serializePrimitive(box);
  14747. serializationObject.size = box.size;
  14748. return serializationObject;
  14749. };
  14750. var serializeSphere = function (sphere) {
  14751. var serializationObject = serializePrimitive(sphere);
  14752. serializationObject.segments = sphere.segments;
  14753. serializationObject.diameter = sphere.diameter;
  14754. return serializationObject;
  14755. };
  14756. var serializeCylinder = function (cylinder) {
  14757. var serializationObject = serializePrimitive(cylinder);
  14758. serializationObject.height = cylinder.height;
  14759. serializationObject.diameterTop = cylinder.diameterTop;
  14760. serializationObject.diameterBottom = cylinder.diameterBottom;
  14761. serializationObject.tessellation = cylinder.tessellation;
  14762. return serializationObject;
  14763. };
  14764. var serializeTorus = function (torus) {
  14765. var serializationObject = serializePrimitive(torus);
  14766. serializationObject.diameter = torus.diameter;
  14767. serializationObject.thickness = torus.thickness;
  14768. serializationObject.tessellation = torus.tessellation;
  14769. return serializationObject;
  14770. };
  14771. var serializeGround = function (ground) {
  14772. var serializationObject = serializePrimitive(ground);
  14773. serializationObject.width = ground.width;
  14774. serializationObject.height = ground.height;
  14775. serializationObject.subdivisions = ground.subdivisions;
  14776. return serializationObject;
  14777. };
  14778. var serializePlane = function (plane) {
  14779. var serializationObject = serializePrimitive(plane);
  14780. serializationObject.size = plane.size;
  14781. return serializationObject;
  14782. };
  14783. var serializeTorusKnot = function (torusKnot) {
  14784. var serializationObject = serializePrimitive(torusKnot);
  14785. serializationObject.radius = torusKnot.radius;
  14786. serializationObject.tube = torusKnot.tube;
  14787. serializationObject.radialSegments = torusKnot.radialSegments;
  14788. serializationObject.tubularSegments = torusKnot.tubularSegments;
  14789. serializationObject.p = torusKnot.p;
  14790. serializationObject.q = torusKnot.q;
  14791. return serializationObject;
  14792. };
  14793. var serializeMesh = function (mesh, serializationScene) {
  14794. var serializationObject = {};
  14795. serializationObject.name = mesh.name;
  14796. serializationObject.id = mesh.id;
  14797. if (BABYLON.Tags.HasTags(mesh)) {
  14798. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  14799. }
  14800. serializationObject.position = mesh.position.asArray();
  14801. if (mesh.rotationQuaternion) {
  14802. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  14803. } else if (mesh.rotation) {
  14804. serializationObject.rotation = mesh.rotation.asArray();
  14805. }
  14806. serializationObject.scaling = mesh.scaling.asArray();
  14807. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  14808. serializationObject.isEnabled = mesh.isEnabled();
  14809. serializationObject.isVisible = mesh.isVisible;
  14810. serializationObject.infiniteDistance = mesh.infiniteDistance;
  14811. serializationObject.pickable = mesh.isPickable;
  14812. serializationObject.receiveShadows = mesh.receiveShadows;
  14813. serializationObject.billboardMode = mesh.billboardMode;
  14814. serializationObject.visibility = mesh.visibility;
  14815. serializationObject.checkCollisions = mesh.checkCollisions;
  14816. if (mesh.parent) {
  14817. serializationObject.parentId = mesh.parent.id;
  14818. }
  14819. var geometry = mesh._geometry;
  14820. if (geometry) {
  14821. var geometryId = geometry.id;
  14822. serializationObject.geometryId = geometryId;
  14823. if (!mesh.getScene().getGeometryByID(geometryId)) {
  14824. serializeGeometry(geometry, serializationScene.geometries);
  14825. }
  14826. serializationObject.subMeshes = [];
  14827. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  14828. var subMesh = mesh.subMeshes[subIndex];
  14829. serializationObject.subMeshes.push({
  14830. materialIndex: subMesh.materialIndex,
  14831. verticesStart: subMesh.verticesStart,
  14832. verticesCount: subMesh.verticesCount,
  14833. indexStart: subMesh.indexStart,
  14834. indexCount: subMesh.indexCount
  14835. });
  14836. }
  14837. }
  14838. if (mesh.material) {
  14839. serializationObject.materialId = mesh.material.id;
  14840. } else {
  14841. mesh.material = null;
  14842. }
  14843. if (mesh.skeleton) {
  14844. serializationObject.skeletonId = mesh.skeleton.id;
  14845. }
  14846. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  14847. serializationObject.physicsMass = mesh.getPhysicsMass();
  14848. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  14849. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  14850. switch (mesh.getPhysicsImpostor()) {
  14851. case BABYLON.PhysicsEngine.BoxImpostor:
  14852. serializationObject.physicsImpostor = 1;
  14853. break;
  14854. case BABYLON.PhysicsEngine.SphereImpostor:
  14855. serializationObject.physicsImpostor = 2;
  14856. break;
  14857. }
  14858. }
  14859. serializationObject.instances = [];
  14860. for (var index = 0; index < mesh.instances.length; index++) {
  14861. var instance = mesh.instances[index];
  14862. var serializationInstance = {
  14863. name: instance.name,
  14864. position: instance.position,
  14865. rotation: instance.rotation,
  14866. rotationQuaternion: instance.rotationQuaternion,
  14867. scaling: instance.scaling
  14868. };
  14869. serializationObject.instances.push(serializationInstance);
  14870. appendAnimations(instance, serializationInstance);
  14871. }
  14872. appendAnimations(mesh, serializationObject);
  14873. serializationObject.layerMask = mesh.layerMask;
  14874. return serializationObject;
  14875. };
  14876. var SceneSerializer = (function () {
  14877. function SceneSerializer() {
  14878. }
  14879. SceneSerializer.Serialize = function (scene) {
  14880. var serializationObject = {};
  14881. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  14882. serializationObject.autoClear = scene.autoClear;
  14883. serializationObject.clearColor = scene.clearColor.asArray();
  14884. serializationObject.ambientColor = scene.ambientColor.asArray();
  14885. serializationObject.gravity = scene.gravity.asArray();
  14886. if (scene.fogMode && scene.fogMode !== 0) {
  14887. serializationObject.fogMode = scene.fogMode;
  14888. serializationObject.fogColor = scene.fogColor.asArray();
  14889. serializationObject.fogStart = scene.fogStart;
  14890. serializationObject.fogEnd = scene.fogEnd;
  14891. serializationObject.fogDensity = scene.fogDensity;
  14892. }
  14893. serializationObject.lights = [];
  14894. for (var index = 0; index < scene.lights.length; index++) {
  14895. var light = scene.lights[index];
  14896. serializationObject.lights.push(serializeLight(light));
  14897. }
  14898. serializationObject.cameras = [];
  14899. for (index = 0; index < scene.cameras.length; index++) {
  14900. var camera = scene.cameras[index];
  14901. if (camera instanceof BABYLON.FreeCamera) {
  14902. serializationObject.cameras.push(serializeCamera(camera));
  14903. }
  14904. }
  14905. if (scene.activeCamera) {
  14906. serializationObject.activeCameraID = scene.activeCamera.id;
  14907. }
  14908. serializationObject.materials = [];
  14909. serializationObject.multiMaterials = [];
  14910. for (index = 0; index < scene.materials.length; index++) {
  14911. var material = scene.materials[index];
  14912. if (material instanceof BABYLON.StandardMaterial) {
  14913. serializationObject.materials.push(serializeMaterial(material));
  14914. } else if (material instanceof BABYLON.MultiMaterial) {
  14915. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  14916. }
  14917. }
  14918. serializationObject.skeletons = [];
  14919. for (index = 0; index < scene.skeletons.length; index++) {
  14920. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  14921. }
  14922. serializationObject.geometries = {};
  14923. serializationObject.geometries.boxes = [];
  14924. serializationObject.geometries.spheres = [];
  14925. serializationObject.geometries.cylinders = [];
  14926. serializationObject.geometries.toruses = [];
  14927. serializationObject.geometries.grounds = [];
  14928. serializationObject.geometries.planes = [];
  14929. serializationObject.geometries.torusKnots = [];
  14930. serializationObject.geometries.vertexData = [];
  14931. serializedGeometries = [];
  14932. var geometries = scene.getGeometries();
  14933. for (var index = 0; index < geometries.length; index++) {
  14934. var geometry = geometries[index];
  14935. if (geometry.isReady()) {
  14936. serializeGeometry(geometry, serializationObject.geometries);
  14937. }
  14938. }
  14939. serializationObject.meshes = [];
  14940. for (index = 0; index < scene.meshes.length; index++) {
  14941. var abstractMesh = scene.meshes[index];
  14942. if (abstractMesh instanceof BABYLON.Mesh) {
  14943. var mesh = abstractMesh;
  14944. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  14945. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  14946. }
  14947. }
  14948. }
  14949. serializationObject.particleSystems = [];
  14950. for (index = 0; index < scene.particleSystems.length; index++) {
  14951. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  14952. }
  14953. serializationObject.lensFlareSystems = [];
  14954. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  14955. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  14956. }
  14957. serializationObject.shadowGenerators = [];
  14958. for (index = 0; index < scene.lights.length; index++) {
  14959. light = scene.lights[index];
  14960. if (light.getShadowGenerator()) {
  14961. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  14962. }
  14963. }
  14964. return serializationObject;
  14965. };
  14966. return SceneSerializer;
  14967. })();
  14968. BABYLON.SceneSerializer = SceneSerializer;
  14969. })(BABYLON || (BABYLON = {}));
  14970. var BABYLON;
  14971. (function (BABYLON) {
  14972. var SceneLoader = (function () {
  14973. function SceneLoader() {
  14974. }
  14975. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  14976. get: function () {
  14977. return SceneLoader._ForceFullSceneLoadingForIncremental;
  14978. },
  14979. set: function (value) {
  14980. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  14981. },
  14982. enumerable: true,
  14983. configurable: true
  14984. });
  14985. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  14986. get: function () {
  14987. return SceneLoader._ShowLoadingScreen;
  14988. },
  14989. set: function (value) {
  14990. SceneLoader._ShowLoadingScreen = value;
  14991. },
  14992. enumerable: true,
  14993. configurable: true
  14994. });
  14995. SceneLoader._getPluginForFilename = function (sceneFilename) {
  14996. var dotPosition = sceneFilename.lastIndexOf(".");
  14997. var queryStringPosition = sceneFilename.indexOf("?");
  14998. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  14999. for (var index = 0; index < this._registeredPlugins.length; index++) {
  15000. var plugin = this._registeredPlugins[index];
  15001. if (plugin.extensions.indexOf(extension) !== -1) {
  15002. return plugin;
  15003. }
  15004. }
  15005. return this._registeredPlugins[this._registeredPlugins.length - 1];
  15006. };
  15007. SceneLoader.RegisterPlugin = function (plugin) {
  15008. plugin.extensions = plugin.extensions.toLowerCase();
  15009. SceneLoader._registeredPlugins.push(plugin);
  15010. };
  15011. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  15012. var manifestChecked = function (success) {
  15013. scene.database = database;
  15014. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  15015. var importMeshFromData = function (data) {
  15016. var meshes = [];
  15017. var particleSystems = [];
  15018. var skeletons = [];
  15019. try {
  15020. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  15021. if (onerror) {
  15022. onerror(scene);
  15023. }
  15024. return;
  15025. }
  15026. } catch (e) {
  15027. if (onerror) {
  15028. onerror(scene);
  15029. }
  15030. return;
  15031. }
  15032. if (onsuccess) {
  15033. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  15034. onsuccess(meshes, particleSystems, skeletons);
  15035. }
  15036. };
  15037. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  15038. importMeshFromData(sceneFilename.substr(5));
  15039. return;
  15040. }
  15041. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  15042. importMeshFromData(data);
  15043. }, progressCallBack, database);
  15044. };
  15045. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  15046. };
  15047. /**
  15048. * Load a scene
  15049. * @param rootUrl a string that defines the root url for scene and resources
  15050. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  15051. * @param engine is the instance of BABYLON.Engine to use to create the scene
  15052. */
  15053. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  15054. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  15055. };
  15056. /**
  15057. * Append a scene
  15058. * @param rootUrl a string that defines the root url for scene and resources
  15059. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  15060. * @param scene is the instance of BABYLON.Scene to append to
  15061. */
  15062. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  15063. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  15064. var database;
  15065. if (SceneLoader.ShowLoadingScreen) {
  15066. scene.getEngine().displayLoadingUI();
  15067. }
  15068. var loadSceneFromData = function (data) {
  15069. scene.database = database;
  15070. if (!plugin.load(scene, data, rootUrl)) {
  15071. if (onerror) {
  15072. onerror(scene);
  15073. }
  15074. scene.getEngine().hideLoadingUI();
  15075. return;
  15076. }
  15077. if (onsuccess) {
  15078. onsuccess(scene);
  15079. }
  15080. if (SceneLoader.ShowLoadingScreen) {
  15081. scene.executeWhenReady(function () {
  15082. scene.getEngine().hideLoadingUI();
  15083. });
  15084. }
  15085. };
  15086. var manifestChecked = function (success) {
  15087. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  15088. };
  15089. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  15090. loadSceneFromData(sceneFilename.substr(5));
  15091. return;
  15092. }
  15093. if (rootUrl.indexOf("file:") === -1) {
  15094. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  15095. } else {
  15096. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  15097. }
  15098. };
  15099. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  15100. SceneLoader._ShowLoadingScreen = true;
  15101. SceneLoader._registeredPlugins = new Array();
  15102. return SceneLoader;
  15103. })();
  15104. BABYLON.SceneLoader = SceneLoader;
  15105. ;
  15106. })(BABYLON || (BABYLON = {}));
  15107. var BABYLON;
  15108. (function (BABYLON) {
  15109. (function (Internals) {
  15110. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  15111. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  15112. texture.name = parsedTexture.name;
  15113. texture.hasAlpha = parsedTexture.hasAlpha;
  15114. texture.level = parsedTexture.level;
  15115. texture.coordinatesMode = parsedTexture.coordinatesMode;
  15116. return texture;
  15117. };
  15118. var loadTexture = function (rootUrl, parsedTexture, scene) {
  15119. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  15120. return null;
  15121. }
  15122. if (parsedTexture.isCube) {
  15123. return loadCubeTexture(rootUrl, parsedTexture, scene);
  15124. }
  15125. var texture;
  15126. if (parsedTexture.mirrorPlane) {
  15127. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  15128. texture._waitingRenderList = parsedTexture.renderList;
  15129. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  15130. } else if (parsedTexture.isRenderTarget) {
  15131. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  15132. texture._waitingRenderList = parsedTexture.renderList;
  15133. } else {
  15134. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  15135. }
  15136. texture.name = parsedTexture.name;
  15137. texture.hasAlpha = parsedTexture.hasAlpha;
  15138. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  15139. texture.level = parsedTexture.level;
  15140. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  15141. texture.coordinatesMode = parsedTexture.coordinatesMode;
  15142. texture.uOffset = parsedTexture.uOffset;
  15143. texture.vOffset = parsedTexture.vOffset;
  15144. texture.uScale = parsedTexture.uScale;
  15145. texture.vScale = parsedTexture.vScale;
  15146. texture.uAng = parsedTexture.uAng;
  15147. texture.vAng = parsedTexture.vAng;
  15148. texture.wAng = parsedTexture.wAng;
  15149. texture.wrapU = parsedTexture.wrapU;
  15150. texture.wrapV = parsedTexture.wrapV;
  15151. if (parsedTexture.animations) {
  15152. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  15153. var parsedAnimation = parsedTexture.animations[animationIndex];
  15154. texture.animations.push(parseAnimation(parsedAnimation));
  15155. }
  15156. }
  15157. return texture;
  15158. };
  15159. var parseSkeleton = function (parsedSkeleton, scene) {
  15160. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  15161. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  15162. var parsedBone = parsedSkeleton.bones[index];
  15163. var parentBone = null;
  15164. if (parsedBone.parentBoneIndex > -1) {
  15165. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  15166. }
  15167. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  15168. if (parsedBone.animation) {
  15169. bone.animations.push(parseAnimation(parsedBone.animation));
  15170. }
  15171. }
  15172. return skeleton;
  15173. };
  15174. var parseFresnelParameters = function (parsedFresnelParameters) {
  15175. var fresnelParameters = new BABYLON.FresnelParameters();
  15176. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  15177. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  15178. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  15179. fresnelParameters.bias = parsedFresnelParameters.bias;
  15180. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  15181. return fresnelParameters;
  15182. };
  15183. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  15184. var material;
  15185. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  15186. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  15187. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  15188. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  15189. material.specularPower = parsedMaterial.specularPower;
  15190. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  15191. material.alpha = parsedMaterial.alpha;
  15192. material.id = parsedMaterial.id;
  15193. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  15194. material.backFaceCulling = parsedMaterial.backFaceCulling;
  15195. material.wireframe = parsedMaterial.wireframe;
  15196. if (parsedMaterial.diffuseTexture) {
  15197. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  15198. }
  15199. if (parsedMaterial.diffuseFresnelParameters) {
  15200. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  15201. }
  15202. if (parsedMaterial.ambientTexture) {
  15203. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  15204. }
  15205. if (parsedMaterial.opacityTexture) {
  15206. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  15207. }
  15208. if (parsedMaterial.opacityFresnelParameters) {
  15209. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  15210. }
  15211. if (parsedMaterial.reflectionTexture) {
  15212. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  15213. }
  15214. if (parsedMaterial.reflectionFresnelParameters) {
  15215. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  15216. }
  15217. if (parsedMaterial.emissiveTexture) {
  15218. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  15219. }
  15220. if (parsedMaterial.emissiveFresnelParameters) {
  15221. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  15222. }
  15223. if (parsedMaterial.specularTexture) {
  15224. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  15225. }
  15226. if (parsedMaterial.bumpTexture) {
  15227. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  15228. }
  15229. return material;
  15230. };
  15231. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  15232. for (var index = 0; index < parsedData.materials.length; index++) {
  15233. var parsedMaterial = parsedData.materials[index];
  15234. if (parsedMaterial.id === id) {
  15235. return parseMaterial(parsedMaterial, scene, rootUrl);
  15236. }
  15237. }
  15238. return null;
  15239. };
  15240. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  15241. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  15242. multiMaterial.id = parsedMultiMaterial.id;
  15243. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  15244. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  15245. var subMatId = parsedMultiMaterial.materials[matIndex];
  15246. if (subMatId) {
  15247. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  15248. } else {
  15249. multiMaterial.subMaterials.push(null);
  15250. }
  15251. }
  15252. return multiMaterial;
  15253. };
  15254. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  15255. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  15256. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  15257. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  15258. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  15259. var parsedFlare = parsedLensFlareSystem.flares[index];
  15260. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  15261. }
  15262. return lensFlareSystem;
  15263. };
  15264. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  15265. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  15266. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  15267. if (parsedParticleSystem.textureName) {
  15268. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  15269. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  15270. }
  15271. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  15272. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  15273. particleSystem.minSize = parsedParticleSystem.minSize;
  15274. particleSystem.maxSize = parsedParticleSystem.maxSize;
  15275. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  15276. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  15277. particleSystem.emitter = emitter;
  15278. particleSystem.emitRate = parsedParticleSystem.emitRate;
  15279. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  15280. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  15281. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  15282. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  15283. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  15284. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  15285. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  15286. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  15287. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  15288. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  15289. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  15290. particleSystem.blendMode = parsedParticleSystem.blendMode;
  15291. particleSystem.start();
  15292. return particleSystem;
  15293. };
  15294. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  15295. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  15296. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  15297. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  15298. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  15299. shadowGenerator.getShadowMap().renderList.push(mesh);
  15300. }
  15301. if (parsedShadowGenerator.usePoissonSampling) {
  15302. shadowGenerator.usePoissonSampling = true;
  15303. } else {
  15304. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  15305. }
  15306. return shadowGenerator;
  15307. };
  15308. var parseAnimation = function (parsedAnimation) {
  15309. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  15310. var dataType = parsedAnimation.dataType;
  15311. var keys = [];
  15312. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  15313. var key = parsedAnimation.keys[index];
  15314. var data;
  15315. switch (dataType) {
  15316. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  15317. data = key.values[0];
  15318. break;
  15319. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  15320. data = BABYLON.Quaternion.FromArray(key.values);
  15321. break;
  15322. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  15323. data = BABYLON.Matrix.FromArray(key.values);
  15324. break;
  15325. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  15326. default:
  15327. data = BABYLON.Vector3.FromArray(key.values);
  15328. break;
  15329. }
  15330. keys.push({
  15331. frame: key.frame,
  15332. value: data
  15333. });
  15334. }
  15335. animation.setKeys(keys);
  15336. return animation;
  15337. };
  15338. var parseLight = function (parsedLight, scene) {
  15339. var light;
  15340. switch (parsedLight.type) {
  15341. case 0:
  15342. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  15343. break;
  15344. case 1:
  15345. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  15346. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  15347. break;
  15348. case 2:
  15349. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  15350. break;
  15351. case 3:
  15352. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  15353. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  15354. break;
  15355. }
  15356. light.id = parsedLight.id;
  15357. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  15358. if (parsedLight.intensity !== undefined) {
  15359. light.intensity = parsedLight.intensity;
  15360. }
  15361. if (parsedLight.range) {
  15362. light.range = parsedLight.range;
  15363. }
  15364. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  15365. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  15366. if (parsedLight.excludedMeshesIds) {
  15367. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  15368. }
  15369. if (parsedLight.includedOnlyMeshesIds) {
  15370. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  15371. }
  15372. if (parsedLight.animations) {
  15373. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  15374. var parsedAnimation = parsedLight.animations[animationIndex];
  15375. light.animations.push(parseAnimation(parsedAnimation));
  15376. }
  15377. }
  15378. if (parsedLight.autoAnimate) {
  15379. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  15380. }
  15381. };
  15382. var parseCamera = function (parsedCamera, scene) {
  15383. var camera;
  15384. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  15385. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  15386. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  15387. var alpha = parsedCamera.alpha;
  15388. var beta = parsedCamera.beta;
  15389. var radius = parsedCamera.radius;
  15390. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  15391. var eye_space = parsedCamera.eye_space;
  15392. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  15393. } else {
  15394. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  15395. }
  15396. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  15397. var eye_space = parsedCamera.eye_space;
  15398. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  15399. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  15400. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  15401. } else if (parsedCamera.type === "FollowCamera") {
  15402. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  15403. camera.heightOffset = parsedCamera.heightOffset;
  15404. camera.radius = parsedCamera.radius;
  15405. camera.rotationOffset = parsedCamera.rotationOffset;
  15406. if (lockedTargetMesh)
  15407. camera.target = lockedTargetMesh;
  15408. } else if (parsedCamera.type === "GamepadCamera") {
  15409. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  15410. } else if (parsedCamera.type === "OculusCamera") {
  15411. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  15412. } else if (parsedCamera.type === "TouchCamera") {
  15413. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  15414. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  15415. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  15416. } else if (parsedCamera.type === "WebVRCamera") {
  15417. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  15418. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  15419. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  15420. } else {
  15421. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  15422. }
  15423. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  15424. camera.lockedTarget = lockedTargetMesh;
  15425. }
  15426. camera.id = parsedCamera.id;
  15427. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  15428. if (parsedCamera.parentId) {
  15429. camera._waitingParentId = parsedCamera.parentId;
  15430. }
  15431. if (parsedCamera.target) {
  15432. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15433. } else {
  15434. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  15435. }
  15436. camera.fov = parsedCamera.fov;
  15437. camera.minZ = parsedCamera.minZ;
  15438. camera.maxZ = parsedCamera.maxZ;
  15439. camera.speed = parsedCamera.speed;
  15440. camera.inertia = parsedCamera.inertia;
  15441. camera.checkCollisions = parsedCamera.checkCollisions;
  15442. camera.applyGravity = parsedCamera.applyGravity;
  15443. if (parsedCamera.ellipsoid) {
  15444. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  15445. }
  15446. if (parsedCamera.animations) {
  15447. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15448. var parsedAnimation = parsedCamera.animations[animationIndex];
  15449. camera.animations.push(parseAnimation(parsedAnimation));
  15450. }
  15451. }
  15452. if (parsedCamera.autoAnimate) {
  15453. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  15454. }
  15455. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  15456. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  15457. } else {
  15458. camera.layerMask = 0xFFFFFFFF;
  15459. }
  15460. return camera;
  15461. };
  15462. var parseGeometry = function (parsedGeometry, scene) {
  15463. var id = parsedGeometry.id;
  15464. return scene.getGeometryByID(id);
  15465. };
  15466. var parseBox = function (parsedBox, scene) {
  15467. if (parseGeometry(parsedBox, scene)) {
  15468. return null;
  15469. }
  15470. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  15471. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  15472. scene.pushGeometry(box, true);
  15473. return box;
  15474. };
  15475. var parseSphere = function (parsedSphere, scene) {
  15476. if (parseGeometry(parsedSphere, scene)) {
  15477. return null;
  15478. }
  15479. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  15480. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  15481. scene.pushGeometry(sphere, true);
  15482. return sphere;
  15483. };
  15484. var parseCylinder = function (parsedCylinder, scene) {
  15485. if (parseGeometry(parsedCylinder, scene)) {
  15486. return null;
  15487. }
  15488. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  15489. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  15490. scene.pushGeometry(cylinder, true);
  15491. return cylinder;
  15492. };
  15493. var parseTorus = function (parsedTorus, scene) {
  15494. if (parseGeometry(parsedTorus, scene)) {
  15495. return null;
  15496. }
  15497. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  15498. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  15499. scene.pushGeometry(torus, true);
  15500. return torus;
  15501. };
  15502. var parseGround = function (parsedGround, scene) {
  15503. if (parseGeometry(parsedGround, scene)) {
  15504. return null;
  15505. }
  15506. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  15507. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  15508. scene.pushGeometry(ground, true);
  15509. return ground;
  15510. };
  15511. var parsePlane = function (parsedPlane, scene) {
  15512. if (parseGeometry(parsedPlane, scene)) {
  15513. return null;
  15514. }
  15515. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  15516. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  15517. scene.pushGeometry(plane, true);
  15518. return plane;
  15519. };
  15520. var parseTorusKnot = function (parsedTorusKnot, scene) {
  15521. if (parseGeometry(parsedTorusKnot, scene)) {
  15522. return null;
  15523. }
  15524. 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);
  15525. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  15526. scene.pushGeometry(torusKnot, true);
  15527. return torusKnot;
  15528. };
  15529. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  15530. if (parseGeometry(parsedVertexData, scene)) {
  15531. return null;
  15532. }
  15533. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  15534. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  15535. if (parsedVertexData.delayLoadingFile) {
  15536. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15537. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  15538. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  15539. geometry._delayInfo = [];
  15540. if (parsedVertexData.hasUVs) {
  15541. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15542. }
  15543. if (parsedVertexData.hasUVs2) {
  15544. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15545. }
  15546. if (parsedVertexData.hasColors) {
  15547. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15548. }
  15549. if (parsedVertexData.hasMatricesIndices) {
  15550. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15551. }
  15552. if (parsedVertexData.hasMatricesWeights) {
  15553. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15554. }
  15555. geometry._delayLoadingFunction = importVertexData;
  15556. } else {
  15557. importVertexData(parsedVertexData, geometry);
  15558. }
  15559. scene.pushGeometry(geometry, true);
  15560. return geometry;
  15561. };
  15562. var parseMesh = function (parsedMesh, scene, rootUrl) {
  15563. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  15564. mesh.id = parsedMesh.id;
  15565. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15566. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15567. if (parsedMesh.rotationQuaternion) {
  15568. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15569. } else if (parsedMesh.rotation) {
  15570. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15571. }
  15572. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15573. if (parsedMesh.localMatrix) {
  15574. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15575. } else if (parsedMesh.pivotMatrix) {
  15576. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15577. }
  15578. mesh.setEnabled(parsedMesh.isEnabled);
  15579. mesh.isVisible = parsedMesh.isVisible;
  15580. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15581. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15582. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15583. if (parsedMesh.pickable !== undefined) {
  15584. mesh.isPickable = parsedMesh.pickable;
  15585. }
  15586. mesh.receiveShadows = parsedMesh.receiveShadows;
  15587. mesh.billboardMode = parsedMesh.billboardMode;
  15588. if (parsedMesh.visibility !== undefined) {
  15589. mesh.visibility = parsedMesh.visibility;
  15590. }
  15591. mesh.checkCollisions = parsedMesh.checkCollisions;
  15592. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15593. if (parsedMesh.parentId) {
  15594. mesh._waitingParentId = parsedMesh.parentId;
  15595. }
  15596. if (parsedMesh.delayLoadingFile) {
  15597. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15598. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15599. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15600. if (parsedMesh._binaryInfo) {
  15601. mesh._binaryInfo = parsedMesh._binaryInfo;
  15602. }
  15603. mesh._delayInfo = [];
  15604. if (parsedMesh.hasUVs) {
  15605. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15606. }
  15607. if (parsedMesh.hasUVs2) {
  15608. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15609. }
  15610. if (parsedMesh.hasColors) {
  15611. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15612. }
  15613. if (parsedMesh.hasMatricesIndices) {
  15614. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15615. }
  15616. if (parsedMesh.hasMatricesWeights) {
  15617. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15618. }
  15619. mesh._delayLoadingFunction = importGeometry;
  15620. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15621. mesh._checkDelayState();
  15622. }
  15623. } else {
  15624. importGeometry(parsedMesh, mesh);
  15625. }
  15626. if (parsedMesh.materialId) {
  15627. mesh.setMaterialByID(parsedMesh.materialId);
  15628. } else {
  15629. mesh.material = null;
  15630. }
  15631. if (parsedMesh.skeletonId > -1) {
  15632. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15633. }
  15634. if (parsedMesh.physicsImpostor) {
  15635. if (!scene.isPhysicsEnabled()) {
  15636. scene.enablePhysics();
  15637. }
  15638. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15639. }
  15640. if (parsedMesh.animations) {
  15641. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15642. var parsedAnimation = parsedMesh.animations[animationIndex];
  15643. mesh.animations.push(parseAnimation(parsedAnimation));
  15644. }
  15645. }
  15646. if (parsedMesh.autoAnimate) {
  15647. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15648. }
  15649. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15650. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15651. } else {
  15652. mesh.layerMask = 0xFFFFFFFF;
  15653. }
  15654. if (parsedMesh.instances) {
  15655. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15656. var parsedInstance = parsedMesh.instances[index];
  15657. var instance = mesh.createInstance(parsedInstance.name);
  15658. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  15659. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  15660. if (parsedInstance.rotationQuaternion) {
  15661. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  15662. } else if (parsedInstance.rotation) {
  15663. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  15664. }
  15665. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  15666. instance.checkCollisions = mesh.checkCollisions;
  15667. if (parsedMesh.animations) {
  15668. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15669. parsedAnimation = parsedMesh.animations[animationIndex];
  15670. instance.animations.push(parseAnimation(parsedAnimation));
  15671. }
  15672. }
  15673. }
  15674. }
  15675. return mesh;
  15676. };
  15677. var isDescendantOf = function (mesh, names, hierarchyIds) {
  15678. names = (names instanceof Array) ? names : [names];
  15679. for (var i in names) {
  15680. if (mesh.name === names[i]) {
  15681. hierarchyIds.push(mesh.id);
  15682. return true;
  15683. }
  15684. }
  15685. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  15686. hierarchyIds.push(mesh.id);
  15687. return true;
  15688. }
  15689. return false;
  15690. };
  15691. var importVertexData = function (parsedVertexData, geometry) {
  15692. var vertexData = new BABYLON.VertexData();
  15693. var positions = parsedVertexData.positions;
  15694. if (positions) {
  15695. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  15696. }
  15697. var normals = parsedVertexData.normals;
  15698. if (normals) {
  15699. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  15700. }
  15701. var uvs = parsedVertexData.uvs;
  15702. if (uvs) {
  15703. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  15704. }
  15705. var uv2s = parsedVertexData.uv2s;
  15706. if (uv2s) {
  15707. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  15708. }
  15709. var colors = parsedVertexData.colors;
  15710. if (colors) {
  15711. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  15712. }
  15713. var matricesIndices = parsedVertexData.matricesIndices;
  15714. if (matricesIndices) {
  15715. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  15716. }
  15717. var matricesWeights = parsedVertexData.matricesWeights;
  15718. if (matricesWeights) {
  15719. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  15720. }
  15721. var indices = parsedVertexData.indices;
  15722. if (indices) {
  15723. vertexData.indices = indices;
  15724. }
  15725. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  15726. };
  15727. var importGeometry = function (parsedGeometry, mesh) {
  15728. var scene = mesh.getScene();
  15729. var geometryId = parsedGeometry.geometryId;
  15730. if (geometryId) {
  15731. var geometry = scene.getGeometryByID(geometryId);
  15732. if (geometry) {
  15733. geometry.applyToMesh(mesh);
  15734. }
  15735. } else if (parsedGeometry instanceof ArrayBuffer) {
  15736. var binaryInfo = mesh._binaryInfo;
  15737. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  15738. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  15739. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  15740. }
  15741. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  15742. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  15743. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  15744. }
  15745. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  15746. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  15747. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  15748. }
  15749. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  15750. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  15751. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  15752. }
  15753. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  15754. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  15755. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  15756. }
  15757. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  15758. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  15759. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  15760. }
  15761. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  15762. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  15763. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  15764. }
  15765. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  15766. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  15767. mesh.setIndices(indicesData);
  15768. }
  15769. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  15770. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  15771. mesh.subMeshes = [];
  15772. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  15773. var materialIndex = subMeshesData[(i * 5) + 0];
  15774. var verticesStart = subMeshesData[(i * 5) + 1];
  15775. var verticesCount = subMeshesData[(i * 5) + 2];
  15776. var indexStart = subMeshesData[(i * 5) + 3];
  15777. var indexCount = subMeshesData[(i * 5) + 4];
  15778. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  15779. }
  15780. }
  15781. return;
  15782. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  15783. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  15784. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  15785. if (parsedGeometry.uvs) {
  15786. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  15787. }
  15788. if (parsedGeometry.uvs2) {
  15789. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  15790. }
  15791. if (parsedGeometry.colors) {
  15792. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, parsedGeometry.colors, false);
  15793. }
  15794. if (parsedGeometry.matricesIndices) {
  15795. if (!parsedGeometry.matricesIndices._isExpanded) {
  15796. var floatIndices = [];
  15797. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  15798. var matricesIndex = parsedGeometry.matricesIndices[i];
  15799. floatIndices.push(matricesIndex & 0x000000FF);
  15800. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  15801. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  15802. floatIndices.push(matricesIndex >> 24);
  15803. }
  15804. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  15805. } else {
  15806. delete parsedGeometry.matricesIndices._isExpanded;
  15807. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  15808. }
  15809. }
  15810. if (parsedGeometry.matricesWeights) {
  15811. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  15812. }
  15813. mesh.setIndices(parsedGeometry.indices);
  15814. }
  15815. if (parsedGeometry.subMeshes) {
  15816. mesh.subMeshes = [];
  15817. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  15818. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  15819. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  15820. }
  15821. }
  15822. if (mesh._shouldGenerateFlatShading) {
  15823. mesh.convertToFlatShadedMesh();
  15824. delete mesh._shouldGenerateFlatShading;
  15825. }
  15826. mesh.computeWorldMatrix(true);
  15827. if (scene._selectionOctree) {
  15828. scene._selectionOctree.addMesh(mesh);
  15829. }
  15830. };
  15831. BABYLON.SceneLoader.RegisterPlugin({
  15832. extensions: ".babylon",
  15833. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  15834. var parsedData = JSON.parse(data);
  15835. var loadedSkeletonsIds = [];
  15836. var loadedMaterialsIds = [];
  15837. var hierarchyIds = [];
  15838. for (var index = 0; index < parsedData.meshes.length; index++) {
  15839. var parsedMesh = parsedData.meshes[index];
  15840. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  15841. if (meshesNames instanceof Array) {
  15842. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  15843. }
  15844. if (parsedMesh.materialId) {
  15845. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  15846. if (!materialFound) {
  15847. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  15848. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  15849. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  15850. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  15851. var subMatId = parsedMultiMaterial.materials[matIndex];
  15852. loadedMaterialsIds.push(subMatId);
  15853. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  15854. }
  15855. loadedMaterialsIds.push(parsedMultiMaterial.id);
  15856. parseMultiMaterial(parsedMultiMaterial, scene);
  15857. materialFound = true;
  15858. break;
  15859. }
  15860. }
  15861. }
  15862. if (!materialFound) {
  15863. loadedMaterialsIds.push(parsedMesh.materialId);
  15864. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  15865. }
  15866. }
  15867. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  15868. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  15869. if (!skeletonAlreadyLoaded) {
  15870. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  15871. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  15872. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  15873. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  15874. loadedSkeletonsIds.push(parsedSkeleton.id);
  15875. }
  15876. }
  15877. }
  15878. }
  15879. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  15880. meshes.push(mesh);
  15881. }
  15882. }
  15883. for (index = 0; index < scene.meshes.length; index++) {
  15884. var currentMesh = scene.meshes[index];
  15885. if (currentMesh._waitingParentId) {
  15886. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  15887. currentMesh._waitingParentId = undefined;
  15888. }
  15889. }
  15890. if (parsedData.particleSystems) {
  15891. for (index = 0; index < parsedData.particleSystems.length; index++) {
  15892. var parsedParticleSystem = parsedData.particleSystems[index];
  15893. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  15894. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  15895. }
  15896. }
  15897. }
  15898. return true;
  15899. },
  15900. load: function (scene, data, rootUrl) {
  15901. var parsedData = JSON.parse(data);
  15902. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  15903. scene.autoClear = parsedData.autoClear;
  15904. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  15905. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  15906. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  15907. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  15908. scene.fogMode = parsedData.fogMode;
  15909. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  15910. scene.fogStart = parsedData.fogStart;
  15911. scene.fogEnd = parsedData.fogEnd;
  15912. scene.fogDensity = parsedData.fogDensity;
  15913. }
  15914. for (var index = 0; index < parsedData.lights.length; index++) {
  15915. var parsedLight = parsedData.lights[index];
  15916. parseLight(parsedLight, scene);
  15917. }
  15918. if (parsedData.materials) {
  15919. for (index = 0; index < parsedData.materials.length; index++) {
  15920. var parsedMaterial = parsedData.materials[index];
  15921. parseMaterial(parsedMaterial, scene, rootUrl);
  15922. }
  15923. }
  15924. if (parsedData.multiMaterials) {
  15925. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  15926. var parsedMultiMaterial = parsedData.multiMaterials[index];
  15927. parseMultiMaterial(parsedMultiMaterial, scene);
  15928. }
  15929. }
  15930. if (parsedData.skeletons) {
  15931. for (index = 0; index < parsedData.skeletons.length; index++) {
  15932. var parsedSkeleton = parsedData.skeletons[index];
  15933. parseSkeleton(parsedSkeleton, scene);
  15934. }
  15935. }
  15936. var geometries = parsedData.geometries;
  15937. if (geometries) {
  15938. var boxes = geometries.boxes;
  15939. if (boxes) {
  15940. for (index = 0; index < boxes.length; index++) {
  15941. var parsedBox = boxes[index];
  15942. parseBox(parsedBox, scene);
  15943. }
  15944. }
  15945. var spheres = geometries.spheres;
  15946. if (spheres) {
  15947. for (index = 0; index < spheres.length; index++) {
  15948. var parsedSphere = spheres[index];
  15949. parseSphere(parsedSphere, scene);
  15950. }
  15951. }
  15952. var cylinders = geometries.cylinders;
  15953. if (cylinders) {
  15954. for (index = 0; index < cylinders.length; index++) {
  15955. var parsedCylinder = cylinders[index];
  15956. parseCylinder(parsedCylinder, scene);
  15957. }
  15958. }
  15959. var toruses = geometries.toruses;
  15960. if (toruses) {
  15961. for (index = 0; index < toruses.length; index++) {
  15962. var parsedTorus = toruses[index];
  15963. parseTorus(parsedTorus, scene);
  15964. }
  15965. }
  15966. var grounds = geometries.grounds;
  15967. if (grounds) {
  15968. for (index = 0; index < grounds.length; index++) {
  15969. var parsedGround = grounds[index];
  15970. parseGround(parsedGround, scene);
  15971. }
  15972. }
  15973. var planes = geometries.planes;
  15974. if (planes) {
  15975. for (index = 0; index < planes.length; index++) {
  15976. var parsedPlane = planes[index];
  15977. parsePlane(parsedPlane, scene);
  15978. }
  15979. }
  15980. var torusKnots = geometries.torusKnots;
  15981. if (torusKnots) {
  15982. for (index = 0; index < torusKnots.length; index++) {
  15983. var parsedTorusKnot = torusKnots[index];
  15984. parseTorusKnot(parsedTorusKnot, scene);
  15985. }
  15986. }
  15987. var vertexData = geometries.vertexData;
  15988. if (vertexData) {
  15989. for (index = 0; index < vertexData.length; index++) {
  15990. var parsedVertexData = vertexData[index];
  15991. parseVertexData(parsedVertexData, scene, rootUrl);
  15992. }
  15993. }
  15994. }
  15995. for (index = 0; index < parsedData.meshes.length; index++) {
  15996. var parsedMesh = parsedData.meshes[index];
  15997. parseMesh(parsedMesh, scene, rootUrl);
  15998. }
  15999. for (index = 0; index < parsedData.cameras.length; index++) {
  16000. var parsedCamera = parsedData.cameras[index];
  16001. parseCamera(parsedCamera, scene);
  16002. }
  16003. if (parsedData.activeCameraID) {
  16004. scene.setActiveCameraByID(parsedData.activeCameraID);
  16005. }
  16006. for (index = 0; index < scene.cameras.length; index++) {
  16007. var camera = scene.cameras[index];
  16008. if (camera._waitingParentId) {
  16009. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  16010. camera._waitingParentId = undefined;
  16011. }
  16012. }
  16013. for (index = 0; index < scene.meshes.length; index++) {
  16014. var mesh = scene.meshes[index];
  16015. if (mesh._waitingParentId) {
  16016. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  16017. mesh._waitingParentId = undefined;
  16018. }
  16019. }
  16020. if (parsedData.particleSystems) {
  16021. for (index = 0; index < parsedData.particleSystems.length; index++) {
  16022. var parsedParticleSystem = parsedData.particleSystems[index];
  16023. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  16024. }
  16025. }
  16026. if (parsedData.lensFlareSystems) {
  16027. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  16028. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  16029. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  16030. }
  16031. }
  16032. if (parsedData.shadowGenerators) {
  16033. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  16034. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  16035. parseShadowGenerator(parsedShadowGenerator, scene);
  16036. }
  16037. }
  16038. return true;
  16039. }
  16040. });
  16041. })(BABYLON.Internals || (BABYLON.Internals = {}));
  16042. var Internals = BABYLON.Internals;
  16043. })(BABYLON || (BABYLON = {}));
  16044. var BABYLON;
  16045. (function (BABYLON) {
  16046. var currentCSGMeshId = 0;
  16047. var Vertex = (function () {
  16048. function Vertex(pos, normal, uv) {
  16049. this.pos = pos;
  16050. this.normal = normal;
  16051. this.uv = uv;
  16052. }
  16053. Vertex.prototype.clone = function () {
  16054. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  16055. };
  16056. Vertex.prototype.flip = function () {
  16057. this.normal = this.normal.scale(-1);
  16058. };
  16059. Vertex.prototype.interpolate = function (other, t) {
  16060. 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));
  16061. };
  16062. return Vertex;
  16063. })();
  16064. var Plane = (function () {
  16065. function Plane(normal, w) {
  16066. this.normal = normal;
  16067. this.w = w;
  16068. }
  16069. Plane.FromPoints = function (a, b, c) {
  16070. var v0 = c.subtract(a);
  16071. var v1 = b.subtract(a);
  16072. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  16073. return null;
  16074. }
  16075. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  16076. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  16077. };
  16078. Plane.prototype.clone = function () {
  16079. return new Plane(this.normal.clone(), this.w);
  16080. };
  16081. Plane.prototype.flip = function () {
  16082. this.normal.scaleInPlace(-1);
  16083. this.w = -this.w;
  16084. };
  16085. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  16086. var COPLANAR = 0;
  16087. var FRONT = 1;
  16088. var BACK = 2;
  16089. var SPANNING = 3;
  16090. var polygonType = 0;
  16091. var types = [];
  16092. for (var i = 0; i < polygon.vertices.length; i++) {
  16093. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  16094. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  16095. polygonType |= type;
  16096. types.push(type);
  16097. }
  16098. switch (polygonType) {
  16099. case COPLANAR:
  16100. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  16101. break;
  16102. case FRONT:
  16103. front.push(polygon);
  16104. break;
  16105. case BACK:
  16106. back.push(polygon);
  16107. break;
  16108. case SPANNING:
  16109. var f = [], b = [];
  16110. for (i = 0; i < polygon.vertices.length; i++) {
  16111. var j = (i + 1) % polygon.vertices.length;
  16112. var ti = types[i], tj = types[j];
  16113. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  16114. if (ti != BACK)
  16115. f.push(vi);
  16116. if (ti != FRONT)
  16117. b.push(ti != BACK ? vi.clone() : vi);
  16118. if ((ti | tj) == SPANNING) {
  16119. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  16120. var v = vi.interpolate(vj, t);
  16121. f.push(v);
  16122. b.push(v.clone());
  16123. }
  16124. }
  16125. if (f.length >= 3) {
  16126. var poly = new Polygon(f, polygon.shared);
  16127. if (poly.plane)
  16128. front.push(poly);
  16129. }
  16130. if (b.length >= 3) {
  16131. poly = new Polygon(b, polygon.shared);
  16132. if (poly.plane)
  16133. back.push(poly);
  16134. }
  16135. break;
  16136. }
  16137. };
  16138. Plane.EPSILON = 1e-5;
  16139. return Plane;
  16140. })();
  16141. var Polygon = (function () {
  16142. function Polygon(vertices, shared) {
  16143. this.vertices = vertices;
  16144. this.shared = shared;
  16145. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  16146. }
  16147. Polygon.prototype.clone = function () {
  16148. var vertices = this.vertices.map(function (v) {
  16149. return v.clone();
  16150. });
  16151. return new Polygon(vertices, this.shared);
  16152. };
  16153. Polygon.prototype.flip = function () {
  16154. this.vertices.reverse().map(function (v) {
  16155. v.flip();
  16156. });
  16157. this.plane.flip();
  16158. };
  16159. return Polygon;
  16160. })();
  16161. var Node = (function () {
  16162. function Node(polygons) {
  16163. this.plane = null;
  16164. this.front = null;
  16165. this.back = null;
  16166. this.polygons = [];
  16167. if (polygons) {
  16168. this.build(polygons);
  16169. }
  16170. }
  16171. Node.prototype.clone = function () {
  16172. var node = new Node();
  16173. node.plane = this.plane && this.plane.clone();
  16174. node.front = this.front && this.front.clone();
  16175. node.back = this.back && this.back.clone();
  16176. node.polygons = this.polygons.map(function (p) {
  16177. return p.clone();
  16178. });
  16179. return node;
  16180. };
  16181. Node.prototype.invert = function () {
  16182. for (var i = 0; i < this.polygons.length; i++) {
  16183. this.polygons[i].flip();
  16184. }
  16185. if (this.plane) {
  16186. this.plane.flip();
  16187. }
  16188. if (this.front) {
  16189. this.front.invert();
  16190. }
  16191. if (this.back) {
  16192. this.back.invert();
  16193. }
  16194. var temp = this.front;
  16195. this.front = this.back;
  16196. this.back = temp;
  16197. };
  16198. Node.prototype.clipPolygons = function (polygons) {
  16199. if (!this.plane)
  16200. return polygons.slice();
  16201. var front = [], back = [];
  16202. for (var i = 0; i < polygons.length; i++) {
  16203. this.plane.splitPolygon(polygons[i], front, back, front, back);
  16204. }
  16205. if (this.front) {
  16206. front = this.front.clipPolygons(front);
  16207. }
  16208. if (this.back) {
  16209. back = this.back.clipPolygons(back);
  16210. } else {
  16211. back = [];
  16212. }
  16213. return front.concat(back);
  16214. };
  16215. Node.prototype.clipTo = function (bsp) {
  16216. this.polygons = bsp.clipPolygons(this.polygons);
  16217. if (this.front)
  16218. this.front.clipTo(bsp);
  16219. if (this.back)
  16220. this.back.clipTo(bsp);
  16221. };
  16222. Node.prototype.allPolygons = function () {
  16223. var polygons = this.polygons.slice();
  16224. if (this.front)
  16225. polygons = polygons.concat(this.front.allPolygons());
  16226. if (this.back)
  16227. polygons = polygons.concat(this.back.allPolygons());
  16228. return polygons;
  16229. };
  16230. Node.prototype.build = function (polygons) {
  16231. if (!polygons.length)
  16232. return;
  16233. if (!this.plane)
  16234. this.plane = polygons[0].plane.clone();
  16235. var front = [], back = [];
  16236. for (var i = 0; i < polygons.length; i++) {
  16237. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  16238. }
  16239. if (front.length) {
  16240. if (!this.front)
  16241. this.front = new Node();
  16242. this.front.build(front);
  16243. }
  16244. if (back.length) {
  16245. if (!this.back)
  16246. this.back = new Node();
  16247. this.back.build(back);
  16248. }
  16249. };
  16250. return Node;
  16251. })();
  16252. var CSG = (function () {
  16253. function CSG() {
  16254. this.polygons = new Array();
  16255. }
  16256. CSG.FromMesh = function (mesh) {
  16257. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  16258. if (mesh instanceof BABYLON.Mesh) {
  16259. mesh.computeWorldMatrix(true);
  16260. var matrix = mesh.getWorldMatrix();
  16261. var meshPosition = mesh.position.clone();
  16262. var meshRotation = mesh.rotation.clone();
  16263. var meshScaling = mesh.scaling.clone();
  16264. } else {
  16265. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  16266. }
  16267. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16268. var subMeshes = mesh.subMeshes;
  16269. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  16270. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  16271. vertices = [];
  16272. for (var j = 0; j < 3; j++) {
  16273. normal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  16274. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  16275. position = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  16276. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, position);
  16277. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  16278. vertex = new Vertex(position, normal, uv);
  16279. vertices.push(vertex);
  16280. }
  16281. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  16282. if (polygon.plane)
  16283. polygons.push(polygon);
  16284. }
  16285. }
  16286. var csg = CSG.FromPolygons(polygons);
  16287. csg.matrix = matrix;
  16288. csg.position = meshPosition;
  16289. csg.rotation = meshRotation;
  16290. csg.scaling = meshScaling;
  16291. currentCSGMeshId++;
  16292. return csg;
  16293. };
  16294. CSG.FromPolygons = function (polygons) {
  16295. var csg = new BABYLON.CSG();
  16296. csg.polygons = polygons;
  16297. return csg;
  16298. };
  16299. CSG.prototype.clone = function () {
  16300. var csg = new BABYLON.CSG();
  16301. csg.polygons = this.polygons.map(function (p) {
  16302. return p.clone();
  16303. });
  16304. csg.copyTransformAttributes(this);
  16305. return csg;
  16306. };
  16307. CSG.prototype.toPolygons = function () {
  16308. return this.polygons;
  16309. };
  16310. CSG.prototype.union = function (csg) {
  16311. var a = new Node(this.clone().polygons);
  16312. var b = new Node(csg.clone().polygons);
  16313. a.clipTo(b);
  16314. b.clipTo(a);
  16315. b.invert();
  16316. b.clipTo(a);
  16317. b.invert();
  16318. a.build(b.allPolygons());
  16319. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  16320. };
  16321. CSG.prototype.unionInPlace = function (csg) {
  16322. var a = new Node(this.polygons);
  16323. var b = new Node(csg.polygons);
  16324. a.clipTo(b);
  16325. b.clipTo(a);
  16326. b.invert();
  16327. b.clipTo(a);
  16328. b.invert();
  16329. a.build(b.allPolygons());
  16330. this.polygons = a.allPolygons();
  16331. };
  16332. CSG.prototype.subtract = function (csg) {
  16333. var a = new Node(this.clone().polygons);
  16334. var b = new Node(csg.clone().polygons);
  16335. a.invert();
  16336. a.clipTo(b);
  16337. b.clipTo(a);
  16338. b.invert();
  16339. b.clipTo(a);
  16340. b.invert();
  16341. a.build(b.allPolygons());
  16342. a.invert();
  16343. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  16344. };
  16345. CSG.prototype.subtractInPlace = function (csg) {
  16346. var a = new Node(this.polygons);
  16347. var b = new Node(csg.polygons);
  16348. a.invert();
  16349. a.clipTo(b);
  16350. b.clipTo(a);
  16351. b.invert();
  16352. b.clipTo(a);
  16353. b.invert();
  16354. a.build(b.allPolygons());
  16355. a.invert();
  16356. this.polygons = a.allPolygons();
  16357. };
  16358. CSG.prototype.intersect = function (csg) {
  16359. var a = new Node(this.clone().polygons);
  16360. var b = new Node(csg.clone().polygons);
  16361. a.invert();
  16362. b.clipTo(a);
  16363. b.invert();
  16364. a.clipTo(b);
  16365. b.clipTo(a);
  16366. a.build(b.allPolygons());
  16367. a.invert();
  16368. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  16369. };
  16370. CSG.prototype.intersectInPlace = function (csg) {
  16371. var a = new Node(this.polygons);
  16372. var b = new Node(csg.polygons);
  16373. a.invert();
  16374. b.clipTo(a);
  16375. b.invert();
  16376. a.clipTo(b);
  16377. b.clipTo(a);
  16378. a.build(b.allPolygons());
  16379. a.invert();
  16380. this.polygons = a.allPolygons();
  16381. };
  16382. CSG.prototype.inverse = function () {
  16383. var csg = this.clone();
  16384. csg.inverseInPlace();
  16385. return csg;
  16386. };
  16387. CSG.prototype.inverseInPlace = function () {
  16388. this.polygons.map(function (p) {
  16389. p.flip();
  16390. });
  16391. };
  16392. CSG.prototype.copyTransformAttributes = function (csg) {
  16393. this.matrix = csg.matrix;
  16394. this.position = csg.position;
  16395. this.rotation = csg.rotation;
  16396. this.scaling = csg.scaling;
  16397. return this;
  16398. };
  16399. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  16400. var matrix = this.matrix.clone();
  16401. matrix.invert();
  16402. 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;
  16403. if (keepSubMeshes) {
  16404. polygons.sort(function (a, b) {
  16405. if (a.shared.meshId === b.shared.meshId) {
  16406. return a.shared.subMeshId - b.shared.subMeshId;
  16407. } else {
  16408. return a.shared.meshId - b.shared.meshId;
  16409. }
  16410. });
  16411. }
  16412. for (var i = 0, il = polygons.length; i < il; i++) {
  16413. polygon = polygons[i];
  16414. if (!subMesh_dict[polygon.shared.meshId]) {
  16415. subMesh_dict[polygon.shared.meshId] = {};
  16416. }
  16417. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  16418. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  16419. indexStart: +Infinity,
  16420. indexEnd: -Infinity,
  16421. materialIndex: polygon.shared.materialIndex
  16422. };
  16423. }
  16424. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  16425. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  16426. polygonIndices[0] = 0;
  16427. polygonIndices[1] = j - 1;
  16428. polygonIndices[2] = j;
  16429. for (var k = 0; k < 3; k++) {
  16430. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  16431. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  16432. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  16433. BABYLON.Vector3.TransformCoordinatesToRef(vertex, matrix, vertex);
  16434. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  16435. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z];
  16436. if (!(typeof vertex_idx !== 'undefined' && normals[vertex_idx * 3] === normal.x && normals[vertex_idx * 3 + 1] === normal.y && normals[vertex_idx * 3 + 2] === normal.z && uvs[vertex_idx * 2] === uv.x && uvs[vertex_idx * 2 + 1] === uv.y)) {
  16437. vertices.push(vertex.x, vertex.y, vertex.z);
  16438. uvs.push(uv.x, uv.y);
  16439. normals.push(normal.x, normal.y, normal.z);
  16440. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z] = (vertices.length / 3) - 1;
  16441. }
  16442. indices.push(vertex_idx);
  16443. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  16444. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  16445. currentIndex++;
  16446. }
  16447. }
  16448. }
  16449. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  16450. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  16451. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  16452. mesh.setIndices(indices);
  16453. if (keepSubMeshes) {
  16454. var materialIndexOffset = 0, materialMaxIndex;
  16455. mesh.subMeshes.length = 0;
  16456. for (var m in subMesh_dict) {
  16457. materialMaxIndex = -1;
  16458. for (var sm in subMesh_dict[m]) {
  16459. subMesh_obj = subMesh_dict[m][sm];
  16460. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  16461. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  16462. }
  16463. materialIndexOffset += ++materialMaxIndex;
  16464. }
  16465. }
  16466. return mesh;
  16467. };
  16468. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  16469. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  16470. mesh.material = material;
  16471. mesh.position.copyFrom(this.position);
  16472. mesh.rotation.copyFrom(this.rotation);
  16473. mesh.scaling.copyFrom(this.scaling);
  16474. mesh.computeWorldMatrix(true);
  16475. return mesh;
  16476. };
  16477. return CSG;
  16478. })();
  16479. BABYLON.CSG = CSG;
  16480. })(BABYLON || (BABYLON = {}));
  16481. var __extends = this.__extends || function (d, b) {
  16482. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16483. function __() { this.constructor = d; }
  16484. __.prototype = b.prototype;
  16485. d.prototype = new __();
  16486. };
  16487. var BABYLON;
  16488. (function (BABYLON) {
  16489. var OculusDistortionCorrectionPostProcess = (function (_super) {
  16490. __extends(OculusDistortionCorrectionPostProcess, _super);
  16491. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  16492. var _this = this;
  16493. _super.call(this, name, "oculusDistortionCorrection", [
  16494. 'LensCenter',
  16495. 'Scale',
  16496. 'ScaleIn',
  16497. 'HmdWarpParam'
  16498. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  16499. this._isRightEye = isRightEye;
  16500. this._distortionFactors = cameraSettings.DistortionK;
  16501. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  16502. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  16503. this.onSizeChanged = function () {
  16504. _this.aspectRatio = _this.width * .5 / _this.height;
  16505. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  16506. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  16507. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  16508. };
  16509. this.onApply = function (effect) {
  16510. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  16511. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  16512. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  16513. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  16514. };
  16515. }
  16516. return OculusDistortionCorrectionPostProcess;
  16517. })(BABYLON.PostProcess);
  16518. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  16519. })(BABYLON || (BABYLON = {}));
  16520. var BABYLON;
  16521. (function (BABYLON) {
  16522. (function (JoystickAxis) {
  16523. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  16524. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  16525. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  16526. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  16527. var JoystickAxis = BABYLON.JoystickAxis;
  16528. var VirtualJoystick = (function () {
  16529. function VirtualJoystick(leftJoystick) {
  16530. var _this = this;
  16531. if (leftJoystick) {
  16532. this._leftJoystick = true;
  16533. } else {
  16534. this._leftJoystick = false;
  16535. }
  16536. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  16537. VirtualJoystick._globalJoystickIndex++;
  16538. this._axisTargetedByLeftAndRight = 0 /* X */;
  16539. this._axisTargetedByUpAndDown = 1 /* Y */;
  16540. this.reverseLeftRight = false;
  16541. this.reverseUpDown = false;
  16542. this._touches = new BABYLON.VirtualJoystick.Collection();
  16543. this.deltaPosition = BABYLON.Vector3.Zero();
  16544. this._joystickSensibility = 25;
  16545. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  16546. this._rotationSpeed = 25;
  16547. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  16548. this._rotateOnAxisRelativeToMesh = false;
  16549. if (!VirtualJoystick.vjCanvas) {
  16550. window.addEventListener("resize", function () {
  16551. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  16552. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  16553. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  16554. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  16555. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  16556. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  16557. }, false);
  16558. VirtualJoystick.vjCanvas = document.createElement("canvas");
  16559. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  16560. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  16561. VirtualJoystick.vjCanvas.width = window.innerWidth;
  16562. VirtualJoystick.vjCanvas.height = window.innerHeight;
  16563. VirtualJoystick.vjCanvas.style.width = "100%";
  16564. VirtualJoystick.vjCanvas.style.height = "100%";
  16565. VirtualJoystick.vjCanvas.style.position = "absolute";
  16566. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  16567. VirtualJoystick.vjCanvas.style.top = "0px";
  16568. VirtualJoystick.vjCanvas.style.left = "0px";
  16569. VirtualJoystick.vjCanvas.style.zIndex = "5";
  16570. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  16571. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  16572. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  16573. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  16574. document.body.appendChild(VirtualJoystick.vjCanvas);
  16575. }
  16576. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  16577. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  16578. this.pressed = false;
  16579. this._joystickColor = "cyan";
  16580. this._joystickPointerID = -1;
  16581. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  16582. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  16583. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  16584. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  16585. _this._onPointerDown(evt);
  16586. }, false);
  16587. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  16588. _this._onPointerMove(evt);
  16589. }, false);
  16590. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  16591. _this._onPointerUp(evt);
  16592. }, false);
  16593. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  16594. _this._onPointerUp(evt);
  16595. }, false);
  16596. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  16597. evt.preventDefault();
  16598. }, false);
  16599. requestAnimationFrame(function () {
  16600. _this._drawVirtualJoystick();
  16601. });
  16602. }
  16603. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  16604. this._joystickSensibility = newJoystickSensibility;
  16605. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  16606. };
  16607. VirtualJoystick.prototype._onPointerDown = function (e) {
  16608. var positionOnScreenCondition;
  16609. e.preventDefault();
  16610. if (this._leftJoystick === true) {
  16611. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  16612. } else {
  16613. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  16614. }
  16615. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  16616. this._joystickPointerID = e.pointerId;
  16617. this._joystickPointerStartPos.x = e.clientX;
  16618. this._joystickPointerStartPos.y = e.clientY;
  16619. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  16620. this._deltaJoystickVector.x = 0;
  16621. this._deltaJoystickVector.y = 0;
  16622. this.pressed = true;
  16623. this._touches.add(e.pointerId.toString(), e);
  16624. } else {
  16625. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  16626. this._action();
  16627. this._touches.add(e.pointerId.toString(), e);
  16628. }
  16629. }
  16630. };
  16631. VirtualJoystick.prototype._onPointerMove = function (e) {
  16632. if (this._joystickPointerID == e.pointerId) {
  16633. this._joystickPointerPos.x = e.clientX;
  16634. this._joystickPointerPos.y = e.clientY;
  16635. this._deltaJoystickVector = this._joystickPointerPos.clone();
  16636. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  16637. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  16638. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  16639. switch (this._axisTargetedByLeftAndRight) {
  16640. case 0 /* X */:
  16641. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  16642. break;
  16643. case 1 /* Y */:
  16644. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  16645. break;
  16646. case 2 /* Z */:
  16647. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  16648. break;
  16649. }
  16650. var directionUpDown = this.reverseUpDown ? 1 : -1;
  16651. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  16652. switch (this._axisTargetedByUpAndDown) {
  16653. case 0 /* X */:
  16654. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  16655. break;
  16656. case 1 /* Y */:
  16657. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  16658. break;
  16659. case 2 /* Z */:
  16660. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  16661. break;
  16662. }
  16663. } else {
  16664. if (this._touches.item(e.pointerId.toString())) {
  16665. this._touches.item(e.pointerId.toString()).x = e.clientX;
  16666. this._touches.item(e.pointerId.toString()).y = e.clientY;
  16667. }
  16668. }
  16669. };
  16670. VirtualJoystick.prototype._onPointerUp = function (e) {
  16671. this._clearCanvas();
  16672. if (this._joystickPointerID == e.pointerId) {
  16673. this._joystickPointerID = -1;
  16674. this.pressed = false;
  16675. }
  16676. this._deltaJoystickVector.x = 0;
  16677. this._deltaJoystickVector.y = 0;
  16678. this._touches.remove(e.pointerId.toString());
  16679. };
  16680. /**
  16681. * Change the color of the virtual joystick
  16682. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  16683. */
  16684. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  16685. this._joystickColor = newColor;
  16686. };
  16687. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  16688. this._action = action;
  16689. };
  16690. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  16691. switch (axis) {
  16692. case 0 /* X */:
  16693. case 1 /* Y */:
  16694. case 2 /* Z */:
  16695. this._axisTargetedByLeftAndRight = axis;
  16696. break;
  16697. default:
  16698. this._axisTargetedByLeftAndRight = 0 /* X */;
  16699. break;
  16700. }
  16701. };
  16702. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  16703. switch (axis) {
  16704. case 0 /* X */:
  16705. case 1 /* Y */:
  16706. case 2 /* Z */:
  16707. this._axisTargetedByUpAndDown = axis;
  16708. break;
  16709. default:
  16710. this._axisTargetedByUpAndDown = 1 /* Y */;
  16711. break;
  16712. }
  16713. };
  16714. VirtualJoystick.prototype._clearCanvas = function () {
  16715. if (this._leftJoystick) {
  16716. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  16717. } else {
  16718. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  16719. }
  16720. };
  16721. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  16722. var _this = this;
  16723. if (this.pressed) {
  16724. this._clearCanvas();
  16725. this._touches.forEach(function (touch) {
  16726. if (touch.pointerId === _this._joystickPointerID) {
  16727. VirtualJoystick.vjCanvasContext.beginPath();
  16728. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16729. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  16730. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  16731. VirtualJoystick.vjCanvasContext.stroke();
  16732. VirtualJoystick.vjCanvasContext.beginPath();
  16733. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16734. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  16735. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  16736. VirtualJoystick.vjCanvasContext.stroke();
  16737. VirtualJoystick.vjCanvasContext.beginPath();
  16738. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16739. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  16740. VirtualJoystick.vjCanvasContext.stroke();
  16741. } else {
  16742. VirtualJoystick.vjCanvasContext.beginPath();
  16743. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  16744. VirtualJoystick.vjCanvasContext.beginPath();
  16745. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  16746. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  16747. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  16748. VirtualJoystick.vjCanvasContext.stroke();
  16749. }
  16750. ;
  16751. });
  16752. }
  16753. requestAnimationFrame(function () {
  16754. _this._drawVirtualJoystick();
  16755. });
  16756. };
  16757. VirtualJoystick.prototype.releaseCanvas = function () {
  16758. if (VirtualJoystick.vjCanvas) {
  16759. document.body.removeChild(VirtualJoystick.vjCanvas);
  16760. VirtualJoystick.vjCanvas = null;
  16761. }
  16762. };
  16763. VirtualJoystick._globalJoystickIndex = 0;
  16764. return VirtualJoystick;
  16765. })();
  16766. BABYLON.VirtualJoystick = VirtualJoystick;
  16767. })(BABYLON || (BABYLON = {}));
  16768. var BABYLON;
  16769. (function (BABYLON) {
  16770. (function (VirtualJoystick) {
  16771. var Collection = (function () {
  16772. function Collection() {
  16773. this._count = 0;
  16774. this._collection = new Array();
  16775. }
  16776. Collection.prototype.Count = function () {
  16777. return this._count;
  16778. };
  16779. Collection.prototype.add = function (key, item) {
  16780. if (this._collection[key] != undefined) {
  16781. return undefined;
  16782. }
  16783. this._collection[key] = item;
  16784. return ++this._count;
  16785. };
  16786. Collection.prototype.remove = function (key) {
  16787. if (this._collection[key] == undefined) {
  16788. return undefined;
  16789. }
  16790. delete this._collection[key];
  16791. return --this._count;
  16792. };
  16793. Collection.prototype.item = function (key) {
  16794. return this._collection[key];
  16795. };
  16796. Collection.prototype.forEach = function (block) {
  16797. var key;
  16798. for (key in this._collection) {
  16799. if (this._collection.hasOwnProperty(key)) {
  16800. block(this._collection[key]);
  16801. }
  16802. }
  16803. };
  16804. return Collection;
  16805. })();
  16806. VirtualJoystick.Collection = Collection;
  16807. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  16808. var VirtualJoystick = BABYLON.VirtualJoystick;
  16809. })(BABYLON || (BABYLON = {}));
  16810. var __extends = this.__extends || function (d, b) {
  16811. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16812. function __() { this.constructor = d; }
  16813. __.prototype = b.prototype;
  16814. d.prototype = new __();
  16815. };
  16816. var BABYLON;
  16817. (function (BABYLON) {
  16818. var OculusRiftDevKit2013_Metric = {
  16819. HResolution: 1280,
  16820. VResolution: 800,
  16821. HScreenSize: 0.149759993,
  16822. VScreenSize: 0.0935999975,
  16823. VScreenCenter: 0.0467999987,
  16824. EyeToScreenDistance: 0.0410000011,
  16825. LensSeparationDistance: 0.0635000020,
  16826. InterpupillaryDistance: 0.0640000030,
  16827. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  16828. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  16829. PostProcessScaleFactor: 1.714605507808412,
  16830. LensCenterOffset: 0.151976421
  16831. };
  16832. var _OculusInnerCamera = (function (_super) {
  16833. __extends(_OculusInnerCamera, _super);
  16834. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  16835. _super.call(this, name, position, scene);
  16836. this._workMatrix = new BABYLON.Matrix();
  16837. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  16838. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  16839. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  16840. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  16841. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  16842. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  16843. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  16844. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  16845. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  16846. }
  16847. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  16848. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  16849. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  16850. return this._projectionMatrix;
  16851. };
  16852. _OculusInnerCamera.prototype._getViewMatrix = function () {
  16853. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  16854. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  16855. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  16856. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  16857. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  16858. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  16859. return this._viewMatrix;
  16860. };
  16861. return _OculusInnerCamera;
  16862. })(BABYLON.FreeCamera);
  16863. var OculusCamera = (function (_super) {
  16864. __extends(OculusCamera, _super);
  16865. function OculusCamera(name, position, scene) {
  16866. _super.call(this, name, position, scene);
  16867. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  16868. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  16869. this.subCameras.push(this._leftCamera);
  16870. this.subCameras.push(this._rightCamera);
  16871. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  16872. }
  16873. OculusCamera.prototype._update = function () {
  16874. this._leftCamera.position.copyFrom(this.position);
  16875. this._rightCamera.position.copyFrom(this.position);
  16876. this._updateCamera(this._leftCamera);
  16877. this._updateCamera(this._rightCamera);
  16878. _super.prototype._update.call(this);
  16879. };
  16880. OculusCamera.prototype._updateCamera = function (camera) {
  16881. camera.minZ = this.minZ;
  16882. camera.maxZ = this.maxZ;
  16883. camera.rotation.x = this.rotation.x;
  16884. camera.rotation.y = this.rotation.y;
  16885. camera.rotation.z = this.rotation.z;
  16886. };
  16887. OculusCamera.prototype._onOrientationEvent = function (evt) {
  16888. var yaw = evt.alpha / 180 * Math.PI;
  16889. var pitch = evt.beta / 180 * Math.PI;
  16890. var roll = evt.gamma / 180 * Math.PI;
  16891. if (!this._offsetOrientation) {
  16892. this._offsetOrientation = {
  16893. yaw: yaw,
  16894. pitch: pitch,
  16895. roll: roll
  16896. };
  16897. return;
  16898. } else {
  16899. this.rotation.y += yaw - this._offsetOrientation.yaw;
  16900. this.rotation.x += pitch - this._offsetOrientation.pitch;
  16901. this.rotation.z += this._offsetOrientation.roll - roll;
  16902. this._offsetOrientation.yaw = yaw;
  16903. this._offsetOrientation.pitch = pitch;
  16904. this._offsetOrientation.roll = roll;
  16905. }
  16906. };
  16907. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  16908. _super.prototype.attachControl.call(this, element, noPreventDefault);
  16909. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  16910. };
  16911. OculusCamera.prototype.detachControl = function (element) {
  16912. _super.prototype.detachControl.call(this, element);
  16913. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  16914. };
  16915. return OculusCamera;
  16916. })(BABYLON.FreeCamera);
  16917. BABYLON.OculusCamera = OculusCamera;
  16918. })(BABYLON || (BABYLON = {}));
  16919. var __extends = this.__extends || function (d, b) {
  16920. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16921. function __() { this.constructor = d; }
  16922. __.prototype = b.prototype;
  16923. d.prototype = new __();
  16924. };
  16925. var BABYLON;
  16926. (function (BABYLON) {
  16927. var OculusRiftDevKit2013_Metric = {
  16928. HResolution: 1280,
  16929. VResolution: 800,
  16930. HScreenSize: 0.149759993,
  16931. VScreenSize: 0.0935999975,
  16932. VScreenCenter: 0.0467999987,
  16933. EyeToScreenDistance: 0.0410000011,
  16934. LensSeparationDistance: 0.0635000020,
  16935. InterpupillaryDistance: 0.0640000030,
  16936. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  16937. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  16938. PostProcessScaleFactor: 1.714605507808412,
  16939. LensCenterOffset: 0.151976421
  16940. };
  16941. var _OculusInnerGamepadCamera = (function (_super) {
  16942. __extends(_OculusInnerGamepadCamera, _super);
  16943. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  16944. _super.call(this, name, position, scene);
  16945. this._workMatrix = new BABYLON.Matrix();
  16946. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  16947. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  16948. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  16949. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  16950. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  16951. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  16952. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  16953. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  16954. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  16955. }
  16956. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  16957. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  16958. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  16959. return this._projectionMatrix;
  16960. };
  16961. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  16962. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  16963. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  16964. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  16965. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  16966. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  16967. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  16968. return this._viewMatrix;
  16969. };
  16970. return _OculusInnerGamepadCamera;
  16971. })(BABYLON.FreeCamera);
  16972. var OculusGamepadCamera = (function (_super) {
  16973. __extends(OculusGamepadCamera, _super);
  16974. function OculusGamepadCamera(name, position, scene) {
  16975. var _this = this;
  16976. _super.call(this, name, position, scene);
  16977. this.angularSensibility = 200;
  16978. this.moveSensibility = 75;
  16979. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  16980. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  16981. this.subCameras.push(this._leftCamera);
  16982. this.subCameras.push(this._rightCamera);
  16983. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  16984. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  16985. _this._onNewGameConnected(gamepad);
  16986. });
  16987. }
  16988. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  16989. if (gamepad.index === 0) {
  16990. this._gamepad = gamepad;
  16991. }
  16992. };
  16993. OculusGamepadCamera.prototype._update = function () {
  16994. this._leftCamera.position.copyFrom(this.position);
  16995. this._rightCamera.position.copyFrom(this.position);
  16996. this._updateCamera(this._leftCamera);
  16997. this._updateCamera(this._rightCamera);
  16998. _super.prototype._update.call(this);
  16999. };
  17000. OculusGamepadCamera.prototype._checkInputs = function () {
  17001. if (!this._gamepad) {
  17002. return;
  17003. }
  17004. var LSValues = this._gamepad.leftStick;
  17005. var normalizedLX = LSValues.x / this.moveSensibility;
  17006. var normalizedLY = LSValues.y / this.moveSensibility;
  17007. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  17008. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  17009. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  17010. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  17011. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  17012. };
  17013. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  17014. camera.minZ = this.minZ;
  17015. camera.maxZ = this.maxZ;
  17016. camera.rotation.x = this.rotation.x;
  17017. camera.rotation.y = this.rotation.y;
  17018. camera.rotation.z = this.rotation.z;
  17019. };
  17020. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  17021. var yaw = evt.alpha / 180 * Math.PI;
  17022. var pitch = evt.beta / 180 * Math.PI;
  17023. var roll = evt.gamma / 180 * Math.PI;
  17024. if (!this._offsetOrientation) {
  17025. this._offsetOrientation = {
  17026. yaw: yaw,
  17027. pitch: pitch,
  17028. roll: roll
  17029. };
  17030. return;
  17031. } else {
  17032. this.rotation.y += yaw - this._offsetOrientation.yaw;
  17033. this.rotation.x += pitch - this._offsetOrientation.pitch;
  17034. this.rotation.z += this._offsetOrientation.roll - roll;
  17035. this._offsetOrientation.yaw = yaw;
  17036. this._offsetOrientation.pitch = pitch;
  17037. this._offsetOrientation.roll = roll;
  17038. }
  17039. };
  17040. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  17041. _super.prototype.attachControl.call(this, element, noPreventDefault);
  17042. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  17043. };
  17044. OculusGamepadCamera.prototype.detachControl = function (element) {
  17045. _super.prototype.detachControl.call(this, element);
  17046. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  17047. };
  17048. OculusGamepadCamera.prototype.dispose = function () {
  17049. this._gamepads.dispose();
  17050. _super.prototype.dispose.call(this);
  17051. };
  17052. return OculusGamepadCamera;
  17053. })(BABYLON.FreeCamera);
  17054. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  17055. })(BABYLON || (BABYLON = {}));
  17056. var __extends = this.__extends || function (d, b) {
  17057. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17058. function __() { this.constructor = d; }
  17059. __.prototype = b.prototype;
  17060. d.prototype = new __();
  17061. };
  17062. var BABYLON;
  17063. (function (BABYLON) {
  17064. var VirtualJoysticksCamera = (function (_super) {
  17065. __extends(VirtualJoysticksCamera, _super);
  17066. function VirtualJoysticksCamera(name, position, scene) {
  17067. _super.call(this, name, position, scene);
  17068. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  17069. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  17070. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  17071. this._leftjoystick.setJoystickSensibility(0.15);
  17072. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  17073. this._rightjoystick.setAxisForUpDown(0 /* X */);
  17074. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  17075. this._rightjoystick.reverseUpDown = true;
  17076. this._rightjoystick.setJoystickSensibility(0.05);
  17077. this._rightjoystick.setJoystickColor("yellow");
  17078. }
  17079. VirtualJoysticksCamera.prototype._checkInputs = function () {
  17080. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  17081. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  17082. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  17083. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  17084. if (!this._leftjoystick.pressed) {
  17085. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  17086. }
  17087. if (!this._rightjoystick.pressed) {
  17088. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  17089. }
  17090. };
  17091. VirtualJoysticksCamera.prototype.dispose = function () {
  17092. this._leftjoystick.releaseCanvas();
  17093. _super.prototype.dispose.call(this);
  17094. };
  17095. return VirtualJoysticksCamera;
  17096. })(BABYLON.FreeCamera);
  17097. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  17098. })(BABYLON || (BABYLON = {}));
  17099. var __extends = this.__extends || function (d, b) {
  17100. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17101. function __() { this.constructor = d; }
  17102. __.prototype = b.prototype;
  17103. d.prototype = new __();
  17104. };
  17105. var BABYLON;
  17106. (function (BABYLON) {
  17107. var ShaderMaterial = (function (_super) {
  17108. __extends(ShaderMaterial, _super);
  17109. function ShaderMaterial(name, scene, shaderPath, options) {
  17110. _super.call(this, name, scene);
  17111. this._textures = new Array();
  17112. this._floats = new Array();
  17113. this._floatsArrays = {};
  17114. this._colors3 = new Array();
  17115. this._colors4 = new Array();
  17116. this._vectors2 = new Array();
  17117. this._vectors3 = new Array();
  17118. this._matrices = new Array();
  17119. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  17120. this._shaderPath = shaderPath;
  17121. options.needAlphaBlending = options.needAlphaBlending || false;
  17122. options.needAlphaTesting = options.needAlphaTesting || false;
  17123. options.attributes = options.attributes || ["position", "normal", "uv"];
  17124. options.uniforms = options.uniforms || ["worldViewProjection"];
  17125. options.samplers = options.samplers || [];
  17126. this._options = options;
  17127. }
  17128. ShaderMaterial.prototype.needAlphaBlending = function () {
  17129. return this._options.needAlphaBlending;
  17130. };
  17131. ShaderMaterial.prototype.needAlphaTesting = function () {
  17132. return this._options.needAlphaTesting;
  17133. };
  17134. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  17135. if (this._options.uniforms.indexOf(uniformName) === -1) {
  17136. this._options.uniforms.push(uniformName);
  17137. }
  17138. };
  17139. ShaderMaterial.prototype.setTexture = function (name, texture) {
  17140. if (this._options.samplers.indexOf(name) === -1) {
  17141. this._options.samplers.push(name);
  17142. }
  17143. this._textures[name] = texture;
  17144. return this;
  17145. };
  17146. ShaderMaterial.prototype.setFloat = function (name, value) {
  17147. this._checkUniform(name);
  17148. this._floats[name] = value;
  17149. return this;
  17150. };
  17151. ShaderMaterial.prototype.setFloats = function (name, value) {
  17152. this._checkUniform(name);
  17153. this._floatsArrays[name] = value;
  17154. return this;
  17155. };
  17156. ShaderMaterial.prototype.setColor3 = function (name, value) {
  17157. this._checkUniform(name);
  17158. this._colors3[name] = value;
  17159. return this;
  17160. };
  17161. ShaderMaterial.prototype.setColor4 = function (name, value) {
  17162. this._checkUniform(name);
  17163. this._colors4[name] = value;
  17164. return this;
  17165. };
  17166. ShaderMaterial.prototype.setVector2 = function (name, value) {
  17167. this._checkUniform(name);
  17168. this._vectors2[name] = value;
  17169. return this;
  17170. };
  17171. ShaderMaterial.prototype.setVector3 = function (name, value) {
  17172. this._checkUniform(name);
  17173. this._vectors3[name] = value;
  17174. return this;
  17175. };
  17176. ShaderMaterial.prototype.setMatrix = function (name, value) {
  17177. this._checkUniform(name);
  17178. this._matrices[name] = value;
  17179. return this;
  17180. };
  17181. ShaderMaterial.prototype.isReady = function () {
  17182. var engine = this.getScene().getEngine();
  17183. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  17184. if (!this._effect.isReady()) {
  17185. return false;
  17186. }
  17187. return true;
  17188. };
  17189. ShaderMaterial.prototype.bind = function (world) {
  17190. if (this._options.uniforms.indexOf("world") !== -1) {
  17191. this._effect.setMatrix("world", world);
  17192. }
  17193. if (this._options.uniforms.indexOf("view") !== -1) {
  17194. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  17195. }
  17196. if (this._options.uniforms.indexOf("worldView") !== -1) {
  17197. world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
  17198. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  17199. }
  17200. if (this._options.uniforms.indexOf("projection") !== -1) {
  17201. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  17202. }
  17203. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  17204. this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
  17205. }
  17206. for (var name in this._textures) {
  17207. this._effect.setTexture(name, this._textures[name]);
  17208. }
  17209. for (name in this._floats) {
  17210. this._effect.setFloat(name, this._floats[name]);
  17211. }
  17212. for (name in this._floatsArrays) {
  17213. this._effect.setArray(name, this._floatsArrays[name]);
  17214. }
  17215. for (name in this._colors3) {
  17216. this._effect.setColor3(name, this._colors3[name]);
  17217. }
  17218. for (name in this._colors4) {
  17219. var color = this._colors4[name];
  17220. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17221. }
  17222. for (name in this._vectors2) {
  17223. this._effect.setVector2(name, this._vectors2[name]);
  17224. }
  17225. for (name in this._vectors3) {
  17226. this._effect.setVector3(name, this._vectors3[name]);
  17227. }
  17228. for (name in this._matrices) {
  17229. this._effect.setMatrix(name, this._matrices[name]);
  17230. }
  17231. };
  17232. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  17233. for (var name in this._textures) {
  17234. this._textures[name].dispose();
  17235. }
  17236. this._textures = [];
  17237. _super.prototype.dispose.call(this, forceDisposeEffect);
  17238. };
  17239. return ShaderMaterial;
  17240. })(BABYLON.Material);
  17241. BABYLON.ShaderMaterial = ShaderMaterial;
  17242. })(BABYLON || (BABYLON = {}));
  17243. var BABYLON;
  17244. (function (BABYLON) {
  17245. var VertexData = (function () {
  17246. function VertexData() {
  17247. }
  17248. VertexData.prototype.set = function (data, kind) {
  17249. switch (kind) {
  17250. case BABYLON.VertexBuffer.PositionKind:
  17251. this.positions = data;
  17252. break;
  17253. case BABYLON.VertexBuffer.NormalKind:
  17254. this.normals = data;
  17255. break;
  17256. case BABYLON.VertexBuffer.UVKind:
  17257. this.uvs = data;
  17258. break;
  17259. case BABYLON.VertexBuffer.UV2Kind:
  17260. this.uv2s = data;
  17261. break;
  17262. case BABYLON.VertexBuffer.ColorKind:
  17263. this.colors = data;
  17264. break;
  17265. case BABYLON.VertexBuffer.MatricesIndicesKind:
  17266. this.matricesIndices = data;
  17267. break;
  17268. case BABYLON.VertexBuffer.MatricesWeightsKind:
  17269. this.matricesWeights = data;
  17270. break;
  17271. }
  17272. };
  17273. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  17274. this._applyTo(mesh, updatable);
  17275. };
  17276. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  17277. this._applyTo(geometry, updatable);
  17278. };
  17279. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  17280. this._update(mesh);
  17281. };
  17282. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  17283. this._update(geometry);
  17284. };
  17285. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  17286. if (this.positions) {
  17287. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  17288. }
  17289. if (this.normals) {
  17290. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  17291. }
  17292. if (this.uvs) {
  17293. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  17294. }
  17295. if (this.uv2s) {
  17296. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  17297. }
  17298. if (this.colors) {
  17299. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  17300. }
  17301. if (this.matricesIndices) {
  17302. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  17303. }
  17304. if (this.matricesWeights) {
  17305. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  17306. }
  17307. if (this.indices) {
  17308. meshOrGeometry.setIndices(this.indices);
  17309. }
  17310. };
  17311. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  17312. if (this.positions) {
  17313. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  17314. }
  17315. if (this.normals) {
  17316. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  17317. }
  17318. if (this.uvs) {
  17319. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  17320. }
  17321. if (this.uv2s) {
  17322. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  17323. }
  17324. if (this.colors) {
  17325. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  17326. }
  17327. if (this.matricesIndices) {
  17328. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  17329. }
  17330. if (this.matricesWeights) {
  17331. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  17332. }
  17333. if (this.indices) {
  17334. meshOrGeometry.setIndices(this.indices);
  17335. }
  17336. };
  17337. VertexData.prototype.transform = function (matrix) {
  17338. var transformed = BABYLON.Vector3.Zero();
  17339. if (this.positions) {
  17340. var position = BABYLON.Vector3.Zero();
  17341. for (var index = 0; index < this.positions.length; index += 3) {
  17342. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  17343. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  17344. this.positions[index] = transformed.x;
  17345. this.positions[index + 1] = transformed.y;
  17346. this.positions[index + 2] = transformed.z;
  17347. }
  17348. }
  17349. if (this.normals) {
  17350. var normal = BABYLON.Vector3.Zero();
  17351. for (index = 0; index < this.normals.length; index += 3) {
  17352. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  17353. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  17354. this.normals[index] = transformed.x;
  17355. this.normals[index + 1] = transformed.y;
  17356. this.normals[index + 2] = transformed.z;
  17357. }
  17358. }
  17359. };
  17360. VertexData.prototype.merge = function (other) {
  17361. if (other.indices) {
  17362. if (!this.indices) {
  17363. this.indices = [];
  17364. }
  17365. var offset = this.positions ? this.positions.length / 3 : 0;
  17366. for (var index = 0; index < other.indices.length; index++) {
  17367. this.indices.push(other.indices[index] + offset);
  17368. }
  17369. }
  17370. if (other.positions) {
  17371. if (!this.positions) {
  17372. this.positions = [];
  17373. }
  17374. for (index = 0; index < other.positions.length; index++) {
  17375. this.positions.push(other.positions[index]);
  17376. }
  17377. }
  17378. if (other.normals) {
  17379. if (!this.normals) {
  17380. this.normals = [];
  17381. }
  17382. for (index = 0; index < other.normals.length; index++) {
  17383. this.normals.push(other.normals[index]);
  17384. }
  17385. }
  17386. if (other.uvs) {
  17387. if (!this.uvs) {
  17388. this.uvs = [];
  17389. }
  17390. for (index = 0; index < other.uvs.length; index++) {
  17391. this.uvs.push(other.uvs[index]);
  17392. }
  17393. }
  17394. if (other.uv2s) {
  17395. if (!this.uv2s) {
  17396. this.uv2s = [];
  17397. }
  17398. for (index = 0; index < other.uv2s.length; index++) {
  17399. this.uv2s.push(other.uv2s[index]);
  17400. }
  17401. }
  17402. if (other.matricesIndices) {
  17403. if (!this.matricesIndices) {
  17404. this.matricesIndices = [];
  17405. }
  17406. for (index = 0; index < other.matricesIndices.length; index++) {
  17407. this.matricesIndices.push(other.matricesIndices[index]);
  17408. }
  17409. }
  17410. if (other.matricesWeights) {
  17411. if (!this.matricesWeights) {
  17412. this.matricesWeights = [];
  17413. }
  17414. for (index = 0; index < other.matricesWeights.length; index++) {
  17415. this.matricesWeights.push(other.matricesWeights[index]);
  17416. }
  17417. }
  17418. if (other.colors) {
  17419. if (!this.colors) {
  17420. this.colors = [];
  17421. }
  17422. for (index = 0; index < other.colors.length; index++) {
  17423. this.colors.push(other.colors[index]);
  17424. }
  17425. }
  17426. };
  17427. VertexData.ExtractFromMesh = function (mesh) {
  17428. return VertexData._ExtractFrom(mesh);
  17429. };
  17430. VertexData.ExtractFromGeometry = function (geometry) {
  17431. return VertexData._ExtractFrom(geometry);
  17432. };
  17433. VertexData._ExtractFrom = function (meshOrGeometry) {
  17434. var result = new BABYLON.VertexData();
  17435. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17436. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17437. }
  17438. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17439. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17440. }
  17441. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17442. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17443. }
  17444. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17445. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  17446. }
  17447. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17448. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  17449. }
  17450. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17451. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17452. }
  17453. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17454. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17455. }
  17456. result.indices = meshOrGeometry.getIndices();
  17457. return result;
  17458. };
  17459. VertexData.CreateBox = function (size) {
  17460. var normalsSource = [
  17461. new BABYLON.Vector3(0, 0, 1),
  17462. new BABYLON.Vector3(0, 0, -1),
  17463. new BABYLON.Vector3(1, 0, 0),
  17464. new BABYLON.Vector3(-1, 0, 0),
  17465. new BABYLON.Vector3(0, 1, 0),
  17466. new BABYLON.Vector3(0, -1, 0)
  17467. ];
  17468. var indices = [];
  17469. var positions = [];
  17470. var normals = [];
  17471. var uvs = [];
  17472. size = size || 1;
  17473. for (var index = 0; index < normalsSource.length; index++) {
  17474. var normal = normalsSource[index];
  17475. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  17476. var side2 = BABYLON.Vector3.Cross(normal, side1);
  17477. var verticesLength = positions.length / 3;
  17478. indices.push(verticesLength);
  17479. indices.push(verticesLength + 1);
  17480. indices.push(verticesLength + 2);
  17481. indices.push(verticesLength);
  17482. indices.push(verticesLength + 2);
  17483. indices.push(verticesLength + 3);
  17484. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  17485. positions.push(vertex.x, vertex.y, vertex.z);
  17486. normals.push(normal.x, normal.y, normal.z);
  17487. uvs.push(1.0, 1.0);
  17488. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  17489. positions.push(vertex.x, vertex.y, vertex.z);
  17490. normals.push(normal.x, normal.y, normal.z);
  17491. uvs.push(0.0, 1.0);
  17492. vertex = normal.add(side1).add(side2).scale(size / 2);
  17493. positions.push(vertex.x, vertex.y, vertex.z);
  17494. normals.push(normal.x, normal.y, normal.z);
  17495. uvs.push(0.0, 0.0);
  17496. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  17497. positions.push(vertex.x, vertex.y, vertex.z);
  17498. normals.push(normal.x, normal.y, normal.z);
  17499. uvs.push(1.0, 0.0);
  17500. }
  17501. var vertexData = new BABYLON.VertexData();
  17502. vertexData.indices = indices;
  17503. vertexData.positions = positions;
  17504. vertexData.normals = normals;
  17505. vertexData.uvs = uvs;
  17506. return vertexData;
  17507. };
  17508. VertexData.CreateSphere = function (segments, diameter) {
  17509. segments = segments || 32;
  17510. diameter = diameter || 1;
  17511. var radius = diameter / 2;
  17512. var totalZRotationSteps = 2 + segments;
  17513. var totalYRotationSteps = 2 * totalZRotationSteps;
  17514. var indices = [];
  17515. var positions = [];
  17516. var normals = [];
  17517. var uvs = [];
  17518. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  17519. var normalizedZ = zRotationStep / totalZRotationSteps;
  17520. var angleZ = (normalizedZ * Math.PI);
  17521. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  17522. var normalizedY = yRotationStep / totalYRotationSteps;
  17523. var angleY = normalizedY * Math.PI * 2;
  17524. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  17525. var rotationY = BABYLON.Matrix.RotationY(angleY);
  17526. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  17527. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  17528. var vertex = complete.scale(radius);
  17529. var normal = BABYLON.Vector3.Normalize(vertex);
  17530. positions.push(vertex.x, vertex.y, vertex.z);
  17531. normals.push(normal.x, normal.y, normal.z);
  17532. uvs.push(normalizedZ, normalizedY);
  17533. }
  17534. if (zRotationStep > 0) {
  17535. var verticesCount = positions.length / 3;
  17536. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  17537. indices.push((firstIndex));
  17538. indices.push((firstIndex + 1));
  17539. indices.push(firstIndex + totalYRotationSteps + 1);
  17540. indices.push((firstIndex + totalYRotationSteps + 1));
  17541. indices.push((firstIndex + 1));
  17542. indices.push((firstIndex + totalYRotationSteps + 2));
  17543. }
  17544. }
  17545. }
  17546. var vertexData = new BABYLON.VertexData();
  17547. vertexData.indices = indices;
  17548. vertexData.positions = positions;
  17549. vertexData.normals = normals;
  17550. vertexData.uvs = uvs;
  17551. return vertexData;
  17552. };
  17553. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  17554. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  17555. var radiusTop = diameterTop / 2;
  17556. var radiusBottom = diameterBottom / 2;
  17557. var indices = [];
  17558. var positions = [];
  17559. var normals = [];
  17560. var uvs = [];
  17561. height = height || 1;
  17562. diameterTop = diameterTop || 0.5;
  17563. diameterBottom = diameterBottom || 1;
  17564. tessellation = tessellation || 16;
  17565. subdivisions = subdivisions || 1;
  17566. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  17567. var getCircleVector = function (i) {
  17568. var angle = (i * 2.0 * Math.PI / tessellation);
  17569. var dx = Math.cos(angle);
  17570. var dz = Math.sin(angle);
  17571. return new BABYLON.Vector3(dx, 0, dz);
  17572. };
  17573. var createCylinderCap = function (isTop) {
  17574. var radius = isTop ? radiusTop : radiusBottom;
  17575. if (radius == 0) {
  17576. return;
  17577. }
  17578. var vbase = positions.length / 3;
  17579. var offset = new BABYLON.Vector3(0, height / 2, 0);
  17580. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  17581. if (!isTop) {
  17582. offset.scaleInPlace(-1);
  17583. textureScale.x = -textureScale.x;
  17584. }
  17585. for (i = 0; i < tessellation; i++) {
  17586. var circleVector = getCircleVector(i);
  17587. var position = circleVector.scale(radius).add(offset);
  17588. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  17589. positions.push(position.x, position.y, position.z);
  17590. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17591. }
  17592. for (var i = 0; i < tessellation - 2; i++) {
  17593. if (!isTop) {
  17594. indices.push(vbase);
  17595. indices.push(vbase + (i + 2) % tessellation);
  17596. indices.push(vbase + (i + 1) % tessellation);
  17597. } else {
  17598. indices.push(vbase);
  17599. indices.push(vbase + (i + 1) % tessellation);
  17600. indices.push(vbase + (i + 2) % tessellation);
  17601. }
  17602. }
  17603. };
  17604. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  17605. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  17606. var stride = tessellation + 1;
  17607. for (var i = 0; i <= tessellation; i++) {
  17608. var circleVector = getCircleVector(i);
  17609. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  17610. var position, radius = radiusBottom;
  17611. for (var s = 0; s <= subdivisions; s++) {
  17612. position = circleVector.scale(radius);
  17613. position.addInPlace(base.add(offset.scale(s)));
  17614. textureCoordinate.y += 1 / subdivisions;
  17615. radius += (radiusTop - radiusBottom) / subdivisions;
  17616. positions.push(position.x, position.y, position.z);
  17617. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17618. }
  17619. }
  17620. subdivisions += 1;
  17621. for (var s = 0; s < subdivisions - 1; s++) {
  17622. for (var i = 0; i <= tessellation; i++) {
  17623. indices.push(i * subdivisions + s);
  17624. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  17625. indices.push(i * subdivisions + (s + 1));
  17626. indices.push(i * subdivisions + (s + 1));
  17627. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  17628. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  17629. }
  17630. }
  17631. createCylinderCap(true);
  17632. createCylinderCap(false);
  17633. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17634. var vertexData = new BABYLON.VertexData();
  17635. vertexData.indices = indices;
  17636. vertexData.positions = positions;
  17637. vertexData.normals = normals;
  17638. vertexData.uvs = uvs;
  17639. return vertexData;
  17640. };
  17641. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  17642. var indices = [];
  17643. var positions = [];
  17644. var normals = [];
  17645. var uvs = [];
  17646. diameter = diameter || 1;
  17647. thickness = thickness || 0.5;
  17648. tessellation = tessellation || 16;
  17649. var stride = tessellation + 1;
  17650. for (var i = 0; i <= tessellation; i++) {
  17651. var u = i / tessellation;
  17652. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  17653. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  17654. for (var j = 0; j <= tessellation; j++) {
  17655. var v = 1 - j / tessellation;
  17656. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  17657. var dx = Math.cos(innerAngle);
  17658. var dy = Math.sin(innerAngle);
  17659. var normal = new BABYLON.Vector3(dx, dy, 0);
  17660. var position = normal.scale(thickness / 2);
  17661. var textureCoordinate = new BABYLON.Vector2(u, v);
  17662. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  17663. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  17664. positions.push(position.x, position.y, position.z);
  17665. normals.push(normal.x, normal.y, normal.z);
  17666. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17667. var nextI = (i + 1) % stride;
  17668. var nextJ = (j + 1) % stride;
  17669. indices.push(i * stride + j);
  17670. indices.push(i * stride + nextJ);
  17671. indices.push(nextI * stride + j);
  17672. indices.push(i * stride + nextJ);
  17673. indices.push(nextI * stride + nextJ);
  17674. indices.push(nextI * stride + j);
  17675. }
  17676. }
  17677. var vertexData = new BABYLON.VertexData();
  17678. vertexData.indices = indices;
  17679. vertexData.positions = positions;
  17680. vertexData.normals = normals;
  17681. vertexData.uvs = uvs;
  17682. return vertexData;
  17683. };
  17684. VertexData.CreateLines = function (points) {
  17685. var indices = [];
  17686. var positions = [];
  17687. for (var index = 0; index < points.length; index++) {
  17688. positions.push(points[index].x, points[index].y, points[index].z);
  17689. if (index > 0) {
  17690. indices.push(index - 1);
  17691. indices.push(index);
  17692. }
  17693. }
  17694. var vertexData = new BABYLON.VertexData();
  17695. vertexData.indices = indices;
  17696. vertexData.positions = positions;
  17697. return vertexData;
  17698. };
  17699. VertexData.CreateGround = function (width, height, subdivisions) {
  17700. var indices = [];
  17701. var positions = [];
  17702. var normals = [];
  17703. var uvs = [];
  17704. var row, col;
  17705. width = width || 1;
  17706. height = height || 1;
  17707. subdivisions = subdivisions || 1;
  17708. for (row = 0; row <= subdivisions; row++) {
  17709. for (col = 0; col <= subdivisions; col++) {
  17710. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  17711. var normal = new BABYLON.Vector3(0, 1.0, 0);
  17712. positions.push(position.x, position.y, position.z);
  17713. normals.push(normal.x, normal.y, normal.z);
  17714. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  17715. }
  17716. }
  17717. for (row = 0; row < subdivisions; row++) {
  17718. for (col = 0; col < subdivisions; col++) {
  17719. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17720. indices.push(col + 1 + row * (subdivisions + 1));
  17721. indices.push(col + row * (subdivisions + 1));
  17722. indices.push(col + (row + 1) * (subdivisions + 1));
  17723. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17724. indices.push(col + row * (subdivisions + 1));
  17725. }
  17726. }
  17727. var vertexData = new BABYLON.VertexData();
  17728. vertexData.indices = indices;
  17729. vertexData.positions = positions;
  17730. vertexData.normals = normals;
  17731. vertexData.uvs = uvs;
  17732. return vertexData;
  17733. };
  17734. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  17735. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  17736. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  17737. var indices = [];
  17738. var positions = [];
  17739. var normals = [];
  17740. var uvs = [];
  17741. var row, col, tileRow, tileCol;
  17742. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  17743. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  17744. precision.w = (precision.w < 1) ? 1 : precision.w;
  17745. precision.h = (precision.h < 1) ? 1 : precision.h;
  17746. var tileSize = {
  17747. 'w': (xmax - xmin) / subdivisions.w,
  17748. 'h': (zmax - zmin) / subdivisions.h
  17749. };
  17750. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  17751. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  17752. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  17753. }
  17754. }
  17755. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  17756. var base = positions.length / 3;
  17757. var rowLength = precision.w + 1;
  17758. for (row = 0; row < precision.h; row++) {
  17759. for (col = 0; col < precision.w; col++) {
  17760. var square = [
  17761. base + col + row * rowLength,
  17762. base + (col + 1) + row * rowLength,
  17763. base + (col + 1) + (row + 1) * rowLength,
  17764. base + col + (row + 1) * rowLength
  17765. ];
  17766. indices.push(square[1]);
  17767. indices.push(square[2]);
  17768. indices.push(square[3]);
  17769. indices.push(square[0]);
  17770. indices.push(square[1]);
  17771. indices.push(square[3]);
  17772. }
  17773. }
  17774. var position = BABYLON.Vector3.Zero();
  17775. var normal = new BABYLON.Vector3(0, 1.0, 0);
  17776. for (row = 0; row <= precision.h; row++) {
  17777. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  17778. for (col = 0; col <= precision.w; col++) {
  17779. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  17780. position.y = 0;
  17781. positions.push(position.x, position.y, position.z);
  17782. normals.push(normal.x, normal.y, normal.z);
  17783. uvs.push(col / precision.w, row / precision.h);
  17784. }
  17785. }
  17786. }
  17787. var vertexData = new BABYLON.VertexData();
  17788. vertexData.indices = indices;
  17789. vertexData.positions = positions;
  17790. vertexData.normals = normals;
  17791. vertexData.uvs = uvs;
  17792. return vertexData;
  17793. };
  17794. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  17795. var indices = [];
  17796. var positions = [];
  17797. var normals = [];
  17798. var uvs = [];
  17799. var row, col;
  17800. for (row = 0; row <= subdivisions; row++) {
  17801. for (col = 0; col <= subdivisions; col++) {
  17802. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  17803. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  17804. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  17805. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  17806. var r = buffer[pos] / 255.0;
  17807. var g = buffer[pos + 1] / 255.0;
  17808. var b = buffer[pos + 2] / 255.0;
  17809. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  17810. position.y = minHeight + (maxHeight - minHeight) * gradient;
  17811. positions.push(position.x, position.y, position.z);
  17812. normals.push(0, 0, 0);
  17813. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  17814. }
  17815. }
  17816. for (row = 0; row < subdivisions; row++) {
  17817. for (col = 0; col < subdivisions; col++) {
  17818. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17819. indices.push(col + 1 + row * (subdivisions + 1));
  17820. indices.push(col + row * (subdivisions + 1));
  17821. indices.push(col + (row + 1) * (subdivisions + 1));
  17822. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17823. indices.push(col + row * (subdivisions + 1));
  17824. }
  17825. }
  17826. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17827. var vertexData = new BABYLON.VertexData();
  17828. vertexData.indices = indices;
  17829. vertexData.positions = positions;
  17830. vertexData.normals = normals;
  17831. vertexData.uvs = uvs;
  17832. return vertexData;
  17833. };
  17834. VertexData.CreatePlane = function (size) {
  17835. var indices = [];
  17836. var positions = [];
  17837. var normals = [];
  17838. var uvs = [];
  17839. size = size || 1;
  17840. var halfSize = size / 2.0;
  17841. positions.push(-halfSize, -halfSize, 0);
  17842. normals.push(0, 0, -1.0);
  17843. uvs.push(0.0, 0.0);
  17844. positions.push(halfSize, -halfSize, 0);
  17845. normals.push(0, 0, -1.0);
  17846. uvs.push(1.0, 0.0);
  17847. positions.push(halfSize, halfSize, 0);
  17848. normals.push(0, 0, -1.0);
  17849. uvs.push(1.0, 1.0);
  17850. positions.push(-halfSize, halfSize, 0);
  17851. normals.push(0, 0, -1.0);
  17852. uvs.push(0.0, 1.0);
  17853. indices.push(0);
  17854. indices.push(1);
  17855. indices.push(2);
  17856. indices.push(0);
  17857. indices.push(2);
  17858. indices.push(3);
  17859. var vertexData = new BABYLON.VertexData();
  17860. vertexData.indices = indices;
  17861. vertexData.positions = positions;
  17862. vertexData.normals = normals;
  17863. vertexData.uvs = uvs;
  17864. return vertexData;
  17865. };
  17866. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  17867. var indices = [];
  17868. var positions = [];
  17869. var normals = [];
  17870. var uvs = [];
  17871. radius = radius || 2;
  17872. tube = tube || 0.5;
  17873. radialSegments = radialSegments || 32;
  17874. tubularSegments = tubularSegments || 32;
  17875. p = p || 2;
  17876. q = q || 3;
  17877. var getPos = function (angle) {
  17878. var cu = Math.cos(angle);
  17879. var su = Math.sin(angle);
  17880. var quOverP = q / p * angle;
  17881. var cs = Math.cos(quOverP);
  17882. var tx = radius * (2 + cs) * 0.5 * cu;
  17883. var ty = radius * (2 + cs) * su * 0.5;
  17884. var tz = radius * Math.sin(quOverP) * 0.5;
  17885. return new BABYLON.Vector3(tx, ty, tz);
  17886. };
  17887. for (var i = 0; i <= radialSegments; i++) {
  17888. var modI = i % radialSegments;
  17889. var u = modI / radialSegments * 2 * p * Math.PI;
  17890. var p1 = getPos(u);
  17891. var p2 = getPos(u + 0.01);
  17892. var tang = p2.subtract(p1);
  17893. var n = p2.add(p1);
  17894. var bitan = BABYLON.Vector3.Cross(tang, n);
  17895. n = BABYLON.Vector3.Cross(bitan, tang);
  17896. bitan.normalize();
  17897. n.normalize();
  17898. for (var j = 0; j < tubularSegments; j++) {
  17899. var modJ = j % tubularSegments;
  17900. var v = modJ / tubularSegments * 2 * Math.PI;
  17901. var cx = -tube * Math.cos(v);
  17902. var cy = tube * Math.sin(v);
  17903. positions.push(p1.x + cx * n.x + cy * bitan.x);
  17904. positions.push(p1.y + cx * n.y + cy * bitan.y);
  17905. positions.push(p1.z + cx * n.z + cy * bitan.z);
  17906. uvs.push(i / radialSegments);
  17907. uvs.push(j / tubularSegments);
  17908. }
  17909. }
  17910. for (i = 0; i < radialSegments; i++) {
  17911. for (j = 0; j < tubularSegments; j++) {
  17912. var jNext = (j + 1) % tubularSegments;
  17913. var a = i * tubularSegments + j;
  17914. var b = (i + 1) * tubularSegments + j;
  17915. var c = (i + 1) * tubularSegments + jNext;
  17916. var d = i * tubularSegments + jNext;
  17917. indices.push(d);
  17918. indices.push(b);
  17919. indices.push(a);
  17920. indices.push(d);
  17921. indices.push(c);
  17922. indices.push(b);
  17923. }
  17924. }
  17925. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17926. var vertexData = new BABYLON.VertexData();
  17927. vertexData.indices = indices;
  17928. vertexData.positions = positions;
  17929. vertexData.normals = normals;
  17930. vertexData.uvs = uvs;
  17931. return vertexData;
  17932. };
  17933. VertexData.ComputeNormals = function (positions, indices, normals) {
  17934. var positionVectors = [];
  17935. var facesOfVertices = [];
  17936. var index;
  17937. for (index = 0; index < positions.length; index += 3) {
  17938. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  17939. positionVectors.push(vector3);
  17940. facesOfVertices.push([]);
  17941. }
  17942. var facesNormals = [];
  17943. for (index = 0; index < indices.length / 3; index++) {
  17944. var i1 = indices[index * 3];
  17945. var i2 = indices[index * 3 + 1];
  17946. var i3 = indices[index * 3 + 2];
  17947. var p1 = positionVectors[i1];
  17948. var p2 = positionVectors[i2];
  17949. var p3 = positionVectors[i3];
  17950. var p1p2 = p1.subtract(p2);
  17951. var p3p2 = p3.subtract(p2);
  17952. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  17953. facesOfVertices[i1].push(index);
  17954. facesOfVertices[i2].push(index);
  17955. facesOfVertices[i3].push(index);
  17956. }
  17957. for (index = 0; index < positionVectors.length; index++) {
  17958. var faces = facesOfVertices[index];
  17959. var normal = BABYLON.Vector3.Zero();
  17960. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  17961. normal.addInPlace(facesNormals[faces[faceIndex]]);
  17962. }
  17963. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  17964. normals[index * 3] = normal.x;
  17965. normals[index * 3 + 1] = normal.y;
  17966. normals[index * 3 + 2] = normal.z;
  17967. }
  17968. };
  17969. return VertexData;
  17970. })();
  17971. BABYLON.VertexData = VertexData;
  17972. })(BABYLON || (BABYLON = {}));
  17973. var __extends = this.__extends || function (d, b) {
  17974. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17975. function __() { this.constructor = d; }
  17976. __.prototype = b.prototype;
  17977. d.prototype = new __();
  17978. };
  17979. var BABYLON;
  17980. (function (BABYLON) {
  17981. var buildCamera = function (that, name) {
  17982. that._leftCamera.isIntermediate = true;
  17983. that.subCameras.push(that._leftCamera);
  17984. that.subCameras.push(that._rightCamera);
  17985. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  17986. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  17987. that._anaglyphPostProcess.onApply = function (effect) {
  17988. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  17989. };
  17990. that._update();
  17991. };
  17992. var AnaglyphArcRotateCamera = (function (_super) {
  17993. __extends(AnaglyphArcRotateCamera, _super);
  17994. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  17995. _super.call(this, name, alpha, beta, radius, target, scene);
  17996. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  17997. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  17998. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  17999. buildCamera(this, name);
  18000. }
  18001. AnaglyphArcRotateCamera.prototype._update = function () {
  18002. this._updateCamera(this._leftCamera);
  18003. this._updateCamera(this._rightCamera);
  18004. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  18005. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  18006. _super.prototype._update.call(this);
  18007. };
  18008. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  18009. camera.beta = this.beta;
  18010. camera.radius = this.radius;
  18011. camera.minZ = this.minZ;
  18012. camera.maxZ = this.maxZ;
  18013. camera.fov = this.fov;
  18014. camera.target = this.target;
  18015. };
  18016. return AnaglyphArcRotateCamera;
  18017. })(BABYLON.ArcRotateCamera);
  18018. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  18019. var AnaglyphFreeCamera = (function (_super) {
  18020. __extends(AnaglyphFreeCamera, _super);
  18021. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  18022. _super.call(this, name, position, scene);
  18023. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  18024. this._transformMatrix = new BABYLON.Matrix();
  18025. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  18026. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  18027. buildCamera(this, name);
  18028. }
  18029. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  18030. var target = this.getTarget();
  18031. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  18032. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  18033. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  18034. };
  18035. AnaglyphFreeCamera.prototype._update = function () {
  18036. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  18037. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  18038. this._updateCamera(this._leftCamera);
  18039. this._updateCamera(this._rightCamera);
  18040. _super.prototype._update.call(this);
  18041. };
  18042. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  18043. camera.minZ = this.minZ;
  18044. camera.maxZ = this.maxZ;
  18045. camera.fov = this.fov;
  18046. camera.viewport = this.viewport;
  18047. camera.setTarget(this.getTarget());
  18048. };
  18049. return AnaglyphFreeCamera;
  18050. })(BABYLON.FreeCamera);
  18051. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  18052. })(BABYLON || (BABYLON = {}));
  18053. var __extends = this.__extends || function (d, b) {
  18054. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18055. function __() { this.constructor = d; }
  18056. __.prototype = b.prototype;
  18057. d.prototype = new __();
  18058. };
  18059. var BABYLON;
  18060. (function (BABYLON) {
  18061. var AnaglyphPostProcess = (function (_super) {
  18062. __extends(AnaglyphPostProcess, _super);
  18063. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18064. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  18065. }
  18066. return AnaglyphPostProcess;
  18067. })(BABYLON.PostProcess);
  18068. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  18069. })(BABYLON || (BABYLON = {}));
  18070. var BABYLON;
  18071. (function (BABYLON) {
  18072. var Tags = (function () {
  18073. function Tags() {
  18074. }
  18075. Tags.EnableFor = function (obj) {
  18076. obj._tags = obj._tags || {};
  18077. obj.hasTags = function () {
  18078. return Tags.HasTags(obj);
  18079. };
  18080. obj.addTags = function (tagsString) {
  18081. return Tags.AddTagsTo(obj, tagsString);
  18082. };
  18083. obj.removeTags = function (tagsString) {
  18084. return Tags.RemoveTagsFrom(obj, tagsString);
  18085. };
  18086. obj.matchesTagsQuery = function (tagsQuery) {
  18087. return Tags.MatchesQuery(obj, tagsQuery);
  18088. };
  18089. };
  18090. Tags.DisableFor = function (obj) {
  18091. delete obj._tags;
  18092. delete obj.hasTags;
  18093. delete obj.addTags;
  18094. delete obj.removeTags;
  18095. delete obj.matchesTagsQuery;
  18096. };
  18097. Tags.HasTags = function (obj) {
  18098. if (!obj._tags) {
  18099. return false;
  18100. }
  18101. return !BABYLON.Tools.IsEmpty(obj._tags);
  18102. };
  18103. Tags.GetTags = function (obj) {
  18104. if (!obj._tags) {
  18105. return null;
  18106. }
  18107. return obj._tags;
  18108. };
  18109. Tags.AddTagsTo = function (obj, tagsString) {
  18110. if (!tagsString) {
  18111. return;
  18112. }
  18113. var tags = tagsString.split(" ");
  18114. for (var t in tags) {
  18115. Tags._AddTagTo(obj, tags[t]);
  18116. }
  18117. };
  18118. Tags._AddTagTo = function (obj, tag) {
  18119. tag = tag.trim();
  18120. if (tag === "" || tag === "true" || tag === "false") {
  18121. return;
  18122. }
  18123. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  18124. return;
  18125. }
  18126. Tags.EnableFor(obj);
  18127. obj._tags[tag] = true;
  18128. };
  18129. Tags.RemoveTagsFrom = function (obj, tagsString) {
  18130. if (!Tags.HasTags(obj)) {
  18131. return;
  18132. }
  18133. var tags = tagsString.split(" ");
  18134. for (var t in tags) {
  18135. Tags._RemoveTagFrom(obj, tags[t]);
  18136. }
  18137. };
  18138. Tags._RemoveTagFrom = function (obj, tag) {
  18139. delete obj._tags[tag];
  18140. };
  18141. Tags.MatchesQuery = function (obj, tagsQuery) {
  18142. if (tagsQuery === undefined) {
  18143. return true;
  18144. }
  18145. if (tagsQuery === "") {
  18146. return Tags.HasTags(obj);
  18147. }
  18148. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  18149. return Tags.HasTags(obj) && obj._tags[r];
  18150. });
  18151. };
  18152. return Tags;
  18153. })();
  18154. BABYLON.Tags = Tags;
  18155. })(BABYLON || (BABYLON = {}));
  18156. var BABYLON;
  18157. (function (BABYLON) {
  18158. (function (Internals) {
  18159. var AndOrNotEvaluator = (function () {
  18160. function AndOrNotEvaluator() {
  18161. }
  18162. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  18163. if (!query.match(/\([^\(\)]*\)/g)) {
  18164. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  18165. } else {
  18166. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  18167. r = r.slice(1, r.length - 1);
  18168. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  18169. });
  18170. }
  18171. if (query === "true") {
  18172. return true;
  18173. }
  18174. if (query === "false") {
  18175. return false;
  18176. }
  18177. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  18178. };
  18179. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  18180. evaluateCallback = evaluateCallback || (function (r) {
  18181. return r === "true" ? true : false;
  18182. });
  18183. var result;
  18184. var or = parenthesisContent.split("||");
  18185. for (var i in or) {
  18186. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  18187. var and = ori.split("&&");
  18188. if (and.length > 1) {
  18189. for (var j = 0; j < and.length; ++j) {
  18190. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  18191. if (andj !== "true" && andj !== "false") {
  18192. if (andj[0] === "!") {
  18193. result = !evaluateCallback(andj.substring(1));
  18194. } else {
  18195. result = evaluateCallback(andj);
  18196. }
  18197. } else {
  18198. result = andj === "true" ? true : false;
  18199. }
  18200. if (!result) {
  18201. ori = "false";
  18202. break;
  18203. }
  18204. }
  18205. }
  18206. if (result || ori === "true") {
  18207. result = true;
  18208. break;
  18209. }
  18210. if (ori !== "true" && ori !== "false") {
  18211. if (ori[0] === "!") {
  18212. result = !evaluateCallback(ori.substring(1));
  18213. } else {
  18214. result = evaluateCallback(ori);
  18215. }
  18216. } else {
  18217. result = ori === "true" ? true : false;
  18218. }
  18219. }
  18220. return result ? "true" : "false";
  18221. };
  18222. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  18223. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  18224. r = r.replace(/[\s]/g, function () {
  18225. return "";
  18226. });
  18227. return r.length % 2 ? "!" : "";
  18228. });
  18229. booleanString = booleanString.trim();
  18230. if (booleanString === "!true") {
  18231. booleanString = "false";
  18232. } else if (booleanString === "!false") {
  18233. booleanString = "true";
  18234. }
  18235. return booleanString;
  18236. };
  18237. return AndOrNotEvaluator;
  18238. })();
  18239. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  18240. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18241. var Internals = BABYLON.Internals;
  18242. })(BABYLON || (BABYLON = {}));
  18243. var BABYLON;
  18244. (function (BABYLON) {
  18245. var PostProcessRenderPass = (function () {
  18246. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  18247. this._enabled = true;
  18248. this._refCount = 0;
  18249. this._name = name;
  18250. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  18251. this.setRenderList(renderList);
  18252. this._renderTexture.onBeforeRender = beforeRender;
  18253. this._renderTexture.onAfterRender = afterRender;
  18254. this._scene = scene;
  18255. }
  18256. PostProcessRenderPass.prototype._incRefCount = function () {
  18257. if (this._refCount === 0) {
  18258. this._scene.customRenderTargets.push(this._renderTexture);
  18259. }
  18260. return ++this._refCount;
  18261. };
  18262. PostProcessRenderPass.prototype._decRefCount = function () {
  18263. this._refCount--;
  18264. if (this._refCount <= 0) {
  18265. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  18266. }
  18267. return this._refCount;
  18268. };
  18269. PostProcessRenderPass.prototype._update = function () {
  18270. this.setRenderList(this._renderList);
  18271. };
  18272. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  18273. this._renderTexture.renderList = renderList;
  18274. };
  18275. PostProcessRenderPass.prototype.getRenderTexture = function () {
  18276. return this._renderTexture;
  18277. };
  18278. return PostProcessRenderPass;
  18279. })();
  18280. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  18281. })(BABYLON || (BABYLON = {}));
  18282. var BABYLON;
  18283. (function (BABYLON) {
  18284. var PostProcessRenderEffect = (function () {
  18285. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  18286. this._engine = engine;
  18287. this._name = name;
  18288. this._singleInstance = singleInstance || true;
  18289. this._getPostProcess = getPostProcess;
  18290. this._cameras = [];
  18291. this._postProcesses = [];
  18292. this._indicesForCamera = [];
  18293. this._renderPasses = [];
  18294. this._renderEffectAsPasses = [];
  18295. }
  18296. PostProcessRenderEffect.prototype._update = function () {
  18297. for (var renderPassName in this._renderPasses) {
  18298. this._renderPasses[renderPassName]._update();
  18299. }
  18300. };
  18301. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  18302. this._renderPasses[renderPass._name] = renderPass;
  18303. this._linkParameters();
  18304. };
  18305. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  18306. delete this._renderPasses[renderPass._name];
  18307. this._linkParameters();
  18308. };
  18309. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  18310. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  18311. this._linkParameters();
  18312. };
  18313. PostProcessRenderEffect.prototype.getPass = function (passName) {
  18314. for (var renderPassName in this._renderPasses) {
  18315. if (renderPassName === passName) {
  18316. return this._renderPasses[passName];
  18317. }
  18318. }
  18319. };
  18320. PostProcessRenderEffect.prototype.emptyPasses = function () {
  18321. this._renderPasses.length = 0;
  18322. this._linkParameters();
  18323. };
  18324. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  18325. var cameraKey;
  18326. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18327. for (var i = 0; i < _cam.length; i++) {
  18328. var camera = _cam[i];
  18329. var cameraName = camera.name;
  18330. if (this._singleInstance) {
  18331. cameraKey = 0;
  18332. } else {
  18333. cameraKey = cameraName;
  18334. }
  18335. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  18336. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  18337. if (!this._indicesForCamera[cameraName]) {
  18338. this._indicesForCamera[cameraName] = [];
  18339. }
  18340. this._indicesForCamera[cameraName].push(index);
  18341. if (this._cameras.indexOf(camera) === -1) {
  18342. this._cameras[cameraName] = camera;
  18343. }
  18344. for (var passName in this._renderPasses) {
  18345. this._renderPasses[passName]._incRefCount();
  18346. }
  18347. }
  18348. this._linkParameters();
  18349. };
  18350. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  18351. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18352. for (var i = 0; i < _cam.length; i++) {
  18353. var camera = _cam[i];
  18354. var cameraName = camera.name;
  18355. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  18356. var index = this._cameras.indexOf(cameraName);
  18357. this._indicesForCamera.splice(index, 1);
  18358. this._cameras.splice(index, 1);
  18359. for (var passName in this._renderPasses) {
  18360. this._renderPasses[passName]._decRefCount();
  18361. }
  18362. }
  18363. };
  18364. PostProcessRenderEffect.prototype._enable = function (cameras) {
  18365. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18366. for (var i = 0; i < _cam.length; i++) {
  18367. var camera = _cam[i];
  18368. var cameraName = camera.name;
  18369. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  18370. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  18371. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  18372. }
  18373. }
  18374. for (var passName in this._renderPasses) {
  18375. this._renderPasses[passName]._incRefCount();
  18376. }
  18377. }
  18378. };
  18379. PostProcessRenderEffect.prototype._disable = function (cameras) {
  18380. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18381. for (var i = 0; i < _cam.length; i++) {
  18382. var camera = _cam[i];
  18383. var cameraName = camera.Name;
  18384. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  18385. for (var passName in this._renderPasses) {
  18386. this._renderPasses[passName]._decRefCount();
  18387. }
  18388. }
  18389. };
  18390. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  18391. if (this._singleInstance) {
  18392. return this._postProcesses[0];
  18393. } else {
  18394. return this._postProcesses[camera.name];
  18395. }
  18396. };
  18397. PostProcessRenderEffect.prototype._linkParameters = function () {
  18398. var _this = this;
  18399. for (var index in this._postProcesses) {
  18400. if (this.applyParameters) {
  18401. this.applyParameters(this._postProcesses[index]);
  18402. }
  18403. this._postProcesses[index].onBeforeRender = function (effect) {
  18404. _this._linkTextures(effect);
  18405. };
  18406. }
  18407. };
  18408. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  18409. for (var renderPassName in this._renderPasses) {
  18410. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  18411. }
  18412. for (var renderEffectName in this._renderEffectAsPasses) {
  18413. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  18414. }
  18415. };
  18416. return PostProcessRenderEffect;
  18417. })();
  18418. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  18419. })(BABYLON || (BABYLON = {}));
  18420. var BABYLON;
  18421. (function (BABYLON) {
  18422. var PostProcessRenderPipeline = (function () {
  18423. function PostProcessRenderPipeline(engine, name) {
  18424. this._engine = engine;
  18425. this._name = name;
  18426. this._renderEffects = [];
  18427. this._renderEffectsForIsolatedPass = [];
  18428. this._cameras = [];
  18429. }
  18430. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  18431. this._renderEffects[renderEffect._name] = renderEffect;
  18432. };
  18433. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  18434. var renderEffects = this._renderEffects[renderEffectName];
  18435. if (!renderEffects) {
  18436. return;
  18437. }
  18438. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  18439. };
  18440. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  18441. var renderEffects = this._renderEffects[renderEffectName];
  18442. if (!renderEffects) {
  18443. return;
  18444. }
  18445. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  18446. };
  18447. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  18448. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18449. var indicesToDelete = [];
  18450. for (var i = 0; i < _cam.length; i++) {
  18451. var camera = _cam[i];
  18452. var cameraName = camera.name;
  18453. if (this._cameras.indexOf(camera) === -1) {
  18454. this._cameras[cameraName] = camera;
  18455. } else if (unique) {
  18456. indicesToDelete.push(i);
  18457. }
  18458. }
  18459. for (var i = 0; i < indicesToDelete.length; i++) {
  18460. cameras.splice(indicesToDelete[i], 1);
  18461. }
  18462. for (var renderEffectName in this._renderEffects) {
  18463. this._renderEffects[renderEffectName]._attachCameras(_cam);
  18464. }
  18465. };
  18466. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  18467. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18468. for (var renderEffectName in this._renderEffects) {
  18469. this._renderEffects[renderEffectName]._detachCameras(_cam);
  18470. }
  18471. for (var i = 0; i < _cam.length; i++) {
  18472. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  18473. }
  18474. };
  18475. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  18476. var _this = this;
  18477. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18478. var pass = null;
  18479. for (var renderEffectName in this._renderEffects) {
  18480. pass = this._renderEffects[renderEffectName].getPass(passName);
  18481. if (pass != null) {
  18482. break;
  18483. }
  18484. }
  18485. if (pass === null) {
  18486. return;
  18487. }
  18488. for (var renderEffectName in this._renderEffects) {
  18489. this._renderEffects[renderEffectName]._disable(_cam);
  18490. }
  18491. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  18492. for (var i = 0; i < _cam.length; i++) {
  18493. var camera = _cam[i];
  18494. var cameraName = camera.name;
  18495. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  18496. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  18497. });
  18498. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  18499. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  18500. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  18501. }
  18502. };
  18503. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  18504. var _this = this;
  18505. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18506. for (var i = 0; i < _cam.length; i++) {
  18507. var camera = _cam[i];
  18508. var cameraName = camera.name;
  18509. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  18510. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  18511. });
  18512. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  18513. }
  18514. for (var renderEffectName in this._renderEffects) {
  18515. this._renderEffects[renderEffectName]._enable(_cam);
  18516. }
  18517. };
  18518. PostProcessRenderPipeline.prototype._update = function () {
  18519. for (var renderEffectName in this._renderEffects) {
  18520. this._renderEffects[renderEffectName]._update();
  18521. }
  18522. for (var i = 0; i < this._cameras.length; i++) {
  18523. var cameraName = this._cameras[i].name;
  18524. if (this._renderEffectsForIsolatedPass[cameraName]) {
  18525. this._renderEffectsForIsolatedPass[cameraName]._update();
  18526. }
  18527. }
  18528. };
  18529. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  18530. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  18531. return PostProcessRenderPipeline;
  18532. })();
  18533. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  18534. })(BABYLON || (BABYLON = {}));
  18535. var BABYLON;
  18536. (function (BABYLON) {
  18537. var PostProcessRenderPipelineManager = (function () {
  18538. function PostProcessRenderPipelineManager() {
  18539. this._renderPipelines = new Array();
  18540. }
  18541. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  18542. this._renderPipelines[renderPipeline._name] = renderPipeline;
  18543. };
  18544. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  18545. var renderPipeline = this._renderPipelines[renderPipelineName];
  18546. if (!renderPipeline) {
  18547. return;
  18548. }
  18549. renderPipeline._attachCameras(cameras, unique);
  18550. };
  18551. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  18552. var renderPipeline = this._renderPipelines[renderPipelineName];
  18553. if (!renderPipeline) {
  18554. return;
  18555. }
  18556. renderPipeline._detachCameras(cameras);
  18557. };
  18558. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  18559. var renderPipeline = this._renderPipelines[renderPipelineName];
  18560. if (!renderPipeline) {
  18561. return;
  18562. }
  18563. renderPipeline._enableEffect(renderEffectName, cameras);
  18564. };
  18565. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  18566. var renderPipeline = this._renderPipelines[renderPipelineName];
  18567. if (!renderPipeline) {
  18568. return;
  18569. }
  18570. renderPipeline._disableEffect(renderEffectName, cameras);
  18571. };
  18572. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  18573. var renderPipeline = this._renderPipelines[renderPipelineName];
  18574. if (!renderPipeline) {
  18575. return;
  18576. }
  18577. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  18578. };
  18579. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  18580. var renderPipeline = this._renderPipelines[renderPipelineName];
  18581. if (!renderPipeline) {
  18582. return;
  18583. }
  18584. renderPipeline._disableDisplayOnlyPass(cameras);
  18585. };
  18586. PostProcessRenderPipelineManager.prototype.update = function () {
  18587. for (var renderPipelineName in this._renderPipelines) {
  18588. this._renderPipelines[renderPipelineName]._update();
  18589. }
  18590. };
  18591. return PostProcessRenderPipelineManager;
  18592. })();
  18593. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  18594. })(BABYLON || (BABYLON = {}));
  18595. var __extends = this.__extends || function (d, b) {
  18596. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18597. function __() { this.constructor = d; }
  18598. __.prototype = b.prototype;
  18599. d.prototype = new __();
  18600. };
  18601. var BABYLON;
  18602. (function (BABYLON) {
  18603. var DisplayPassPostProcess = (function (_super) {
  18604. __extends(DisplayPassPostProcess, _super);
  18605. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18606. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  18607. }
  18608. return DisplayPassPostProcess;
  18609. })(BABYLON.PostProcess);
  18610. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  18611. })(BABYLON || (BABYLON = {}));
  18612. var BABYLON;
  18613. (function (BABYLON) {
  18614. var BoundingBoxRenderer = (function () {
  18615. function BoundingBoxRenderer(scene) {
  18616. this.frontColor = new BABYLON.Color3(1, 1, 1);
  18617. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  18618. this.showBackLines = true;
  18619. this.renderList = new BABYLON.SmartArray(32);
  18620. this._scene = scene;
  18621. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  18622. attributes: ["position"],
  18623. uniforms: ["worldViewProjection", "color"]
  18624. });
  18625. var engine = this._scene.getEngine();
  18626. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  18627. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  18628. 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]);
  18629. }
  18630. BoundingBoxRenderer.prototype.reset = function () {
  18631. this.renderList.reset();
  18632. };
  18633. BoundingBoxRenderer.prototype.render = function () {
  18634. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  18635. return;
  18636. }
  18637. var engine = this._scene.getEngine();
  18638. engine.setDepthWrite(false);
  18639. this._colorShader._preBind();
  18640. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  18641. var boundingBox = this.renderList.data[boundingBoxIndex];
  18642. var min = boundingBox.minimum;
  18643. var max = boundingBox.maximum;
  18644. var diff = max.subtract(min);
  18645. var median = min.add(diff.scale(0.5));
  18646. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  18647. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  18648. if (this.showBackLines) {
  18649. engine.setDepthFunctionToGreaterOrEqual();
  18650. this._colorShader.setColor4("color", this.backColor.toColor4());
  18651. this._colorShader.bind(worldMatrix);
  18652. engine.draw(false, 0, 24);
  18653. }
  18654. engine.setDepthFunctionToLess();
  18655. this._colorShader.setColor4("color", this.frontColor.toColor4());
  18656. this._colorShader.bind(worldMatrix);
  18657. engine.draw(false, 0, 24);
  18658. }
  18659. this._colorShader.unbind();
  18660. engine.setDepthFunctionToLessOrEqual();
  18661. engine.setDepthWrite(true);
  18662. };
  18663. BoundingBoxRenderer.prototype.dispose = function () {
  18664. this._colorShader.dispose();
  18665. this._vb.dispose();
  18666. this._scene.getEngine()._releaseBuffer(this._ib);
  18667. };
  18668. return BoundingBoxRenderer;
  18669. })();
  18670. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  18671. })(BABYLON || (BABYLON = {}));
  18672. /**
  18673. * Based on jsTGALoader - Javascript loader for TGA file
  18674. * By Vincent Thibault
  18675. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  18676. */
  18677. var BABYLON;
  18678. (function (BABYLON) {
  18679. (function (Internals) {
  18680. var TGATools = (function () {
  18681. function TGATools() {
  18682. }
  18683. TGATools.GetTGAHeader = function (data) {
  18684. var offset = 0;
  18685. var header = {
  18686. id_length: data[offset++],
  18687. colormap_type: data[offset++],
  18688. image_type: data[offset++],
  18689. colormap_index: data[offset++] | data[offset++] << 8,
  18690. colormap_length: data[offset++] | data[offset++] << 8,
  18691. colormap_size: data[offset++],
  18692. origin: [
  18693. data[offset++] | data[offset++] << 8,
  18694. data[offset++] | data[offset++] << 8
  18695. ],
  18696. width: data[offset++] | data[offset++] << 8,
  18697. height: data[offset++] | data[offset++] << 8,
  18698. pixel_size: data[offset++],
  18699. flags: data[offset++]
  18700. };
  18701. return header;
  18702. };
  18703. TGATools.UploadContent = function (gl, data) {
  18704. if (data.length < 19) {
  18705. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  18706. return;
  18707. }
  18708. var offset = 18;
  18709. var header = TGATools.GetTGAHeader(data);
  18710. if (header.id_length + offset > data.length) {
  18711. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  18712. return;
  18713. }
  18714. offset += header.id_length;
  18715. var use_rle = false;
  18716. var use_pal = false;
  18717. var use_rgb = false;
  18718. var use_grey = false;
  18719. switch (header.image_type) {
  18720. case TGATools._TYPE_RLE_INDEXED:
  18721. use_rle = true;
  18722. case TGATools._TYPE_INDEXED:
  18723. use_pal = true;
  18724. break;
  18725. case TGATools._TYPE_RLE_RGB:
  18726. use_rle = true;
  18727. case TGATools._TYPE_RGB:
  18728. use_rgb = true;
  18729. break;
  18730. case TGATools._TYPE_RLE_GREY:
  18731. use_rle = true;
  18732. case TGATools._TYPE_GREY:
  18733. use_grey = true;
  18734. break;
  18735. }
  18736. var pixel_data;
  18737. var numAlphaBits = header.flags & 0xf;
  18738. var pixel_size = header.pixel_size >> 3;
  18739. var pixel_total = header.width * header.height * pixel_size;
  18740. var palettes;
  18741. if (use_pal) {
  18742. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  18743. }
  18744. if (use_rle) {
  18745. pixel_data = new Uint8Array(pixel_total);
  18746. var c, count, i;
  18747. var localOffset = 0;
  18748. var pixels = new Uint8Array(pixel_size);
  18749. while (offset < pixel_total && localOffset < pixel_total) {
  18750. c = data[offset++];
  18751. count = (c & 0x7f) + 1;
  18752. if (c & 0x80) {
  18753. for (i = 0; i < pixel_size; ++i) {
  18754. pixels[i] = data[offset++];
  18755. }
  18756. for (i = 0; i < count; ++i) {
  18757. pixel_data.set(pixels, localOffset + i * pixel_size);
  18758. }
  18759. localOffset += pixel_size * count;
  18760. } else {
  18761. count *= pixel_size;
  18762. for (i = 0; i < count; ++i) {
  18763. pixel_data[localOffset + i] = data[offset++];
  18764. }
  18765. localOffset += count;
  18766. }
  18767. }
  18768. } else {
  18769. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  18770. }
  18771. var x_start, y_start, x_step, y_step, y_end, x_end;
  18772. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  18773. default:
  18774. case TGATools._ORIGIN_UL:
  18775. x_start = 0;
  18776. x_step = 1;
  18777. x_end = header.width;
  18778. y_start = 0;
  18779. y_step = 1;
  18780. y_end = header.height;
  18781. break;
  18782. case TGATools._ORIGIN_BL:
  18783. x_start = 0;
  18784. x_step = 1;
  18785. x_end = header.width;
  18786. y_start = header.height - 1;
  18787. y_step = -1;
  18788. y_end = -1;
  18789. break;
  18790. case TGATools._ORIGIN_UR:
  18791. x_start = header.width - 1;
  18792. x_step = -1;
  18793. x_end = -1;
  18794. y_start = 0;
  18795. y_step = 1;
  18796. y_end = header.height;
  18797. break;
  18798. case TGATools._ORIGIN_BR:
  18799. x_start = header.width - 1;
  18800. x_step = -1;
  18801. x_end = -1;
  18802. y_start = header.height - 1;
  18803. y_step = -1;
  18804. y_end = -1;
  18805. break;
  18806. }
  18807. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  18808. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  18809. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  18810. };
  18811. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18812. var image = pixel_data, colormap = palettes;
  18813. var width = header.width, height = header.height;
  18814. var color, i = 0, x, y;
  18815. var imageData = new Uint8Array(width * height * 4);
  18816. for (y = y_start; y !== y_end; y += y_step) {
  18817. for (x = x_start; x !== x_end; x += x_step, i++) {
  18818. color = image[i];
  18819. imageData[(x + width * y) * 4 + 3] = 255;
  18820. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  18821. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  18822. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  18823. }
  18824. }
  18825. return imageData;
  18826. };
  18827. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18828. var image = pixel_data;
  18829. var width = header.width, height = header.height;
  18830. var color, i = 0, x, y;
  18831. var imageData = new Uint8Array(width * height * 4);
  18832. for (y = y_start; y !== y_end; y += y_step) {
  18833. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  18834. color = image[i + 0] + (image[i + 1] << 8);
  18835. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  18836. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  18837. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  18838. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  18839. }
  18840. }
  18841. return imageData;
  18842. };
  18843. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18844. var image = pixel_data;
  18845. var width = header.width, height = header.height;
  18846. var i = 0, x, y;
  18847. var imageData = new Uint8Array(width * height * 4);
  18848. for (y = y_start; y !== y_end; y += y_step) {
  18849. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  18850. imageData[(x + width * y) * 4 + 3] = 255;
  18851. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  18852. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  18853. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  18854. }
  18855. }
  18856. return imageData;
  18857. };
  18858. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18859. var image = pixel_data;
  18860. var width = header.width, height = header.height;
  18861. var i = 0, x, y;
  18862. var imageData = new Uint8Array(width * height * 4);
  18863. for (y = y_start; y !== y_end; y += y_step) {
  18864. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  18865. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  18866. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  18867. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  18868. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  18869. }
  18870. }
  18871. return imageData;
  18872. };
  18873. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18874. var image = pixel_data;
  18875. var width = header.width, height = header.height;
  18876. var color, i = 0, x, y;
  18877. var imageData = new Uint8Array(width * height * 4);
  18878. for (y = y_start; y !== y_end; y += y_step) {
  18879. for (x = x_start; x !== x_end; x += x_step, i++) {
  18880. color = image[i];
  18881. imageData[(x + width * y) * 4 + 0] = color;
  18882. imageData[(x + width * y) * 4 + 1] = color;
  18883. imageData[(x + width * y) * 4 + 2] = color;
  18884. imageData[(x + width * y) * 4 + 3] = 255;
  18885. }
  18886. }
  18887. return imageData;
  18888. };
  18889. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18890. var image = pixel_data;
  18891. var width = header.width, height = header.height;
  18892. var i = 0, x, y;
  18893. var imageData = new Uint8Array(width * height * 4);
  18894. for (y = y_start; y !== y_end; y += y_step) {
  18895. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  18896. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  18897. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  18898. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  18899. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  18900. }
  18901. }
  18902. return imageData;
  18903. };
  18904. TGATools._TYPE_NO_DATA = 0;
  18905. TGATools._TYPE_INDEXED = 1;
  18906. TGATools._TYPE_RGB = 2;
  18907. TGATools._TYPE_GREY = 3;
  18908. TGATools._TYPE_RLE_INDEXED = 9;
  18909. TGATools._TYPE_RLE_RGB = 10;
  18910. TGATools._TYPE_RLE_GREY = 11;
  18911. TGATools._ORIGIN_MASK = 0x30;
  18912. TGATools._ORIGIN_SHIFT = 0x04;
  18913. TGATools._ORIGIN_BL = 0x00;
  18914. TGATools._ORIGIN_BR = 0x01;
  18915. TGATools._ORIGIN_UL = 0x02;
  18916. TGATools._ORIGIN_UR = 0x03;
  18917. return TGATools;
  18918. })();
  18919. Internals.TGATools = TGATools;
  18920. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18921. var Internals = BABYLON.Internals;
  18922. })(BABYLON || (BABYLON = {}));
  18923. var BABYLON;
  18924. (function (BABYLON) {
  18925. (function (Internals) {
  18926. var DDS_MAGIC = 0x20534444;
  18927. 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;
  18928. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  18929. 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;
  18930. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  18931. function FourCCToInt32(value) {
  18932. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  18933. }
  18934. function Int32ToFourCC(value) {
  18935. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  18936. }
  18937. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  18938. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  18939. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  18940. var headerLengthInt = 31;
  18941. var off_magic = 0;
  18942. var off_size = 1;
  18943. var off_flags = 2;
  18944. var off_height = 3;
  18945. var off_width = 4;
  18946. var off_mipmapCount = 7;
  18947. var off_pfFlags = 20;
  18948. var off_pfFourCC = 21;
  18949. var off_RGBbpp = 22;
  18950. var off_RMask = 23;
  18951. var off_GMask = 24;
  18952. var off_BMask = 25;
  18953. var off_AMask = 26;
  18954. var off_caps1 = 27;
  18955. var off_caps2 = 28;
  18956. ;
  18957. var DDSTools = (function () {
  18958. function DDSTools() {
  18959. }
  18960. DDSTools.GetDDSInfo = function (arrayBuffer) {
  18961. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  18962. var mipmapCount = 1;
  18963. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  18964. mipmapCount = Math.max(1, header[off_mipmapCount]);
  18965. }
  18966. return {
  18967. width: header[off_width],
  18968. height: header[off_height],
  18969. mipmapCount: mipmapCount,
  18970. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  18971. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  18972. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  18973. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  18974. };
  18975. };
  18976. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  18977. var byteArray = new Uint8Array(dataLength);
  18978. var srcData = new Uint8Array(arrayBuffer);
  18979. var index = 0;
  18980. for (var y = height - 1; y >= 0; y--) {
  18981. for (var x = 0; x < width; x++) {
  18982. var srcPos = dataOffset + (x + y * width) * 4;
  18983. byteArray[index + 2] = srcData[srcPos];
  18984. byteArray[index + 1] = srcData[srcPos + 1];
  18985. byteArray[index] = srcData[srcPos + 2];
  18986. byteArray[index + 3] = srcData[srcPos + 3];
  18987. index += 4;
  18988. }
  18989. }
  18990. return byteArray;
  18991. };
  18992. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  18993. var byteArray = new Uint8Array(dataLength);
  18994. var srcData = new Uint8Array(arrayBuffer);
  18995. var index = 0;
  18996. for (var y = height - 1; y >= 0; y--) {
  18997. for (var x = 0; x < width; x++) {
  18998. var srcPos = dataOffset + (x + y * width) * 3;
  18999. byteArray[index + 2] = srcData[srcPos];
  19000. byteArray[index + 1] = srcData[srcPos + 1];
  19001. byteArray[index] = srcData[srcPos + 2];
  19002. index += 3;
  19003. }
  19004. }
  19005. return byteArray;
  19006. };
  19007. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  19008. var byteArray = new Uint8Array(dataLength);
  19009. var srcData = new Uint8Array(arrayBuffer);
  19010. var index = 0;
  19011. for (var y = height - 1; y >= 0; y--) {
  19012. for (var x = 0; x < width; x++) {
  19013. var srcPos = dataOffset + (x + y * width);
  19014. byteArray[index] = srcData[srcPos];
  19015. index++;
  19016. }
  19017. }
  19018. return byteArray;
  19019. };
  19020. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  19021. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  19022. if (header[off_magic] != DDS_MAGIC) {
  19023. BABYLON.Tools.Error("Invalid magic number in DDS header");
  19024. return;
  19025. }
  19026. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  19027. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  19028. return;
  19029. }
  19030. if (info.isFourCC) {
  19031. fourCC = header[off_pfFourCC];
  19032. switch (fourCC) {
  19033. case FOURCC_DXT1:
  19034. blockBytes = 8;
  19035. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  19036. break;
  19037. case FOURCC_DXT3:
  19038. blockBytes = 16;
  19039. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  19040. break;
  19041. case FOURCC_DXT5:
  19042. blockBytes = 16;
  19043. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  19044. break;
  19045. default:
  19046. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  19047. return;
  19048. }
  19049. }
  19050. mipmapCount = 1;
  19051. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  19052. mipmapCount = Math.max(1, header[off_mipmapCount]);
  19053. }
  19054. var bpp = header[off_RGBbpp];
  19055. for (var face = 0; face < faces; face++) {
  19056. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  19057. width = header[off_width];
  19058. height = header[off_height];
  19059. dataOffset = header[off_size] + 4;
  19060. for (i = 0; i < mipmapCount; ++i) {
  19061. if (info.isRGB) {
  19062. if (bpp == 24) {
  19063. dataLength = width * height * 3;
  19064. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  19065. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  19066. } else {
  19067. dataLength = width * height * 4;
  19068. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  19069. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  19070. }
  19071. } else if (info.isLuminance) {
  19072. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  19073. var unpaddedRowSize = width;
  19074. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  19075. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  19076. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  19077. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  19078. } else {
  19079. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  19080. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  19081. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  19082. }
  19083. dataOffset += dataLength;
  19084. width *= 0.5;
  19085. height *= 0.5;
  19086. width = Math.max(1.0, width);
  19087. height = Math.max(1.0, height);
  19088. }
  19089. }
  19090. };
  19091. return DDSTools;
  19092. })();
  19093. Internals.DDSTools = DDSTools;
  19094. })(BABYLON.Internals || (BABYLON.Internals = {}));
  19095. var Internals = BABYLON.Internals;
  19096. })(BABYLON || (BABYLON = {}));
  19097. var BABYLON;
  19098. (function (BABYLON) {
  19099. var SmartArray = (function () {
  19100. function SmartArray(capacity) {
  19101. this.length = 0;
  19102. this._duplicateId = 0;
  19103. this.data = new Array(capacity);
  19104. this._id = SmartArray._GlobalId++;
  19105. }
  19106. SmartArray.prototype.push = function (value) {
  19107. this.data[this.length++] = value;
  19108. if (this.length > this.data.length) {
  19109. this.data.length *= 2;
  19110. }
  19111. if (!value.__smartArrayFlags) {
  19112. value.__smartArrayFlags = {};
  19113. }
  19114. value.__smartArrayFlags[this._id] = this._duplicateId;
  19115. };
  19116. SmartArray.prototype.pushNoDuplicate = function (value) {
  19117. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  19118. return;
  19119. }
  19120. this.push(value);
  19121. };
  19122. SmartArray.prototype.sort = function (compareFn) {
  19123. this.data.sort(compareFn);
  19124. };
  19125. SmartArray.prototype.reset = function () {
  19126. this.length = 0;
  19127. this._duplicateId++;
  19128. };
  19129. SmartArray.prototype.concat = function (array) {
  19130. if (array.length === 0) {
  19131. return;
  19132. }
  19133. if (this.length + array.length > this.data.length) {
  19134. this.data.length = (this.length + array.length) * 2;
  19135. }
  19136. for (var index = 0; index < array.length; index++) {
  19137. this.data[this.length++] = (array.data || array)[index];
  19138. }
  19139. };
  19140. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  19141. if (array.length === 0) {
  19142. return;
  19143. }
  19144. if (this.length + array.length > this.data.length) {
  19145. this.data.length = (this.length + array.length) * 2;
  19146. }
  19147. for (var index = 0; index < array.length; index++) {
  19148. var item = (array.data || array)[index];
  19149. this.pushNoDuplicate(item);
  19150. }
  19151. };
  19152. SmartArray.prototype.indexOf = function (value) {
  19153. var position = this.data.indexOf(value);
  19154. if (position >= this.length) {
  19155. return -1;
  19156. }
  19157. return position;
  19158. };
  19159. SmartArray._GlobalId = 0;
  19160. return SmartArray;
  19161. })();
  19162. BABYLON.SmartArray = SmartArray;
  19163. })(BABYLON || (BABYLON = {}));
  19164. var BABYLON;
  19165. (function (BABYLON) {
  19166. var CannonJSPlugin = (function () {
  19167. function CannonJSPlugin() {
  19168. this._registeredMeshes = [];
  19169. this._physicsMaterials = [];
  19170. this.updateBodyPosition = function (mesh) {
  19171. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19172. var registeredMesh = this._registeredMeshes[index];
  19173. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  19174. var body = registeredMesh.body;
  19175. var center = mesh.getBoundingInfo().boundingBox.center;
  19176. body.position.set(center.x, center.z, center.y);
  19177. body.quaternion.x = mesh.rotationQuaternion.x;
  19178. body.quaternion.z = mesh.rotationQuaternion.y;
  19179. body.quaternion.y = mesh.rotationQuaternion.z;
  19180. body.quaternion.w = -mesh.rotationQuaternion.w;
  19181. return;
  19182. }
  19183. }
  19184. };
  19185. }
  19186. CannonJSPlugin.prototype.initialize = function (iterations) {
  19187. if (typeof iterations === "undefined") { iterations = 10; }
  19188. this._world = new CANNON.World();
  19189. this._world.broadphase = new CANNON.NaiveBroadphase();
  19190. this._world.solver.iterations = iterations;
  19191. };
  19192. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  19193. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  19194. };
  19195. CannonJSPlugin.prototype.runOneStep = function (delta) {
  19196. this._world.step(delta);
  19197. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19198. var registeredMesh = this._registeredMeshes[index];
  19199. if (registeredMesh.isChild) {
  19200. continue;
  19201. }
  19202. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  19203. var deltaPos = registeredMesh.delta;
  19204. if (deltaPos) {
  19205. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  19206. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  19207. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  19208. } else {
  19209. registeredMesh.mesh.position.x = bodyX;
  19210. registeredMesh.mesh.position.y = bodyZ;
  19211. registeredMesh.mesh.position.z = bodyY;
  19212. }
  19213. if (!registeredMesh.mesh.rotationQuaternion) {
  19214. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  19215. }
  19216. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  19217. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  19218. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  19219. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  19220. }
  19221. };
  19222. CannonJSPlugin.prototype.setGravity = function (gravity) {
  19223. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  19224. };
  19225. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  19226. this.unregisterMesh(mesh);
  19227. mesh.computeWorldMatrix(true);
  19228. switch (impostor) {
  19229. case BABYLON.PhysicsEngine.SphereImpostor:
  19230. var bbox = mesh.getBoundingInfo().boundingBox;
  19231. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  19232. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  19233. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  19234. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  19235. case BABYLON.PhysicsEngine.BoxImpostor:
  19236. bbox = mesh.getBoundingInfo().boundingBox;
  19237. var min = bbox.minimumWorld;
  19238. var max = bbox.maximumWorld;
  19239. var box = max.subtract(min).scale(0.5);
  19240. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  19241. case BABYLON.PhysicsEngine.PlaneImpostor:
  19242. return this._createPlane(mesh, options);
  19243. case BABYLON.PhysicsEngine.MeshImpostor:
  19244. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19245. var rawFaces = mesh.getIndices();
  19246. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  19247. }
  19248. return null;
  19249. };
  19250. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  19251. var shape = new CANNON.Sphere(radius);
  19252. if (!options) {
  19253. return shape;
  19254. }
  19255. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  19256. };
  19257. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  19258. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  19259. if (!options) {
  19260. return shape;
  19261. }
  19262. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  19263. };
  19264. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  19265. var shape = new CANNON.Plane();
  19266. if (!options) {
  19267. return shape;
  19268. }
  19269. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  19270. };
  19271. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  19272. var verts = [], faces = [];
  19273. mesh.computeWorldMatrix(true);
  19274. for (var i = 0; i < rawVerts.length; i += 3) {
  19275. var transformed = BABYLON.Vector3.Zero();
  19276. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  19277. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  19278. }
  19279. for (var j = 0; j < rawFaces.length; j += 3) {
  19280. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  19281. }
  19282. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  19283. if (!options) {
  19284. return shape;
  19285. }
  19286. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  19287. };
  19288. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  19289. var index;
  19290. var mat;
  19291. for (index = 0; index < this._physicsMaterials.length; index++) {
  19292. mat = this._physicsMaterials[index];
  19293. if (mat.friction === friction && mat.restitution === restitution) {
  19294. return mat;
  19295. }
  19296. }
  19297. var currentMat = new CANNON.Material();
  19298. currentMat.friction = friction;
  19299. currentMat.restitution = restitution;
  19300. this._physicsMaterials.push(currentMat);
  19301. for (index = 0; index < this._physicsMaterials.length; index++) {
  19302. mat = this._physicsMaterials[index];
  19303. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  19304. contactMaterial.contactEquationStiffness = 1e10;
  19305. contactMaterial.contactEquationRegularizationTime = 10;
  19306. this._world.addContactMaterial(contactMaterial);
  19307. }
  19308. return currentMat;
  19309. };
  19310. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  19311. var initialRotation = null;
  19312. if (mesh.rotationQuaternion) {
  19313. initialRotation = mesh.rotationQuaternion.clone();
  19314. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  19315. }
  19316. var bbox = mesh.getBoundingInfo().boundingBox;
  19317. var deltaPosition = mesh.position.subtract(bbox.center);
  19318. var material = this._addMaterial(friction, restitution);
  19319. var body = new CANNON.RigidBody(mass, shape, material);
  19320. if (initialRotation) {
  19321. body.quaternion.x = initialRotation.x;
  19322. body.quaternion.z = initialRotation.y;
  19323. body.quaternion.y = initialRotation.z;
  19324. body.quaternion.w = -initialRotation.w;
  19325. }
  19326. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  19327. this._world.add(body);
  19328. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  19329. return body;
  19330. };
  19331. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  19332. var compoundShape = new CANNON.Compound();
  19333. for (var index = 0; index < parts.length; index++) {
  19334. var mesh = parts[index].mesh;
  19335. var shape = this.registerMesh(mesh, parts[index].impostor);
  19336. if (index == 0) {
  19337. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  19338. } else {
  19339. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  19340. }
  19341. }
  19342. var initialMesh = parts[0].mesh;
  19343. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  19344. body.parts = parts;
  19345. return body;
  19346. };
  19347. CannonJSPlugin.prototype._unbindBody = function (body) {
  19348. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19349. var registeredMesh = this._registeredMeshes[index];
  19350. if (registeredMesh.body === body) {
  19351. registeredMesh.body = null;
  19352. registeredMesh.delta = 0;
  19353. }
  19354. }
  19355. };
  19356. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  19357. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19358. var registeredMesh = this._registeredMeshes[index];
  19359. if (registeredMesh.mesh === mesh) {
  19360. if (registeredMesh.body) {
  19361. this._world.remove(registeredMesh.body);
  19362. this._unbindBody(registeredMesh.body);
  19363. }
  19364. this._registeredMeshes.splice(index, 1);
  19365. return;
  19366. }
  19367. }
  19368. };
  19369. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  19370. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  19371. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  19372. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19373. var registeredMesh = this._registeredMeshes[index];
  19374. if (registeredMesh.mesh === mesh) {
  19375. registeredMesh.body.applyImpulse(impulse, worldPoint);
  19376. return;
  19377. }
  19378. }
  19379. };
  19380. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  19381. var body1 = null, body2 = null;
  19382. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19383. var registeredMesh = this._registeredMeshes[index];
  19384. if (registeredMesh.mesh === mesh1) {
  19385. body1 = registeredMesh.body;
  19386. } else if (registeredMesh.mesh === mesh2) {
  19387. body2 = registeredMesh.body;
  19388. }
  19389. }
  19390. if (!body1 || !body2) {
  19391. return false;
  19392. }
  19393. 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));
  19394. this._world.addConstraint(constraint);
  19395. return true;
  19396. };
  19397. CannonJSPlugin.prototype.dispose = function () {
  19398. while (this._registeredMeshes.length) {
  19399. this.unregisterMesh(this._registeredMeshes[0].mesh);
  19400. }
  19401. };
  19402. CannonJSPlugin.prototype.isSupported = function () {
  19403. return window.CANNON !== undefined;
  19404. };
  19405. return CannonJSPlugin;
  19406. })();
  19407. BABYLON.CannonJSPlugin = CannonJSPlugin;
  19408. })(BABYLON || (BABYLON = {}));
  19409. var __extends = this.__extends || function (d, b) {
  19410. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19411. function __() { this.constructor = d; }
  19412. __.prototype = b.prototype;
  19413. d.prototype = new __();
  19414. };
  19415. var BABYLON;
  19416. (function (BABYLON) {
  19417. var Condition = (function () {
  19418. function Condition(actionManager) {
  19419. this._actionManager = actionManager;
  19420. }
  19421. Condition.prototype.isValid = function () {
  19422. return true;
  19423. };
  19424. Condition.prototype._getProperty = function (propertyPath) {
  19425. return this._actionManager._getProperty(propertyPath);
  19426. };
  19427. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  19428. return this._actionManager._getEffectiveTarget(target, propertyPath);
  19429. };
  19430. return Condition;
  19431. })();
  19432. BABYLON.Condition = Condition;
  19433. var ValueCondition = (function (_super) {
  19434. __extends(ValueCondition, _super);
  19435. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  19436. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  19437. _super.call(this, actionManager);
  19438. this.propertyPath = propertyPath;
  19439. this.value = value;
  19440. this.operator = operator;
  19441. this._target = this._getEffectiveTarget(target, this.propertyPath);
  19442. this._property = this._getProperty(this.propertyPath);
  19443. }
  19444. Object.defineProperty(ValueCondition, "IsEqual", {
  19445. get: function () {
  19446. return ValueCondition._IsEqual;
  19447. },
  19448. enumerable: true,
  19449. configurable: true
  19450. });
  19451. Object.defineProperty(ValueCondition, "IsDifferent", {
  19452. get: function () {
  19453. return ValueCondition._IsDifferent;
  19454. },
  19455. enumerable: true,
  19456. configurable: true
  19457. });
  19458. Object.defineProperty(ValueCondition, "IsGreater", {
  19459. get: function () {
  19460. return ValueCondition._IsGreater;
  19461. },
  19462. enumerable: true,
  19463. configurable: true
  19464. });
  19465. Object.defineProperty(ValueCondition, "IsLesser", {
  19466. get: function () {
  19467. return ValueCondition._IsLesser;
  19468. },
  19469. enumerable: true,
  19470. configurable: true
  19471. });
  19472. ValueCondition.prototype.isValid = function () {
  19473. switch (this.operator) {
  19474. case ValueCondition.IsGreater:
  19475. return this._target[this._property] > this.value;
  19476. case ValueCondition.IsLesser:
  19477. return this._target[this._property] < this.value;
  19478. case ValueCondition.IsEqual:
  19479. case ValueCondition.IsDifferent:
  19480. var check;
  19481. if (this.value.equals) {
  19482. check = this.value.equals(this._target[this._property]);
  19483. } else {
  19484. check = this.value === this._target[this._property];
  19485. }
  19486. return this.operator === ValueCondition.IsEqual ? check : !check;
  19487. }
  19488. return false;
  19489. };
  19490. ValueCondition._IsEqual = 0;
  19491. ValueCondition._IsDifferent = 1;
  19492. ValueCondition._IsGreater = 2;
  19493. ValueCondition._IsLesser = 3;
  19494. return ValueCondition;
  19495. })(Condition);
  19496. BABYLON.ValueCondition = ValueCondition;
  19497. var PredicateCondition = (function (_super) {
  19498. __extends(PredicateCondition, _super);
  19499. function PredicateCondition(actionManager, predicate) {
  19500. _super.call(this, actionManager);
  19501. this.predicate = predicate;
  19502. }
  19503. PredicateCondition.prototype.isValid = function () {
  19504. return this.predicate();
  19505. };
  19506. return PredicateCondition;
  19507. })(Condition);
  19508. BABYLON.PredicateCondition = PredicateCondition;
  19509. var StateCondition = (function (_super) {
  19510. __extends(StateCondition, _super);
  19511. function StateCondition(actionManager, target, value) {
  19512. _super.call(this, actionManager);
  19513. this.value = value;
  19514. this._target = target;
  19515. }
  19516. StateCondition.prototype.isValid = function () {
  19517. return this._target.state === this.value;
  19518. };
  19519. return StateCondition;
  19520. })(Condition);
  19521. BABYLON.StateCondition = StateCondition;
  19522. })(BABYLON || (BABYLON = {}));
  19523. var BABYLON;
  19524. (function (BABYLON) {
  19525. var Action = (function () {
  19526. function Action(triggerOptions, condition) {
  19527. this.triggerOptions = triggerOptions;
  19528. if (triggerOptions.parameter) {
  19529. this.trigger = triggerOptions.trigger;
  19530. this._triggerParameter = triggerOptions.parameter;
  19531. } else {
  19532. this.trigger = triggerOptions;
  19533. }
  19534. this._nextActiveAction = this;
  19535. this._condition = condition;
  19536. }
  19537. Action.prototype._prepare = function () {
  19538. };
  19539. Action.prototype.getTriggerParameter = function () {
  19540. return this._triggerParameter;
  19541. };
  19542. Action.prototype._executeCurrent = function (evt) {
  19543. if (this._condition) {
  19544. var currentRenderId = this._actionManager.getScene().getRenderId();
  19545. if (this._condition._evaluationId === currentRenderId) {
  19546. if (!this._condition._currentResult) {
  19547. return;
  19548. }
  19549. } else {
  19550. this._condition._evaluationId = currentRenderId;
  19551. if (!this._condition.isValid()) {
  19552. this._condition._currentResult = false;
  19553. return;
  19554. }
  19555. this._condition._currentResult = true;
  19556. }
  19557. }
  19558. this._nextActiveAction.execute(evt);
  19559. if (this._nextActiveAction._child) {
  19560. if (!this._nextActiveAction._child._actionManager) {
  19561. this._nextActiveAction._child._actionManager = this._actionManager;
  19562. }
  19563. this._nextActiveAction = this._nextActiveAction._child;
  19564. } else {
  19565. this._nextActiveAction = this;
  19566. }
  19567. };
  19568. Action.prototype.execute = function (evt) {
  19569. };
  19570. Action.prototype.then = function (action) {
  19571. this._child = action;
  19572. action._actionManager = this._actionManager;
  19573. action._prepare();
  19574. return action;
  19575. };
  19576. Action.prototype._getProperty = function (propertyPath) {
  19577. return this._actionManager._getProperty(propertyPath);
  19578. };
  19579. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  19580. return this._actionManager._getEffectiveTarget(target, propertyPath);
  19581. };
  19582. return Action;
  19583. })();
  19584. BABYLON.Action = Action;
  19585. })(BABYLON || (BABYLON = {}));
  19586. var BABYLON;
  19587. (function (BABYLON) {
  19588. var ActionEvent = (function () {
  19589. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  19590. this.source = source;
  19591. this.pointerX = pointerX;
  19592. this.pointerY = pointerY;
  19593. this.meshUnderPointer = meshUnderPointer;
  19594. this.sourceEvent = sourceEvent;
  19595. }
  19596. ActionEvent.CreateNew = function (source) {
  19597. var scene = source.getScene();
  19598. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer);
  19599. };
  19600. ActionEvent.CreateNewFromScene = function (scene, evt) {
  19601. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  19602. };
  19603. return ActionEvent;
  19604. })();
  19605. BABYLON.ActionEvent = ActionEvent;
  19606. var ActionManager = (function () {
  19607. function ActionManager(scene) {
  19608. this.actions = new Array();
  19609. this._scene = scene;
  19610. scene._actionManagers.push(this);
  19611. }
  19612. Object.defineProperty(ActionManager, "NothingTrigger", {
  19613. get: function () {
  19614. return ActionManager._NothingTrigger;
  19615. },
  19616. enumerable: true,
  19617. configurable: true
  19618. });
  19619. Object.defineProperty(ActionManager, "OnPickTrigger", {
  19620. get: function () {
  19621. return ActionManager._OnPickTrigger;
  19622. },
  19623. enumerable: true,
  19624. configurable: true
  19625. });
  19626. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  19627. get: function () {
  19628. return ActionManager._OnLeftPickTrigger;
  19629. },
  19630. enumerable: true,
  19631. configurable: true
  19632. });
  19633. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  19634. get: function () {
  19635. return ActionManager._OnRightPickTrigger;
  19636. },
  19637. enumerable: true,
  19638. configurable: true
  19639. });
  19640. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  19641. get: function () {
  19642. return ActionManager._OnCenterPickTrigger;
  19643. },
  19644. enumerable: true,
  19645. configurable: true
  19646. });
  19647. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  19648. get: function () {
  19649. return ActionManager._OnPointerOverTrigger;
  19650. },
  19651. enumerable: true,
  19652. configurable: true
  19653. });
  19654. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  19655. get: function () {
  19656. return ActionManager._OnPointerOutTrigger;
  19657. },
  19658. enumerable: true,
  19659. configurable: true
  19660. });
  19661. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  19662. get: function () {
  19663. return ActionManager._OnEveryFrameTrigger;
  19664. },
  19665. enumerable: true,
  19666. configurable: true
  19667. });
  19668. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  19669. get: function () {
  19670. return ActionManager._OnIntersectionEnterTrigger;
  19671. },
  19672. enumerable: true,
  19673. configurable: true
  19674. });
  19675. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  19676. get: function () {
  19677. return ActionManager._OnIntersectionExitTrigger;
  19678. },
  19679. enumerable: true,
  19680. configurable: true
  19681. });
  19682. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  19683. get: function () {
  19684. return ActionManager._OnKeyDownTrigger;
  19685. },
  19686. enumerable: true,
  19687. configurable: true
  19688. });
  19689. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  19690. get: function () {
  19691. return ActionManager._OnKeyUpTrigger;
  19692. },
  19693. enumerable: true,
  19694. configurable: true
  19695. });
  19696. ActionManager.prototype.dispose = function () {
  19697. var index = this._scene._actionManagers.indexOf(this);
  19698. if (index > -1) {
  19699. this._scene._actionManagers.splice(index, 1);
  19700. }
  19701. };
  19702. ActionManager.prototype.getScene = function () {
  19703. return this._scene;
  19704. };
  19705. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  19706. for (var index = 0; index < this.actions.length; index++) {
  19707. var action = this.actions[index];
  19708. if (triggers.indexOf(action.trigger) > -1) {
  19709. return true;
  19710. }
  19711. }
  19712. return false;
  19713. };
  19714. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  19715. get: function () {
  19716. for (var index = 0; index < this.actions.length; index++) {
  19717. var action = this.actions[index];
  19718. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  19719. return true;
  19720. }
  19721. }
  19722. return false;
  19723. },
  19724. enumerable: true,
  19725. configurable: true
  19726. });
  19727. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  19728. get: function () {
  19729. for (var index = 0; index < this.actions.length; index++) {
  19730. var action = this.actions[index];
  19731. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  19732. return true;
  19733. }
  19734. }
  19735. return false;
  19736. },
  19737. enumerable: true,
  19738. configurable: true
  19739. });
  19740. ActionManager.prototype.registerAction = function (action) {
  19741. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  19742. if (this.getScene().actionManager !== this) {
  19743. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  19744. return null;
  19745. }
  19746. }
  19747. this.actions.push(action);
  19748. action._actionManager = this;
  19749. action._prepare();
  19750. return action;
  19751. };
  19752. ActionManager.prototype.processTrigger = function (trigger, evt) {
  19753. for (var index = 0; index < this.actions.length; index++) {
  19754. var action = this.actions[index];
  19755. if (action.trigger === trigger) {
  19756. if (trigger == ActionManager.OnKeyUpTrigger || trigger == ActionManager.OnKeyDownTrigger) {
  19757. var parameter = action.getTriggerParameter();
  19758. if (parameter) {
  19759. if (evt.sourceEvent.key !== parameter) {
  19760. continue;
  19761. }
  19762. }
  19763. }
  19764. action._executeCurrent(evt);
  19765. }
  19766. }
  19767. };
  19768. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  19769. var properties = propertyPath.split(".");
  19770. for (var index = 0; index < properties.length - 1; index++) {
  19771. target = target[properties[index]];
  19772. }
  19773. return target;
  19774. };
  19775. ActionManager.prototype._getProperty = function (propertyPath) {
  19776. var properties = propertyPath.split(".");
  19777. return properties[properties.length - 1];
  19778. };
  19779. ActionManager._NothingTrigger = 0;
  19780. ActionManager._OnPickTrigger = 1;
  19781. ActionManager._OnLeftPickTrigger = 2;
  19782. ActionManager._OnRightPickTrigger = 3;
  19783. ActionManager._OnCenterPickTrigger = 4;
  19784. ActionManager._OnPointerOverTrigger = 5;
  19785. ActionManager._OnPointerOutTrigger = 6;
  19786. ActionManager._OnEveryFrameTrigger = 7;
  19787. ActionManager._OnIntersectionEnterTrigger = 8;
  19788. ActionManager._OnIntersectionExitTrigger = 9;
  19789. ActionManager._OnKeyDownTrigger = 10;
  19790. ActionManager._OnKeyUpTrigger = 11;
  19791. return ActionManager;
  19792. })();
  19793. BABYLON.ActionManager = ActionManager;
  19794. })(BABYLON || (BABYLON = {}));
  19795. var __extends = this.__extends || function (d, b) {
  19796. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19797. function __() { this.constructor = d; }
  19798. __.prototype = b.prototype;
  19799. d.prototype = new __();
  19800. };
  19801. var BABYLON;
  19802. (function (BABYLON) {
  19803. var InterpolateValueAction = (function (_super) {
  19804. __extends(InterpolateValueAction, _super);
  19805. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  19806. if (typeof duration === "undefined") { duration = 1000; }
  19807. _super.call(this, triggerOptions, condition);
  19808. this.propertyPath = propertyPath;
  19809. this.value = value;
  19810. this.duration = duration;
  19811. this.stopOtherAnimations = stopOtherAnimations;
  19812. this._target = target;
  19813. }
  19814. InterpolateValueAction.prototype._prepare = function () {
  19815. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19816. this._property = this._getProperty(this.propertyPath);
  19817. };
  19818. InterpolateValueAction.prototype.execute = function () {
  19819. var scene = this._actionManager.getScene();
  19820. var keys = [
  19821. {
  19822. frame: 0,
  19823. value: this._target[this._property]
  19824. }, {
  19825. frame: 100,
  19826. value: this.value
  19827. }
  19828. ];
  19829. var dataType;
  19830. if (typeof this.value === "number") {
  19831. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  19832. } else if (this.value instanceof BABYLON.Color3) {
  19833. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  19834. } else if (this.value instanceof BABYLON.Vector3) {
  19835. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  19836. } else if (this.value instanceof BABYLON.Matrix) {
  19837. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  19838. } else if (this.value instanceof BABYLON.Quaternion) {
  19839. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  19840. } else {
  19841. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  19842. return;
  19843. }
  19844. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  19845. animation.setKeys(keys);
  19846. if (this.stopOtherAnimations) {
  19847. scene.stopAnimation(this._target);
  19848. }
  19849. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  19850. };
  19851. return InterpolateValueAction;
  19852. })(BABYLON.Action);
  19853. BABYLON.InterpolateValueAction = InterpolateValueAction;
  19854. })(BABYLON || (BABYLON = {}));
  19855. var __extends = this.__extends || function (d, b) {
  19856. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19857. function __() { this.constructor = d; }
  19858. __.prototype = b.prototype;
  19859. d.prototype = new __();
  19860. };
  19861. var BABYLON;
  19862. (function (BABYLON) {
  19863. var SwitchBooleanAction = (function (_super) {
  19864. __extends(SwitchBooleanAction, _super);
  19865. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  19866. _super.call(this, triggerOptions, condition);
  19867. this.propertyPath = propertyPath;
  19868. this._target = target;
  19869. }
  19870. SwitchBooleanAction.prototype._prepare = function () {
  19871. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19872. this._property = this._getProperty(this.propertyPath);
  19873. };
  19874. SwitchBooleanAction.prototype.execute = function () {
  19875. this._target[this._property] = !this._target[this._property];
  19876. };
  19877. return SwitchBooleanAction;
  19878. })(BABYLON.Action);
  19879. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  19880. var SetStateAction = (function (_super) {
  19881. __extends(SetStateAction, _super);
  19882. function SetStateAction(triggerOptions, target, value, condition) {
  19883. _super.call(this, triggerOptions, condition);
  19884. this.value = value;
  19885. this._target = target;
  19886. }
  19887. SetStateAction.prototype.execute = function () {
  19888. this._target.state = this.value;
  19889. };
  19890. return SetStateAction;
  19891. })(BABYLON.Action);
  19892. BABYLON.SetStateAction = SetStateAction;
  19893. var SetValueAction = (function (_super) {
  19894. __extends(SetValueAction, _super);
  19895. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  19896. _super.call(this, triggerOptions, condition);
  19897. this.propertyPath = propertyPath;
  19898. this.value = value;
  19899. this._target = target;
  19900. }
  19901. SetValueAction.prototype._prepare = function () {
  19902. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19903. this._property = this._getProperty(this.propertyPath);
  19904. };
  19905. SetValueAction.prototype.execute = function () {
  19906. this._target[this._property] = this.value;
  19907. };
  19908. return SetValueAction;
  19909. })(BABYLON.Action);
  19910. BABYLON.SetValueAction = SetValueAction;
  19911. var IncrementValueAction = (function (_super) {
  19912. __extends(IncrementValueAction, _super);
  19913. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  19914. _super.call(this, triggerOptions, condition);
  19915. this.propertyPath = propertyPath;
  19916. this.value = value;
  19917. this._target = target;
  19918. }
  19919. IncrementValueAction.prototype._prepare = function () {
  19920. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19921. this._property = this._getProperty(this.propertyPath);
  19922. if (typeof this._target[this._property] !== "number") {
  19923. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  19924. }
  19925. };
  19926. IncrementValueAction.prototype.execute = function () {
  19927. this._target[this._property] += this.value;
  19928. };
  19929. return IncrementValueAction;
  19930. })(BABYLON.Action);
  19931. BABYLON.IncrementValueAction = IncrementValueAction;
  19932. var PlayAnimationAction = (function (_super) {
  19933. __extends(PlayAnimationAction, _super);
  19934. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  19935. _super.call(this, triggerOptions, condition);
  19936. this.from = from;
  19937. this.to = to;
  19938. this.loop = loop;
  19939. this._target = target;
  19940. }
  19941. PlayAnimationAction.prototype._prepare = function () {
  19942. };
  19943. PlayAnimationAction.prototype.execute = function () {
  19944. var scene = this._actionManager.getScene();
  19945. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  19946. };
  19947. return PlayAnimationAction;
  19948. })(BABYLON.Action);
  19949. BABYLON.PlayAnimationAction = PlayAnimationAction;
  19950. var StopAnimationAction = (function (_super) {
  19951. __extends(StopAnimationAction, _super);
  19952. function StopAnimationAction(triggerOptions, target, condition) {
  19953. _super.call(this, triggerOptions, condition);
  19954. this._target = target;
  19955. }
  19956. StopAnimationAction.prototype._prepare = function () {
  19957. };
  19958. StopAnimationAction.prototype.execute = function () {
  19959. var scene = this._actionManager.getScene();
  19960. scene.stopAnimation(this._target);
  19961. };
  19962. return StopAnimationAction;
  19963. })(BABYLON.Action);
  19964. BABYLON.StopAnimationAction = StopAnimationAction;
  19965. var DoNothingAction = (function (_super) {
  19966. __extends(DoNothingAction, _super);
  19967. function DoNothingAction(triggerOptions, condition) {
  19968. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  19969. _super.call(this, triggerOptions, condition);
  19970. }
  19971. DoNothingAction.prototype.execute = function () {
  19972. };
  19973. return DoNothingAction;
  19974. })(BABYLON.Action);
  19975. BABYLON.DoNothingAction = DoNothingAction;
  19976. var CombineAction = (function (_super) {
  19977. __extends(CombineAction, _super);
  19978. function CombineAction(triggerOptions, children, condition) {
  19979. _super.call(this, triggerOptions, condition);
  19980. this.children = children;
  19981. }
  19982. CombineAction.prototype._prepare = function () {
  19983. for (var index = 0; index < this.children.length; index++) {
  19984. this.children[index]._actionManager = this._actionManager;
  19985. this.children[index]._prepare();
  19986. }
  19987. };
  19988. CombineAction.prototype.execute = function (evt) {
  19989. for (var index = 0; index < this.children.length; index++) {
  19990. this.children[index].execute(evt);
  19991. }
  19992. };
  19993. return CombineAction;
  19994. })(BABYLON.Action);
  19995. BABYLON.CombineAction = CombineAction;
  19996. var ExecuteCodeAction = (function (_super) {
  19997. __extends(ExecuteCodeAction, _super);
  19998. function ExecuteCodeAction(triggerOptions, func, condition) {
  19999. _super.call(this, triggerOptions, condition);
  20000. this.func = func;
  20001. }
  20002. ExecuteCodeAction.prototype.execute = function (evt) {
  20003. this.func(evt);
  20004. };
  20005. return ExecuteCodeAction;
  20006. })(BABYLON.Action);
  20007. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  20008. var SetParentAction = (function (_super) {
  20009. __extends(SetParentAction, _super);
  20010. function SetParentAction(triggerOptions, target, parent, condition) {
  20011. _super.call(this, triggerOptions, condition);
  20012. this._target = target;
  20013. this._parent = parent;
  20014. }
  20015. SetParentAction.prototype._prepare = function () {
  20016. };
  20017. SetParentAction.prototype.execute = function () {
  20018. if (this._target.parent === this._parent) {
  20019. return;
  20020. }
  20021. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  20022. invertParentWorldMatrix.invert();
  20023. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  20024. this._target.parent = this._parent;
  20025. };
  20026. return SetParentAction;
  20027. })(BABYLON.Action);
  20028. BABYLON.SetParentAction = SetParentAction;
  20029. })(BABYLON || (BABYLON = {}));
  20030. var __extends = this.__extends || function (d, b) {
  20031. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20032. function __() { this.constructor = d; }
  20033. __.prototype = b.prototype;
  20034. d.prototype = new __();
  20035. };
  20036. var BABYLON;
  20037. (function (BABYLON) {
  20038. var Geometry = (function () {
  20039. function Geometry(id, scene, vertexData, updatable, mesh) {
  20040. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20041. this._totalVertices = 0;
  20042. this._indices = [];
  20043. this.id = id;
  20044. this._engine = scene.getEngine();
  20045. this._meshes = [];
  20046. this._scene = scene;
  20047. if (vertexData) {
  20048. this.setAllVerticesData(vertexData, updatable);
  20049. } else {
  20050. this._totalVertices = 0;
  20051. this._indices = [];
  20052. }
  20053. if (mesh) {
  20054. this.applyToMesh(mesh);
  20055. }
  20056. }
  20057. Geometry.prototype.getScene = function () {
  20058. return this._scene;
  20059. };
  20060. Geometry.prototype.getEngine = function () {
  20061. return this._engine;
  20062. };
  20063. Geometry.prototype.isReady = function () {
  20064. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  20065. };
  20066. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  20067. vertexData.applyToGeometry(this, updatable);
  20068. };
  20069. Geometry.prototype.setVerticesData = function (kind, data, updatable) {
  20070. this._vertexBuffers = this._vertexBuffers || {};
  20071. if (this._vertexBuffers[kind]) {
  20072. this._vertexBuffers[kind].dispose();
  20073. }
  20074. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0);
  20075. if (kind === BABYLON.VertexBuffer.PositionKind) {
  20076. var stride = this._vertexBuffers[kind].getStrideSize();
  20077. this._totalVertices = data.length / stride;
  20078. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  20079. var meshes = this._meshes;
  20080. var numOfMeshes = meshes.length;
  20081. for (var index = 0; index < numOfMeshes; index++) {
  20082. var mesh = meshes[index];
  20083. mesh._resetPointsArrayCache();
  20084. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20085. mesh._createGlobalSubMesh();
  20086. mesh.computeWorldMatrix(true);
  20087. }
  20088. }
  20089. };
  20090. Geometry.prototype.updateVerticesDataDirectly = function (kind, data) {
  20091. var vertexBuffer = this.getVertexBuffer(kind);
  20092. if (!vertexBuffer) {
  20093. return;
  20094. }
  20095. vertexBuffer.updateDirectly(data);
  20096. };
  20097. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  20098. var vertexBuffer = this.getVertexBuffer(kind);
  20099. if (!vertexBuffer) {
  20100. return;
  20101. }
  20102. vertexBuffer.update(data);
  20103. if (kind === BABYLON.VertexBuffer.PositionKind) {
  20104. var extend;
  20105. if (updateExtends) {
  20106. var stride = vertexBuffer.getStrideSize();
  20107. this._totalVertices = data.length / stride;
  20108. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  20109. }
  20110. var meshes = this._meshes;
  20111. var numOfMeshes = meshes.length;
  20112. for (var index = 0; index < numOfMeshes; index++) {
  20113. var mesh = meshes[index];
  20114. mesh._resetPointsArrayCache();
  20115. if (updateExtends) {
  20116. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20117. }
  20118. }
  20119. }
  20120. };
  20121. Geometry.prototype.getTotalVertices = function () {
  20122. if (!this.isReady()) {
  20123. return 0;
  20124. }
  20125. return this._totalVertices;
  20126. };
  20127. Geometry.prototype.getVerticesData = function (kind) {
  20128. var vertexBuffer = this.getVertexBuffer(kind);
  20129. if (!vertexBuffer) {
  20130. return null;
  20131. }
  20132. return vertexBuffer.getData();
  20133. };
  20134. Geometry.prototype.getVertexBuffer = function (kind) {
  20135. if (!this.isReady()) {
  20136. return null;
  20137. }
  20138. return this._vertexBuffers[kind];
  20139. };
  20140. Geometry.prototype.getVertexBuffers = function () {
  20141. if (!this.isReady()) {
  20142. return null;
  20143. }
  20144. return this._vertexBuffers;
  20145. };
  20146. Geometry.prototype.isVerticesDataPresent = function (kind) {
  20147. if (!this._vertexBuffers) {
  20148. if (this._delayInfo) {
  20149. return this._delayInfo.indexOf(kind) !== -1;
  20150. }
  20151. return false;
  20152. }
  20153. return this._vertexBuffers[kind] !== undefined;
  20154. };
  20155. Geometry.prototype.getVerticesDataKinds = function () {
  20156. var result = [];
  20157. if (!this._vertexBuffers && this._delayInfo) {
  20158. for (var kind in this._delayInfo) {
  20159. result.push(kind);
  20160. }
  20161. } else {
  20162. for (kind in this._vertexBuffers) {
  20163. result.push(kind);
  20164. }
  20165. }
  20166. return result;
  20167. };
  20168. Geometry.prototype.setIndices = function (indices) {
  20169. if (this._indexBuffer) {
  20170. this._engine._releaseBuffer(this._indexBuffer);
  20171. }
  20172. this._indices = indices;
  20173. if (this._meshes.length !== 0 && this._indices) {
  20174. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  20175. }
  20176. var meshes = this._meshes;
  20177. var numOfMeshes = meshes.length;
  20178. for (var index = 0; index < numOfMeshes; index++) {
  20179. meshes[index]._createGlobalSubMesh();
  20180. }
  20181. };
  20182. Geometry.prototype.getTotalIndices = function () {
  20183. if (!this.isReady()) {
  20184. return 0;
  20185. }
  20186. return this._indices.length;
  20187. };
  20188. Geometry.prototype.getIndices = function () {
  20189. if (!this.isReady()) {
  20190. return null;
  20191. }
  20192. return this._indices;
  20193. };
  20194. Geometry.prototype.getIndexBuffer = function () {
  20195. if (!this.isReady()) {
  20196. return null;
  20197. }
  20198. return this._indexBuffer;
  20199. };
  20200. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  20201. var meshes = this._meshes;
  20202. var index = meshes.indexOf(mesh);
  20203. if (index === -1) {
  20204. return;
  20205. }
  20206. for (var kind in this._vertexBuffers) {
  20207. this._vertexBuffers[kind].dispose();
  20208. }
  20209. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  20210. this._indexBuffer = null;
  20211. }
  20212. meshes.splice(index, 1);
  20213. mesh._geometry = null;
  20214. if (meshes.length == 0 && shouldDispose) {
  20215. this.dispose();
  20216. }
  20217. };
  20218. Geometry.prototype.applyToMesh = function (mesh) {
  20219. if (mesh._geometry === this) {
  20220. return;
  20221. }
  20222. var previousGeometry = mesh._geometry;
  20223. if (previousGeometry) {
  20224. previousGeometry.releaseForMesh(mesh);
  20225. }
  20226. var meshes = this._meshes;
  20227. mesh._geometry = this;
  20228. this._scene.pushGeometry(this);
  20229. meshes.push(mesh);
  20230. if (this.isReady()) {
  20231. this._applyToMesh(mesh);
  20232. } else {
  20233. mesh._boundingInfo = this._boundingInfo;
  20234. }
  20235. };
  20236. Geometry.prototype._applyToMesh = function (mesh) {
  20237. var numOfMeshes = this._meshes.length;
  20238. for (var kind in this._vertexBuffers) {
  20239. if (numOfMeshes === 1) {
  20240. this._vertexBuffers[kind].create();
  20241. }
  20242. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  20243. if (kind === BABYLON.VertexBuffer.PositionKind) {
  20244. mesh._resetPointsArrayCache();
  20245. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  20246. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20247. mesh._createGlobalSubMesh();
  20248. }
  20249. }
  20250. if (numOfMeshes === 1 && this._indices) {
  20251. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  20252. }
  20253. if (this._indexBuffer) {
  20254. this._indexBuffer.references = numOfMeshes;
  20255. }
  20256. };
  20257. Geometry.prototype.load = function (scene, onLoaded) {
  20258. var _this = this;
  20259. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20260. return;
  20261. }
  20262. if (this.isReady()) {
  20263. if (onLoaded) {
  20264. onLoaded();
  20265. }
  20266. return;
  20267. }
  20268. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20269. scene._addPendingData(this);
  20270. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20271. _this._delayLoadingFunction(JSON.parse(data), _this);
  20272. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20273. _this._delayInfo = [];
  20274. scene._removePendingData(_this);
  20275. var meshes = _this._meshes;
  20276. var numOfMeshes = meshes.length;
  20277. for (var index = 0; index < numOfMeshes; index++) {
  20278. _this._applyToMesh(meshes[index]);
  20279. }
  20280. if (onLoaded) {
  20281. onLoaded();
  20282. }
  20283. }, function () {
  20284. }, scene.database);
  20285. };
  20286. Geometry.prototype.dispose = function () {
  20287. var meshes = this._meshes;
  20288. var numOfMeshes = meshes.length;
  20289. for (var index = 0; index < numOfMeshes; index++) {
  20290. this.releaseForMesh(meshes[index]);
  20291. }
  20292. this._meshes = [];
  20293. for (var kind in this._vertexBuffers) {
  20294. this._vertexBuffers[kind].dispose();
  20295. }
  20296. this._vertexBuffers = [];
  20297. this._totalVertices = 0;
  20298. if (this._indexBuffer) {
  20299. this._engine._releaseBuffer(this._indexBuffer);
  20300. }
  20301. this._indexBuffer = null;
  20302. this._indices = [];
  20303. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20304. this.delayLoadingFile = null;
  20305. this._delayLoadingFunction = null;
  20306. this._delayInfo = [];
  20307. this._boundingInfo = null;
  20308. var geometries = this._scene.getGeometries();
  20309. index = geometries.indexOf(this);
  20310. if (index > -1) {
  20311. geometries.splice(index, 1);
  20312. }
  20313. };
  20314. Geometry.prototype.copy = function (id) {
  20315. var vertexData = new BABYLON.VertexData();
  20316. vertexData.indices = [];
  20317. var indices = this.getIndices();
  20318. for (var index = 0; index < indices.length; index++) {
  20319. vertexData.indices.push(indices[index]);
  20320. }
  20321. var updatable = false;
  20322. var stopChecking = false;
  20323. for (var kind in this._vertexBuffers) {
  20324. vertexData.set(this.getVerticesData(kind), kind);
  20325. if (!stopChecking) {
  20326. updatable = this.getVertexBuffer(kind).isUpdatable();
  20327. stopChecking = !updatable;
  20328. }
  20329. }
  20330. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  20331. geometry.delayLoadState = this.delayLoadState;
  20332. geometry.delayLoadingFile = this.delayLoadingFile;
  20333. geometry._delayLoadingFunction = this._delayLoadingFunction;
  20334. for (kind in this._delayInfo) {
  20335. geometry._delayInfo = geometry._delayInfo || [];
  20336. geometry._delayInfo.push(kind);
  20337. }
  20338. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  20339. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20340. return geometry;
  20341. };
  20342. Geometry.ExtractFromMesh = function (mesh, id) {
  20343. var geometry = mesh._geometry;
  20344. if (!geometry) {
  20345. return null;
  20346. }
  20347. return geometry.copy(id);
  20348. };
  20349. Geometry.RandomId = function () {
  20350. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  20351. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  20352. return v.toString(16);
  20353. });
  20354. };
  20355. return Geometry;
  20356. })();
  20357. BABYLON.Geometry = Geometry;
  20358. (function (Geometry) {
  20359. (function (Primitives) {
  20360. var _Primitive = (function (_super) {
  20361. __extends(_Primitive, _super);
  20362. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  20363. this._beingRegenerated = true;
  20364. this._canBeRegenerated = canBeRegenerated;
  20365. _super.call(this, id, scene, vertexData, false, mesh);
  20366. this._beingRegenerated = false;
  20367. }
  20368. _Primitive.prototype.canBeRegenerated = function () {
  20369. return this._canBeRegenerated;
  20370. };
  20371. _Primitive.prototype.regenerate = function () {
  20372. if (!this._canBeRegenerated) {
  20373. return;
  20374. }
  20375. this._beingRegenerated = true;
  20376. this.setAllVerticesData(this._regenerateVertexData(), false);
  20377. this._beingRegenerated = false;
  20378. };
  20379. _Primitive.prototype.asNewGeometry = function (id) {
  20380. return _super.prototype.copy.call(this, id);
  20381. };
  20382. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  20383. if (!this._beingRegenerated) {
  20384. return;
  20385. }
  20386. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  20387. };
  20388. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  20389. if (!this._beingRegenerated) {
  20390. return;
  20391. }
  20392. _super.prototype.setVerticesData.call(this, kind, data, false);
  20393. };
  20394. _Primitive.prototype._regenerateVertexData = function () {
  20395. throw new Error("Abstract method");
  20396. };
  20397. _Primitive.prototype.copy = function (id) {
  20398. throw new Error("Must be overriden in sub-classes.");
  20399. };
  20400. return _Primitive;
  20401. })(Geometry);
  20402. Primitives._Primitive = _Primitive;
  20403. var Box = (function (_super) {
  20404. __extends(Box, _super);
  20405. function Box(id, scene, size, canBeRegenerated, mesh) {
  20406. this.size = size;
  20407. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20408. }
  20409. Box.prototype._regenerateVertexData = function () {
  20410. return BABYLON.VertexData.CreateBox(this.size);
  20411. };
  20412. Box.prototype.copy = function (id) {
  20413. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  20414. };
  20415. return Box;
  20416. })(_Primitive);
  20417. Primitives.Box = Box;
  20418. var Sphere = (function (_super) {
  20419. __extends(Sphere, _super);
  20420. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  20421. this.segments = segments;
  20422. this.diameter = diameter;
  20423. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20424. }
  20425. Sphere.prototype._regenerateVertexData = function () {
  20426. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  20427. };
  20428. Sphere.prototype.copy = function (id) {
  20429. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  20430. };
  20431. return Sphere;
  20432. })(_Primitive);
  20433. Primitives.Sphere = Sphere;
  20434. var Cylinder = (function (_super) {
  20435. __extends(Cylinder, _super);
  20436. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  20437. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  20438. this.height = height;
  20439. this.diameterTop = diameterTop;
  20440. this.diameterBottom = diameterBottom;
  20441. this.tessellation = tessellation;
  20442. this.subdivisions = subdivisions;
  20443. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20444. }
  20445. Cylinder.prototype._regenerateVertexData = function () {
  20446. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  20447. };
  20448. Cylinder.prototype.copy = function (id) {
  20449. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  20450. };
  20451. return Cylinder;
  20452. })(_Primitive);
  20453. Primitives.Cylinder = Cylinder;
  20454. var Torus = (function (_super) {
  20455. __extends(Torus, _super);
  20456. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  20457. this.diameter = diameter;
  20458. this.thickness = thickness;
  20459. this.tessellation = tessellation;
  20460. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20461. }
  20462. Torus.prototype._regenerateVertexData = function () {
  20463. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  20464. };
  20465. Torus.prototype.copy = function (id) {
  20466. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  20467. };
  20468. return Torus;
  20469. })(_Primitive);
  20470. Primitives.Torus = Torus;
  20471. var Ground = (function (_super) {
  20472. __extends(Ground, _super);
  20473. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  20474. this.width = width;
  20475. this.height = height;
  20476. this.subdivisions = subdivisions;
  20477. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20478. }
  20479. Ground.prototype._regenerateVertexData = function () {
  20480. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  20481. };
  20482. Ground.prototype.copy = function (id) {
  20483. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  20484. };
  20485. return Ground;
  20486. })(_Primitive);
  20487. Primitives.Ground = Ground;
  20488. var TiledGround = (function (_super) {
  20489. __extends(TiledGround, _super);
  20490. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  20491. this.xmin = xmin;
  20492. this.zmin = zmin;
  20493. this.xmax = xmax;
  20494. this.zmax = zmax;
  20495. this.subdivisions = subdivisions;
  20496. this.precision = precision;
  20497. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20498. }
  20499. TiledGround.prototype._regenerateVertexData = function () {
  20500. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  20501. };
  20502. TiledGround.prototype.copy = function (id) {
  20503. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  20504. };
  20505. return TiledGround;
  20506. })(_Primitive);
  20507. Primitives.TiledGround = TiledGround;
  20508. var Plane = (function (_super) {
  20509. __extends(Plane, _super);
  20510. function Plane(id, scene, size, canBeRegenerated, mesh) {
  20511. this.size = size;
  20512. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20513. }
  20514. Plane.prototype._regenerateVertexData = function () {
  20515. return BABYLON.VertexData.CreatePlane(this.size);
  20516. };
  20517. Plane.prototype.copy = function (id) {
  20518. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  20519. };
  20520. return Plane;
  20521. })(_Primitive);
  20522. Primitives.Plane = Plane;
  20523. var TorusKnot = (function (_super) {
  20524. __extends(TorusKnot, _super);
  20525. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  20526. this.radius = radius;
  20527. this.tube = tube;
  20528. this.radialSegments = radialSegments;
  20529. this.tubularSegments = tubularSegments;
  20530. this.p = p;
  20531. this.q = q;
  20532. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20533. }
  20534. TorusKnot.prototype._regenerateVertexData = function () {
  20535. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  20536. };
  20537. TorusKnot.prototype.copy = function (id) {
  20538. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  20539. };
  20540. return TorusKnot;
  20541. })(_Primitive);
  20542. Primitives.TorusKnot = TorusKnot;
  20543. })(Geometry.Primitives || (Geometry.Primitives = {}));
  20544. var Primitives = Geometry.Primitives;
  20545. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  20546. var Geometry = BABYLON.Geometry;
  20547. })(BABYLON || (BABYLON = {}));
  20548. var __extends = this.__extends || function (d, b) {
  20549. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20550. function __() { this.constructor = d; }
  20551. __.prototype = b.prototype;
  20552. d.prototype = new __();
  20553. };
  20554. var BABYLON;
  20555. (function (BABYLON) {
  20556. var Gamepads = (function () {
  20557. function Gamepads(ongamedpadconnected) {
  20558. var _this = this;
  20559. this.babylonGamepads = [];
  20560. this.oneGamepadConnected = false;
  20561. this.isMonitoring = false;
  20562. this.gamepadEventSupported = 'GamepadEvent' in window;
  20563. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  20564. 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=";
  20565. this._callbackGamepadConnected = ongamedpadconnected;
  20566. if (this.gamepadSupportAvailable) {
  20567. if (this.gamepadEventSupported) {
  20568. window.addEventListener('gamepadconnected', function (evt) {
  20569. _this._onGamepadConnected(evt);
  20570. }, false);
  20571. window.addEventListener('gamepaddisconnected', function (evt) {
  20572. _this._onGamepadDisconnected(evt);
  20573. }, false);
  20574. } else {
  20575. this._startMonitoringGamepads();
  20576. }
  20577. if (!this.oneGamepadConnected) {
  20578. this._insertGamepadDOMInstructions();
  20579. }
  20580. } else {
  20581. this._insertGamepadDOMNotSupported();
  20582. }
  20583. }
  20584. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  20585. Gamepads.gamepadDOMInfo = document.createElement("div");
  20586. var buttonAImage = document.createElement("img");
  20587. buttonAImage.src = this.buttonADataURL;
  20588. var spanMessage = document.createElement("span");
  20589. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  20590. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  20591. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  20592. Gamepads.gamepadDOMInfo.style.position = "absolute";
  20593. Gamepads.gamepadDOMInfo.style.width = "100%";
  20594. Gamepads.gamepadDOMInfo.style.height = "48px";
  20595. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  20596. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  20597. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  20598. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  20599. buttonAImage.style.position = "relative";
  20600. buttonAImage.style.bottom = "8px";
  20601. spanMessage.style.position = "relative";
  20602. spanMessage.style.fontSize = "32px";
  20603. spanMessage.style.bottom = "32px";
  20604. spanMessage.style.color = "green";
  20605. document.body.appendChild(Gamepads.gamepadDOMInfo);
  20606. };
  20607. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  20608. Gamepads.gamepadDOMInfo = document.createElement("div");
  20609. var spanMessage = document.createElement("span");
  20610. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  20611. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  20612. Gamepads.gamepadDOMInfo.style.position = "absolute";
  20613. Gamepads.gamepadDOMInfo.style.width = "100%";
  20614. Gamepads.gamepadDOMInfo.style.height = "40px";
  20615. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  20616. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  20617. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  20618. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  20619. spanMessage.style.position = "relative";
  20620. spanMessage.style.fontSize = "32px";
  20621. spanMessage.style.color = "red";
  20622. document.body.appendChild(Gamepads.gamepadDOMInfo);
  20623. };
  20624. Gamepads.prototype.dispose = function () {
  20625. document.body.removeChild(Gamepads.gamepadDOMInfo);
  20626. };
  20627. Gamepads.prototype._onGamepadConnected = function (evt) {
  20628. var newGamepad = this._addNewGamepad(evt.gamepad);
  20629. if (this._callbackGamepadConnected)
  20630. this._callbackGamepadConnected(newGamepad);
  20631. this._startMonitoringGamepads();
  20632. };
  20633. Gamepads.prototype._addNewGamepad = function (gamepad) {
  20634. if (!this.oneGamepadConnected) {
  20635. this.oneGamepadConnected = true;
  20636. if (Gamepads.gamepadDOMInfo) {
  20637. document.body.removeChild(Gamepads.gamepadDOMInfo);
  20638. Gamepads.gamepadDOMInfo = null;
  20639. }
  20640. }
  20641. var newGamepad;
  20642. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  20643. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  20644. } else {
  20645. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  20646. }
  20647. this.babylonGamepads.push(newGamepad);
  20648. return newGamepad;
  20649. };
  20650. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  20651. for (var i in this.babylonGamepads) {
  20652. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  20653. this.babylonGamepads.splice(i, 1);
  20654. break;
  20655. }
  20656. }
  20657. if (this.babylonGamepads.length == 0) {
  20658. this._stopMonitoringGamepads();
  20659. }
  20660. };
  20661. Gamepads.prototype._startMonitoringGamepads = function () {
  20662. if (!this.isMonitoring) {
  20663. this.isMonitoring = true;
  20664. this._checkGamepadsStatus();
  20665. }
  20666. };
  20667. Gamepads.prototype._stopMonitoringGamepads = function () {
  20668. this.isMonitoring = false;
  20669. };
  20670. Gamepads.prototype._checkGamepadsStatus = function () {
  20671. var _this = this;
  20672. this._updateGamepadObjects();
  20673. for (var i in this.babylonGamepads) {
  20674. this.babylonGamepads[i].update();
  20675. }
  20676. if (this.isMonitoring) {
  20677. if (window.requestAnimationFrame) {
  20678. window.requestAnimationFrame(function () {
  20679. _this._checkGamepadsStatus();
  20680. });
  20681. } else if (window.mozRequestAnimationFrame) {
  20682. window.mozRequestAnimationFrame(function () {
  20683. _this._checkGamepadsStatus();
  20684. });
  20685. } else if (window.webkitRequestAnimationFrame) {
  20686. window.webkitRequestAnimationFrame(function () {
  20687. _this._checkGamepadsStatus();
  20688. });
  20689. }
  20690. }
  20691. };
  20692. Gamepads.prototype._updateGamepadObjects = function () {
  20693. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  20694. for (var i = 0; i < gamepads.length; i++) {
  20695. if (gamepads[i]) {
  20696. if (!(gamepads[i].index in this.babylonGamepads)) {
  20697. var newGamepad = this._addNewGamepad(gamepads[i]);
  20698. if (this._callbackGamepadConnected) {
  20699. this._callbackGamepadConnected(newGamepad);
  20700. }
  20701. } else {
  20702. this.babylonGamepads[i].browserGamepad = gamepads[i];
  20703. }
  20704. }
  20705. }
  20706. };
  20707. return Gamepads;
  20708. })();
  20709. BABYLON.Gamepads = Gamepads;
  20710. var StickValues = (function () {
  20711. function StickValues(x, y) {
  20712. this.x = x;
  20713. this.y = y;
  20714. }
  20715. return StickValues;
  20716. })();
  20717. BABYLON.StickValues = StickValues;
  20718. var Gamepad = (function () {
  20719. function Gamepad(id, index, browserGamepad) {
  20720. this.id = id;
  20721. this.index = index;
  20722. this.browserGamepad = browserGamepad;
  20723. if (this.browserGamepad.axes.length >= 2) {
  20724. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  20725. }
  20726. if (this.browserGamepad.axes.length >= 4) {
  20727. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  20728. }
  20729. }
  20730. Gamepad.prototype.onleftstickchanged = function (callback) {
  20731. this._onleftstickchanged = callback;
  20732. };
  20733. Gamepad.prototype.onrightstickchanged = function (callback) {
  20734. this._onrightstickchanged = callback;
  20735. };
  20736. Object.defineProperty(Gamepad.prototype, "leftStick", {
  20737. get: function () {
  20738. return this._leftStick;
  20739. },
  20740. set: function (newValues) {
  20741. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  20742. this._onleftstickchanged(newValues);
  20743. }
  20744. this._leftStick = newValues;
  20745. },
  20746. enumerable: true,
  20747. configurable: true
  20748. });
  20749. Object.defineProperty(Gamepad.prototype, "rightStick", {
  20750. get: function () {
  20751. return this._rightStick;
  20752. },
  20753. set: function (newValues) {
  20754. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  20755. this._onrightstickchanged(newValues);
  20756. }
  20757. this._rightStick = newValues;
  20758. },
  20759. enumerable: true,
  20760. configurable: true
  20761. });
  20762. Gamepad.prototype.update = function () {
  20763. if (this._leftStick) {
  20764. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  20765. }
  20766. if (this._rightStick) {
  20767. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  20768. }
  20769. };
  20770. return Gamepad;
  20771. })();
  20772. BABYLON.Gamepad = Gamepad;
  20773. var GenericPad = (function (_super) {
  20774. __extends(GenericPad, _super);
  20775. function GenericPad(id, index, gamepad) {
  20776. _super.call(this, id, index, gamepad);
  20777. this.id = id;
  20778. this.index = index;
  20779. this.gamepad = gamepad;
  20780. this._buttons = new Array(gamepad.buttons.length);
  20781. }
  20782. GenericPad.prototype.onbuttondown = function (callback) {
  20783. this._onbuttondown = callback;
  20784. };
  20785. GenericPad.prototype.onbuttonup = function (callback) {
  20786. this._onbuttonup = callback;
  20787. };
  20788. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  20789. if (newValue !== currentValue) {
  20790. if (this._onbuttondown && newValue === 1) {
  20791. this._onbuttondown(buttonIndex);
  20792. }
  20793. if (this._onbuttonup && newValue === 0) {
  20794. this._onbuttonup(buttonIndex);
  20795. }
  20796. }
  20797. return newValue;
  20798. };
  20799. GenericPad.prototype.update = function () {
  20800. _super.prototype.update.call(this);
  20801. for (var index = 0; index < this._buttons.length; index++) {
  20802. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  20803. }
  20804. };
  20805. return GenericPad;
  20806. })(Gamepad);
  20807. BABYLON.GenericPad = GenericPad;
  20808. (function (Xbox360Button) {
  20809. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  20810. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  20811. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  20812. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  20813. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  20814. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  20815. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  20816. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  20817. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  20818. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  20819. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  20820. var Xbox360Button = BABYLON.Xbox360Button;
  20821. (function (Xbox360Dpad) {
  20822. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  20823. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  20824. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  20825. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  20826. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  20827. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  20828. var Xbox360Pad = (function (_super) {
  20829. __extends(Xbox360Pad, _super);
  20830. function Xbox360Pad() {
  20831. _super.apply(this, arguments);
  20832. this._leftTrigger = 0;
  20833. this._rightTrigger = 0;
  20834. this._buttonA = 0;
  20835. this._buttonB = 0;
  20836. this._buttonX = 0;
  20837. this._buttonY = 0;
  20838. this._buttonBack = 0;
  20839. this._buttonStart = 0;
  20840. this._buttonLB = 0;
  20841. this._buttonRB = 0;
  20842. this._buttonLeftStick = 0;
  20843. this._buttonRightStick = 0;
  20844. this._dPadUp = 0;
  20845. this._dPadDown = 0;
  20846. this._dPadLeft = 0;
  20847. this._dPadRight = 0;
  20848. }
  20849. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  20850. this._onlefttriggerchanged = callback;
  20851. };
  20852. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  20853. this._onrighttriggerchanged = callback;
  20854. };
  20855. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  20856. get: function () {
  20857. return this._leftTrigger;
  20858. },
  20859. set: function (newValue) {
  20860. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  20861. this._onlefttriggerchanged(newValue);
  20862. }
  20863. this._leftTrigger = newValue;
  20864. },
  20865. enumerable: true,
  20866. configurable: true
  20867. });
  20868. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  20869. get: function () {
  20870. return this._rightTrigger;
  20871. },
  20872. set: function (newValue) {
  20873. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  20874. this._onrighttriggerchanged(newValue);
  20875. }
  20876. this._rightTrigger = newValue;
  20877. },
  20878. enumerable: true,
  20879. configurable: true
  20880. });
  20881. Xbox360Pad.prototype.onbuttondown = function (callback) {
  20882. this._onbuttondown = callback;
  20883. };
  20884. Xbox360Pad.prototype.onbuttonup = function (callback) {
  20885. this._onbuttonup = callback;
  20886. };
  20887. Xbox360Pad.prototype.ondpaddown = function (callback) {
  20888. this._ondpaddown = callback;
  20889. };
  20890. Xbox360Pad.prototype.ondpadup = function (callback) {
  20891. this._ondpadup = callback;
  20892. };
  20893. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  20894. if (newValue !== currentValue) {
  20895. if (this._onbuttondown && newValue === 1) {
  20896. this._onbuttondown(buttonType);
  20897. }
  20898. if (this._onbuttonup && newValue === 0) {
  20899. this._onbuttonup(buttonType);
  20900. }
  20901. }
  20902. return newValue;
  20903. };
  20904. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  20905. if (newValue !== currentValue) {
  20906. if (this._ondpaddown && newValue === 1) {
  20907. this._ondpaddown(buttonType);
  20908. }
  20909. if (this._ondpadup && newValue === 0) {
  20910. this._ondpadup(buttonType);
  20911. }
  20912. }
  20913. return newValue;
  20914. };
  20915. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  20916. get: function () {
  20917. return this._buttonA;
  20918. },
  20919. set: function (value) {
  20920. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  20921. },
  20922. enumerable: true,
  20923. configurable: true
  20924. });
  20925. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  20926. get: function () {
  20927. return this._buttonB;
  20928. },
  20929. set: function (value) {
  20930. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  20931. },
  20932. enumerable: true,
  20933. configurable: true
  20934. });
  20935. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  20936. get: function () {
  20937. return this._buttonX;
  20938. },
  20939. set: function (value) {
  20940. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  20941. },
  20942. enumerable: true,
  20943. configurable: true
  20944. });
  20945. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  20946. get: function () {
  20947. return this._buttonY;
  20948. },
  20949. set: function (value) {
  20950. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  20951. },
  20952. enumerable: true,
  20953. configurable: true
  20954. });
  20955. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  20956. get: function () {
  20957. return this._buttonStart;
  20958. },
  20959. set: function (value) {
  20960. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  20961. },
  20962. enumerable: true,
  20963. configurable: true
  20964. });
  20965. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  20966. get: function () {
  20967. return this._buttonBack;
  20968. },
  20969. set: function (value) {
  20970. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  20971. },
  20972. enumerable: true,
  20973. configurable: true
  20974. });
  20975. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  20976. get: function () {
  20977. return this._buttonLB;
  20978. },
  20979. set: function (value) {
  20980. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  20981. },
  20982. enumerable: true,
  20983. configurable: true
  20984. });
  20985. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  20986. get: function () {
  20987. return this._buttonRB;
  20988. },
  20989. set: function (value) {
  20990. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  20991. },
  20992. enumerable: true,
  20993. configurable: true
  20994. });
  20995. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  20996. get: function () {
  20997. return this._buttonLeftStick;
  20998. },
  20999. set: function (value) {
  21000. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  21001. },
  21002. enumerable: true,
  21003. configurable: true
  21004. });
  21005. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  21006. get: function () {
  21007. return this._buttonRightStick;
  21008. },
  21009. set: function (value) {
  21010. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  21011. },
  21012. enumerable: true,
  21013. configurable: true
  21014. });
  21015. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  21016. get: function () {
  21017. return this._dPadUp;
  21018. },
  21019. set: function (value) {
  21020. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  21021. },
  21022. enumerable: true,
  21023. configurable: true
  21024. });
  21025. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  21026. get: function () {
  21027. return this._dPadDown;
  21028. },
  21029. set: function (value) {
  21030. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  21031. },
  21032. enumerable: true,
  21033. configurable: true
  21034. });
  21035. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  21036. get: function () {
  21037. return this._dPadLeft;
  21038. },
  21039. set: function (value) {
  21040. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  21041. },
  21042. enumerable: true,
  21043. configurable: true
  21044. });
  21045. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  21046. get: function () {
  21047. return this._dPadRight;
  21048. },
  21049. set: function (value) {
  21050. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  21051. },
  21052. enumerable: true,
  21053. configurable: true
  21054. });
  21055. Xbox360Pad.prototype.update = function () {
  21056. _super.prototype.update.call(this);
  21057. this.buttonA = this.browserGamepad.buttons[0].value;
  21058. this.buttonB = this.browserGamepad.buttons[1].value;
  21059. this.buttonX = this.browserGamepad.buttons[2].value;
  21060. this.buttonY = this.browserGamepad.buttons[3].value;
  21061. this.buttonLB = this.browserGamepad.buttons[4].value;
  21062. this.buttonRB = this.browserGamepad.buttons[5].value;
  21063. this.leftTrigger = this.browserGamepad.buttons[6].value;
  21064. this.rightTrigger = this.browserGamepad.buttons[7].value;
  21065. this.buttonBack = this.browserGamepad.buttons[8].value;
  21066. this.buttonStart = this.browserGamepad.buttons[9].value;
  21067. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  21068. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  21069. this.dPadUp = this.browserGamepad.buttons[12].value;
  21070. this.dPadDown = this.browserGamepad.buttons[13].value;
  21071. this.dPadLeft = this.browserGamepad.buttons[14].value;
  21072. this.dPadRight = this.browserGamepad.buttons[15].value;
  21073. };
  21074. return Xbox360Pad;
  21075. })(Gamepad);
  21076. BABYLON.Xbox360Pad = Xbox360Pad;
  21077. })(BABYLON || (BABYLON = {}));
  21078. var __extends = this.__extends || function (d, b) {
  21079. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21080. function __() { this.constructor = d; }
  21081. __.prototype = b.prototype;
  21082. d.prototype = new __();
  21083. };
  21084. var BABYLON;
  21085. (function (BABYLON) {
  21086. var GamepadCamera = (function (_super) {
  21087. __extends(GamepadCamera, _super);
  21088. function GamepadCamera(name, position, scene) {
  21089. var _this = this;
  21090. _super.call(this, name, position, scene);
  21091. this.angularSensibility = 200;
  21092. this.moveSensibility = 75;
  21093. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21094. _this._onNewGameConnected(gamepad);
  21095. });
  21096. }
  21097. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21098. if (gamepad.index === 0) {
  21099. this._gamepad = gamepad;
  21100. }
  21101. };
  21102. GamepadCamera.prototype._checkInputs = function () {
  21103. if (!this._gamepad) {
  21104. return;
  21105. }
  21106. var LSValues = this._gamepad.leftStick;
  21107. var normalizedLX = LSValues.x / this.moveSensibility;
  21108. var normalizedLY = LSValues.y / this.moveSensibility;
  21109. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  21110. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  21111. var RSValues = this._gamepad.rightStick;
  21112. var normalizedRX = RSValues.x / this.angularSensibility;
  21113. var normalizedRY = RSValues.y / this.angularSensibility;
  21114. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  21115. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  21116. ;
  21117. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21118. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  21119. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21120. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  21121. };
  21122. GamepadCamera.prototype.dispose = function () {
  21123. this._gamepads.dispose();
  21124. _super.prototype.dispose.call(this);
  21125. };
  21126. return GamepadCamera;
  21127. })(BABYLON.FreeCamera);
  21128. BABYLON.GamepadCamera = GamepadCamera;
  21129. })(BABYLON || (BABYLON = {}));
  21130. var __extends = this.__extends || function (d, b) {
  21131. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21132. function __() { this.constructor = d; }
  21133. __.prototype = b.prototype;
  21134. d.prototype = new __();
  21135. };
  21136. var BABYLON;
  21137. (function (BABYLON) {
  21138. var LinesMesh = (function (_super) {
  21139. __extends(LinesMesh, _super);
  21140. function LinesMesh(name, scene, updatable) {
  21141. if (typeof updatable === "undefined") { updatable = false; }
  21142. _super.call(this, name, scene);
  21143. this.color = new BABYLON.Color3(1, 1, 1);
  21144. this.alpha = 1;
  21145. this._indices = new Array();
  21146. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  21147. attributes: ["position"],
  21148. uniforms: ["worldViewProjection", "color"],
  21149. needAlphaBlending: true
  21150. });
  21151. }
  21152. Object.defineProperty(LinesMesh.prototype, "material", {
  21153. get: function () {
  21154. return this._colorShader;
  21155. },
  21156. enumerable: true,
  21157. configurable: true
  21158. });
  21159. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  21160. get: function () {
  21161. return false;
  21162. },
  21163. enumerable: true,
  21164. configurable: true
  21165. });
  21166. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  21167. get: function () {
  21168. return false;
  21169. },
  21170. enumerable: true,
  21171. configurable: true
  21172. });
  21173. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  21174. var engine = this.getScene().getEngine();
  21175. var indexToBind = this._geometry.getIndexBuffer();
  21176. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  21177. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  21178. };
  21179. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21180. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21181. return;
  21182. }
  21183. var engine = this.getScene().getEngine();
  21184. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  21185. };
  21186. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  21187. return null;
  21188. };
  21189. LinesMesh.prototype.dispose = function (doNotRecurse) {
  21190. this._colorShader.dispose();
  21191. _super.prototype.dispose.call(this, doNotRecurse);
  21192. };
  21193. return LinesMesh;
  21194. })(BABYLON.Mesh);
  21195. BABYLON.LinesMesh = LinesMesh;
  21196. })(BABYLON || (BABYLON = {}));
  21197. var BABYLON;
  21198. (function (BABYLON) {
  21199. var OutlineRenderer = (function () {
  21200. function OutlineRenderer(scene) {
  21201. this._scene = scene;
  21202. }
  21203. OutlineRenderer.prototype.render = function (subMesh, batch) {
  21204. var scene = this._scene;
  21205. var engine = this._scene.getEngine();
  21206. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  21207. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  21208. return;
  21209. }
  21210. var mesh = subMesh.getRenderingMesh();
  21211. var material = subMesh.getMaterial();
  21212. engine.enableEffect(this._effect);
  21213. this._effect.setFloat("offset", mesh.outlineWidth);
  21214. this._effect.setColor3("color", mesh.outlineColor);
  21215. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  21216. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  21217. if (useBones) {
  21218. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  21219. }
  21220. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  21221. if (material && material.needAlphaTesting()) {
  21222. var alphaTexture = material.getAlphaTestTexture();
  21223. this._effect.setTexture("diffuseSampler", alphaTexture);
  21224. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  21225. }
  21226. if (hardwareInstancedRendering) {
  21227. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  21228. } else {
  21229. if (batch.renderSelf[subMesh._id]) {
  21230. this._effect.setMatrix("world", mesh.getWorldMatrix());
  21231. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  21232. }
  21233. if (batch.visibleInstances[subMesh._id]) {
  21234. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  21235. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  21236. this._effect.setMatrix("world", instance.getWorldMatrix());
  21237. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  21238. }
  21239. }
  21240. }
  21241. };
  21242. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  21243. var defines = [];
  21244. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  21245. var mesh = subMesh.getMesh();
  21246. var material = subMesh.getMaterial();
  21247. if (material && material.needAlphaTesting()) {
  21248. defines.push("#define ALPHATEST");
  21249. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21250. attribs.push(BABYLON.VertexBuffer.UVKind);
  21251. defines.push("#define UV1");
  21252. }
  21253. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  21254. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  21255. defines.push("#define UV2");
  21256. }
  21257. }
  21258. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21259. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21260. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21261. defines.push("#define BONES");
  21262. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  21263. }
  21264. if (useInstances) {
  21265. defines.push("#define INSTANCES");
  21266. attribs.push("world0");
  21267. attribs.push("world1");
  21268. attribs.push("world2");
  21269. attribs.push("world3");
  21270. }
  21271. var join = defines.join("\n");
  21272. if (this._cachedDefines != join) {
  21273. this._cachedDefines = join;
  21274. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  21275. }
  21276. return this._effect.isReady();
  21277. };
  21278. return OutlineRenderer;
  21279. })();
  21280. BABYLON.OutlineRenderer = OutlineRenderer;
  21281. })(BABYLON || (BABYLON = {}));
  21282. var BABYLON;
  21283. (function (BABYLON) {
  21284. var MeshAssetTask = (function () {
  21285. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  21286. this.name = name;
  21287. this.meshesNames = meshesNames;
  21288. this.rootUrl = rootUrl;
  21289. this.sceneFilename = sceneFilename;
  21290. this.isCompleted = false;
  21291. }
  21292. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21293. var _this = this;
  21294. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  21295. _this.loadedMeshes = meshes;
  21296. _this.loadedParticleSystems = particleSystems;
  21297. _this.loadedSkeletons = skeletons;
  21298. _this.isCompleted = true;
  21299. if (_this.onSuccess) {
  21300. _this.onSuccess(_this);
  21301. }
  21302. onSuccess();
  21303. }, null, function () {
  21304. if (_this.onError) {
  21305. _this.onError(_this);
  21306. }
  21307. onError();
  21308. });
  21309. };
  21310. return MeshAssetTask;
  21311. })();
  21312. BABYLON.MeshAssetTask = MeshAssetTask;
  21313. var TextFileAssetTask = (function () {
  21314. function TextFileAssetTask(name, url) {
  21315. this.name = name;
  21316. this.url = url;
  21317. this.isCompleted = false;
  21318. }
  21319. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21320. var _this = this;
  21321. BABYLON.Tools.LoadFile(this.url, function (data) {
  21322. _this.text = data;
  21323. _this.isCompleted = true;
  21324. if (_this.onSuccess) {
  21325. _this.onSuccess(_this);
  21326. }
  21327. onSuccess();
  21328. }, null, scene.database, false, function () {
  21329. if (_this.onError) {
  21330. _this.onError(_this);
  21331. }
  21332. onError();
  21333. });
  21334. };
  21335. return TextFileAssetTask;
  21336. })();
  21337. BABYLON.TextFileAssetTask = TextFileAssetTask;
  21338. var BinaryFileAssetTask = (function () {
  21339. function BinaryFileAssetTask(name, url) {
  21340. this.name = name;
  21341. this.url = url;
  21342. this.isCompleted = false;
  21343. }
  21344. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21345. var _this = this;
  21346. BABYLON.Tools.LoadFile(this.url, function (data) {
  21347. _this.data = data;
  21348. _this.isCompleted = true;
  21349. if (_this.onSuccess) {
  21350. _this.onSuccess(_this);
  21351. }
  21352. onSuccess();
  21353. }, null, scene.database, true, function () {
  21354. if (_this.onError) {
  21355. _this.onError(_this);
  21356. }
  21357. onError();
  21358. });
  21359. };
  21360. return BinaryFileAssetTask;
  21361. })();
  21362. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  21363. var ImageAssetTask = (function () {
  21364. function ImageAssetTask(name, url) {
  21365. this.name = name;
  21366. this.url = url;
  21367. this.isCompleted = false;
  21368. }
  21369. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21370. var _this = this;
  21371. var img = new Image();
  21372. img.onload = function () {
  21373. _this.image = img;
  21374. _this.isCompleted = true;
  21375. if (_this.onSuccess) {
  21376. _this.onSuccess(_this);
  21377. }
  21378. onSuccess();
  21379. };
  21380. img.onerror = function () {
  21381. if (_this.onError) {
  21382. _this.onError(_this);
  21383. }
  21384. onError();
  21385. };
  21386. img.src = this.url;
  21387. };
  21388. return ImageAssetTask;
  21389. })();
  21390. BABYLON.ImageAssetTask = ImageAssetTask;
  21391. var TextureAssetTask = (function () {
  21392. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  21393. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21394. this.name = name;
  21395. this.url = url;
  21396. this.noMipmap = noMipmap;
  21397. this.invertY = invertY;
  21398. this.samplingMode = samplingMode;
  21399. this.isCompleted = false;
  21400. }
  21401. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21402. var _this = this;
  21403. var onload = function () {
  21404. _this.isCompleted = true;
  21405. if (_this.onSuccess) {
  21406. _this.onSuccess(_this);
  21407. }
  21408. onSuccess();
  21409. };
  21410. var onerror = function () {
  21411. if (_this.onError) {
  21412. _this.onError(_this);
  21413. }
  21414. onError();
  21415. };
  21416. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  21417. };
  21418. return TextureAssetTask;
  21419. })();
  21420. BABYLON.TextureAssetTask = TextureAssetTask;
  21421. var AssetsManager = (function () {
  21422. function AssetsManager(scene) {
  21423. this._tasks = new Array();
  21424. this._waitingTasksCount = 0;
  21425. this.useDefaultLoadingScreen = true;
  21426. this._scene = scene;
  21427. }
  21428. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  21429. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  21430. this._tasks.push(task);
  21431. return task;
  21432. };
  21433. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  21434. var task = new TextFileAssetTask(taskName, url);
  21435. this._tasks.push(task);
  21436. return task;
  21437. };
  21438. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  21439. var task = new BinaryFileAssetTask(taskName, url);
  21440. this._tasks.push(task);
  21441. return task;
  21442. };
  21443. AssetsManager.prototype.addImageTask = function (taskName, url) {
  21444. var task = new ImageAssetTask(taskName, url);
  21445. this._tasks.push(task);
  21446. return task;
  21447. };
  21448. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  21449. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21450. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  21451. this._tasks.push(task);
  21452. return task;
  21453. };
  21454. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  21455. this._waitingTasksCount--;
  21456. if (this._waitingTasksCount === 0) {
  21457. if (this.onFinish) {
  21458. this.onFinish(this._tasks);
  21459. }
  21460. this._scene.getEngine().hideLoadingUI();
  21461. }
  21462. };
  21463. AssetsManager.prototype._runTask = function (task) {
  21464. var _this = this;
  21465. task.run(this._scene, function () {
  21466. if (_this.onTaskSuccess) {
  21467. _this.onTaskSuccess(task);
  21468. }
  21469. _this._decreaseWaitingTasksCount();
  21470. }, function () {
  21471. if (_this.onTaskError) {
  21472. _this.onTaskError(task);
  21473. }
  21474. _this._decreaseWaitingTasksCount();
  21475. });
  21476. };
  21477. AssetsManager.prototype.reset = function () {
  21478. this._tasks = new Array();
  21479. return this;
  21480. };
  21481. AssetsManager.prototype.load = function () {
  21482. this._waitingTasksCount = this._tasks.length;
  21483. if (this._waitingTasksCount === 0) {
  21484. if (this.onFinish) {
  21485. this.onFinish(this._tasks);
  21486. }
  21487. return this;
  21488. }
  21489. if (this.useDefaultLoadingScreen) {
  21490. this._scene.getEngine().displayLoadingUI();
  21491. }
  21492. for (var index = 0; index < this._tasks.length; index++) {
  21493. var task = this._tasks[index];
  21494. this._runTask(task);
  21495. }
  21496. return this;
  21497. };
  21498. return AssetsManager;
  21499. })();
  21500. BABYLON.AssetsManager = AssetsManager;
  21501. })(BABYLON || (BABYLON = {}));
  21502. var __extends = this.__extends || function (d, b) {
  21503. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21504. function __() { this.constructor = d; }
  21505. __.prototype = b.prototype;
  21506. d.prototype = new __();
  21507. };
  21508. var BABYLON;
  21509. (function (BABYLON) {
  21510. var VRDeviceOrientationCamera = (function (_super) {
  21511. __extends(VRDeviceOrientationCamera, _super);
  21512. function VRDeviceOrientationCamera(name, position, scene) {
  21513. _super.call(this, name, position, scene);
  21514. this._alpha = 0;
  21515. this._beta = 0;
  21516. this._gamma = 0;
  21517. }
  21518. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  21519. this._alpha = +evt.alpha | 0;
  21520. this._beta = +evt.beta | 0;
  21521. this._gamma = +evt.gamma | 0;
  21522. if (this._gamma < 0) {
  21523. this._gamma = 90 + this._gamma;
  21524. } else {
  21525. this._gamma = 270 - this._gamma;
  21526. }
  21527. this.rotation.x = this._gamma / 180.0 * Math.PI;
  21528. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  21529. this.rotation.z = this._beta / 180.0 * Math.PI;
  21530. };
  21531. return VRDeviceOrientationCamera;
  21532. })(BABYLON.OculusCamera);
  21533. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  21534. })(BABYLON || (BABYLON = {}));
  21535. var __extends = this.__extends || function (d, b) {
  21536. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21537. function __() { this.constructor = d; }
  21538. __.prototype = b.prototype;
  21539. d.prototype = new __();
  21540. };
  21541. var BABYLON;
  21542. (function (BABYLON) {
  21543. var WebVRCamera = (function (_super) {
  21544. __extends(WebVRCamera, _super);
  21545. function WebVRCamera(name, position, scene) {
  21546. _super.call(this, name, position, scene);
  21547. this._hmdDevice = null;
  21548. this._sensorDevice = null;
  21549. this._cacheState = null;
  21550. this._cacheQuaternion = new BABYLON.Quaternion();
  21551. this._cacheRotation = BABYLON.Vector3.Zero();
  21552. this._vrEnabled = false;
  21553. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  21554. }
  21555. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  21556. var size = devices.length;
  21557. var i = 0;
  21558. this._sensorDevice = null;
  21559. this._hmdDevice = null;
  21560. while (i < size && this._hmdDevice === null) {
  21561. if (devices[i] instanceof HMDVRDevice) {
  21562. this._hmdDevice = devices[i];
  21563. }
  21564. i++;
  21565. }
  21566. i = 0;
  21567. while (i < size && this._sensorDevice === null) {
  21568. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  21569. this._sensorDevice = devices[i];
  21570. }
  21571. i++;
  21572. }
  21573. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  21574. };
  21575. WebVRCamera.prototype._update = function () {
  21576. if (this._vrEnabled) {
  21577. this._cacheState = this._sensorDevice.getState();
  21578. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  21579. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  21580. this.rotation.x = -this._cacheRotation.z;
  21581. this.rotation.y = -this._cacheRotation.y;
  21582. this.rotation.z = this._cacheRotation.x;
  21583. }
  21584. _super.prototype._update.call(this);
  21585. };
  21586. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  21587. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21588. if (navigator.getVRDevices) {
  21589. navigator.getVRDevices().then(this._getWebVRDevices);
  21590. } else if (navigator.mozGetVRDevices) {
  21591. navigator.mozGetVRDevices(this._getWebVRDevices);
  21592. }
  21593. };
  21594. WebVRCamera.prototype.detachControl = function (element) {
  21595. _super.prototype.detachControl.call(this, element);
  21596. this._vrEnabled = false;
  21597. };
  21598. return WebVRCamera;
  21599. })(BABYLON.OculusCamera);
  21600. BABYLON.WebVRCamera = WebVRCamera;
  21601. })(BABYLON || (BABYLON = {}));
  21602. var __extends = this.__extends || function (d, b) {
  21603. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21604. function __() { this.constructor = d; }
  21605. __.prototype = b.prototype;
  21606. d.prototype = new __();
  21607. };
  21608. var BABYLON;
  21609. (function (BABYLON) {
  21610. var SceneOptimization = (function () {
  21611. function SceneOptimization(priority) {
  21612. if (typeof priority === "undefined") { priority = 0; }
  21613. this.priority = priority;
  21614. this.apply = function (scene) {
  21615. return true;
  21616. };
  21617. }
  21618. return SceneOptimization;
  21619. })();
  21620. BABYLON.SceneOptimization = SceneOptimization;
  21621. var TextureOptimization = (function (_super) {
  21622. __extends(TextureOptimization, _super);
  21623. function TextureOptimization(priority, maximumSize) {
  21624. if (typeof priority === "undefined") { priority = 0; }
  21625. if (typeof maximumSize === "undefined") { maximumSize = 1024; }
  21626. var _this = this;
  21627. _super.call(this, priority);
  21628. this.priority = priority;
  21629. this.maximumSize = maximumSize;
  21630. this.apply = function (scene) {
  21631. var allDone = true;
  21632. for (var index = 0; index < scene.textures.length; index++) {
  21633. var texture = scene.textures[index];
  21634. if (!texture.canRescale) {
  21635. continue;
  21636. }
  21637. var currentSize = texture.getSize();
  21638. var maxDimension = Math.max(currentSize.width, currentSize.height);
  21639. if (maxDimension > _this.maximumSize) {
  21640. texture.scale(0.5);
  21641. allDone = false;
  21642. }
  21643. }
  21644. return allDone;
  21645. };
  21646. }
  21647. return TextureOptimization;
  21648. })(SceneOptimization);
  21649. BABYLON.TextureOptimization = TextureOptimization;
  21650. var HardwareScalingOptimization = (function (_super) {
  21651. __extends(HardwareScalingOptimization, _super);
  21652. function HardwareScalingOptimization(priority, maximumScale) {
  21653. if (typeof priority === "undefined") { priority = 0; }
  21654. if (typeof maximumScale === "undefined") { maximumScale = 2; }
  21655. var _this = this;
  21656. _super.call(this, priority);
  21657. this.priority = priority;
  21658. this.maximumScale = maximumScale;
  21659. this._currentScale = 1;
  21660. this.apply = function (scene) {
  21661. _this._currentScale++;
  21662. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  21663. return _this._currentScale >= _this.maximumScale;
  21664. };
  21665. }
  21666. return HardwareScalingOptimization;
  21667. })(SceneOptimization);
  21668. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  21669. var ShadowsOptimization = (function (_super) {
  21670. __extends(ShadowsOptimization, _super);
  21671. function ShadowsOptimization() {
  21672. _super.apply(this, arguments);
  21673. this.apply = function (scene) {
  21674. scene.shadowsEnabled = false;
  21675. return true;
  21676. };
  21677. }
  21678. return ShadowsOptimization;
  21679. })(SceneOptimization);
  21680. BABYLON.ShadowsOptimization = ShadowsOptimization;
  21681. var PostProcessesOptimization = (function (_super) {
  21682. __extends(PostProcessesOptimization, _super);
  21683. function PostProcessesOptimization() {
  21684. _super.apply(this, arguments);
  21685. this.apply = function (scene) {
  21686. scene.postProcessesEnabled = false;
  21687. return true;
  21688. };
  21689. }
  21690. return PostProcessesOptimization;
  21691. })(SceneOptimization);
  21692. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  21693. var LensFlaresOptimization = (function (_super) {
  21694. __extends(LensFlaresOptimization, _super);
  21695. function LensFlaresOptimization() {
  21696. _super.apply(this, arguments);
  21697. this.apply = function (scene) {
  21698. scene.lensFlaresEnabled = false;
  21699. return true;
  21700. };
  21701. }
  21702. return LensFlaresOptimization;
  21703. })(SceneOptimization);
  21704. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  21705. var ParticlesOptimization = (function (_super) {
  21706. __extends(ParticlesOptimization, _super);
  21707. function ParticlesOptimization() {
  21708. _super.apply(this, arguments);
  21709. this.apply = function (scene) {
  21710. scene.particlesEnabled = false;
  21711. return true;
  21712. };
  21713. }
  21714. return ParticlesOptimization;
  21715. })(SceneOptimization);
  21716. BABYLON.ParticlesOptimization = ParticlesOptimization;
  21717. var RenderTargetsOptimization = (function (_super) {
  21718. __extends(RenderTargetsOptimization, _super);
  21719. function RenderTargetsOptimization() {
  21720. _super.apply(this, arguments);
  21721. this.apply = function (scene) {
  21722. scene.renderTargetsEnabled = false;
  21723. return true;
  21724. };
  21725. }
  21726. return RenderTargetsOptimization;
  21727. })(SceneOptimization);
  21728. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  21729. var SceneOptimizerOptions = (function () {
  21730. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  21731. if (typeof targetFrameRate === "undefined") { targetFrameRate = 60; }
  21732. if (typeof trackerDuration === "undefined") { trackerDuration = 2000; }
  21733. this.targetFrameRate = targetFrameRate;
  21734. this.trackerDuration = trackerDuration;
  21735. this.optimizations = new Array();
  21736. }
  21737. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  21738. var result = new SceneOptimizerOptions(targetFrameRate);
  21739. var priority = 0;
  21740. result.optimizations.push(new ShadowsOptimization(priority));
  21741. result.optimizations.push(new LensFlaresOptimization(priority));
  21742. priority++;
  21743. result.optimizations.push(new PostProcessesOptimization(priority));
  21744. result.optimizations.push(new ParticlesOptimization(priority));
  21745. priority++;
  21746. result.optimizations.push(new TextureOptimization(priority, 1024));
  21747. return result;
  21748. };
  21749. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  21750. var result = new SceneOptimizerOptions(targetFrameRate);
  21751. var priority = 0;
  21752. result.optimizations.push(new ShadowsOptimization(priority));
  21753. result.optimizations.push(new LensFlaresOptimization(priority));
  21754. priority++;
  21755. result.optimizations.push(new PostProcessesOptimization(priority));
  21756. result.optimizations.push(new ParticlesOptimization(priority));
  21757. priority++;
  21758. result.optimizations.push(new TextureOptimization(priority, 512));
  21759. priority++;
  21760. result.optimizations.push(new RenderTargetsOptimization(priority));
  21761. priority++;
  21762. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  21763. return result;
  21764. };
  21765. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  21766. var result = new SceneOptimizerOptions(targetFrameRate);
  21767. var priority = 0;
  21768. result.optimizations.push(new ShadowsOptimization(priority));
  21769. result.optimizations.push(new LensFlaresOptimization(priority));
  21770. priority++;
  21771. result.optimizations.push(new PostProcessesOptimization(priority));
  21772. result.optimizations.push(new ParticlesOptimization(priority));
  21773. priority++;
  21774. result.optimizations.push(new TextureOptimization(priority, 256));
  21775. priority++;
  21776. result.optimizations.push(new RenderTargetsOptimization(priority));
  21777. priority++;
  21778. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  21779. return result;
  21780. };
  21781. return SceneOptimizerOptions;
  21782. })();
  21783. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  21784. var SceneOptimizer = (function () {
  21785. function SceneOptimizer() {
  21786. }
  21787. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  21788. if (BABYLON.Tools.GetFps() >= options.targetFrameRate) {
  21789. if (onSuccess) {
  21790. onSuccess();
  21791. }
  21792. return;
  21793. }
  21794. var allDone = true;
  21795. var noOptimizationApplied = true;
  21796. for (var index = 0; index < options.optimizations.length; index++) {
  21797. var optimization = options.optimizations[index];
  21798. if (optimization.priority === currentPriorityLevel) {
  21799. noOptimizationApplied = false;
  21800. allDone = allDone && optimization.apply(scene);
  21801. }
  21802. }
  21803. if (noOptimizationApplied) {
  21804. if (onFailure) {
  21805. onFailure();
  21806. }
  21807. return;
  21808. }
  21809. if (allDone) {
  21810. currentPriorityLevel++;
  21811. }
  21812. scene.executeWhenReady(function () {
  21813. setTimeout(function () {
  21814. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  21815. }, options.trackerDuration);
  21816. });
  21817. };
  21818. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  21819. if (!options) {
  21820. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  21821. }
  21822. scene.executeWhenReady(function () {
  21823. setTimeout(function () {
  21824. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  21825. }, options.trackerDuration);
  21826. });
  21827. };
  21828. return SceneOptimizer;
  21829. })();
  21830. BABYLON.SceneOptimizer = SceneOptimizer;
  21831. })(BABYLON || (BABYLON = {}));