babylon.2.0-alpha.debug.js 1.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665
  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 Quaternion = (function () {
  698. function Quaternion(x, y, z, w) {
  699. if (typeof x === "undefined") { x = 0; }
  700. if (typeof y === "undefined") { y = 0; }
  701. if (typeof z === "undefined") { z = 0; }
  702. if (typeof w === "undefined") { w = 1; }
  703. this.x = x;
  704. this.y = y;
  705. this.z = z;
  706. this.w = w;
  707. }
  708. Quaternion.prototype.toString = function () {
  709. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  710. };
  711. Quaternion.prototype.asArray = function () {
  712. return [this.x, this.y, this.z, this.w];
  713. };
  714. Quaternion.prototype.equals = function (otherQuaternion) {
  715. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  716. };
  717. Quaternion.prototype.clone = function () {
  718. return new Quaternion(this.x, this.y, this.z, this.w);
  719. };
  720. Quaternion.prototype.copyFrom = function (other) {
  721. this.x = other.x;
  722. this.y = other.y;
  723. this.z = other.z;
  724. this.w = other.w;
  725. };
  726. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  727. this.x = x;
  728. this.y = y;
  729. this.z = z;
  730. this.w = w;
  731. };
  732. Quaternion.prototype.add = function (other) {
  733. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  734. };
  735. Quaternion.prototype.subtract = function (other) {
  736. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  737. };
  738. Quaternion.prototype.scale = function (value) {
  739. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  740. };
  741. Quaternion.prototype.multiply = function (q1) {
  742. var result = new Quaternion(0, 0, 0, 1.0);
  743. this.multiplyToRef(q1, result);
  744. return result;
  745. };
  746. Quaternion.prototype.multiplyToRef = function (q1, result) {
  747. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  748. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  749. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  750. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  751. };
  752. Quaternion.prototype.length = function () {
  753. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  754. };
  755. Quaternion.prototype.normalize = function () {
  756. var length = 1.0 / this.length();
  757. this.x *= length;
  758. this.y *= length;
  759. this.z *= length;
  760. this.w *= length;
  761. };
  762. Quaternion.prototype.toEulerAngles = function () {
  763. var result = Vector3.Zero();
  764. this.toEulerAnglesToRef(result);
  765. return result;
  766. };
  767. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  768. var qx = this.x;
  769. var qy = this.y;
  770. var qz = this.z;
  771. var qw = this.w;
  772. var sqx = qx * qx;
  773. var sqy = qy * qy;
  774. var sqz = qz * qz;
  775. var yaw = Math.atan2(2.0 * (qy * qw - qx * qz), 1.0 - 2.0 * (sqy + sqz));
  776. var pitch = Math.asin(2.0 * (qx * qy + qz * qw));
  777. var roll = Math.atan2(2.0 * (qx * qw - qy * qz), 1.0 - 2.0 * (sqx + sqz));
  778. var gimbaLockTest = qx * qy + qz * qw;
  779. if (gimbaLockTest > 0.499) {
  780. yaw = 2.0 * Math.atan2(qx, qw);
  781. roll = 0;
  782. } else if (gimbaLockTest < -0.499) {
  783. yaw = -2.0 * Math.atan2(qx, qw);
  784. roll = 0;
  785. }
  786. result.x = pitch;
  787. result.y = yaw;
  788. result.z = roll;
  789. };
  790. Quaternion.prototype.toRotationMatrix = function (result) {
  791. var xx = this.x * this.x;
  792. var yy = this.y * this.y;
  793. var zz = this.z * this.z;
  794. var xy = this.x * this.y;
  795. var zw = this.z * this.w;
  796. var zx = this.z * this.x;
  797. var yw = this.y * this.w;
  798. var yz = this.y * this.z;
  799. var xw = this.x * this.w;
  800. result.m[0] = 1.0 - (2.0 * (yy + zz));
  801. result.m[1] = 2.0 * (xy + zw);
  802. result.m[2] = 2.0 * (zx - yw);
  803. result.m[3] = 0;
  804. result.m[4] = 2.0 * (xy - zw);
  805. result.m[5] = 1.0 - (2.0 * (zz + xx));
  806. result.m[6] = 2.0 * (yz + xw);
  807. result.m[7] = 0;
  808. result.m[8] = 2.0 * (zx + yw);
  809. result.m[9] = 2.0 * (yz - xw);
  810. result.m[10] = 1.0 - (2.0 * (yy + xx));
  811. result.m[11] = 0;
  812. result.m[12] = 0;
  813. result.m[13] = 0;
  814. result.m[14] = 0;
  815. result.m[15] = 1.0;
  816. };
  817. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  818. var data = matrix.m;
  819. var m11 = data[0], m12 = data[4], m13 = data[8];
  820. var m21 = data[1], m22 = data[5], m23 = data[9];
  821. var m31 = data[2], m32 = data[6], m33 = data[10];
  822. var trace = m11 + m22 + m33;
  823. var s;
  824. if (trace > 0) {
  825. s = 0.5 / Math.sqrt(trace + 1.0);
  826. this.w = 0.25 / s;
  827. this.x = (m32 - m23) * s;
  828. this.y = (m13 - m31) * s;
  829. this.z = (m21 - m12) * s;
  830. return;
  831. }
  832. if (m11 > m22 && m11 > m33) {
  833. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  834. this.w = (m32 - m23) / s;
  835. this.x = 0.25 * s;
  836. this.y = (m12 + m21) / s;
  837. this.z = (m13 + m31) / s;
  838. return;
  839. }
  840. if (m22 > m33) {
  841. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  842. this.w = (m13 - m31) / s;
  843. this.x = (m12 + m21) / s;
  844. this.y = 0.25 * s;
  845. this.z = (m23 + m32) / s;
  846. return;
  847. }
  848. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  849. this.w = (m21 - m12) / s;
  850. this.x = (m13 + m31) / s;
  851. this.y = (m23 + m32) / s;
  852. this.z = 0.25 * s;
  853. };
  854. Quaternion.Inverse = function (q) {
  855. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  856. };
  857. Quaternion.RotationAxis = function (axis, angle) {
  858. var result = new Quaternion();
  859. var sin = Math.sin(angle / 2);
  860. result.w = Math.cos(angle / 2);
  861. result.x = axis.x * sin;
  862. result.y = axis.y * sin;
  863. result.z = axis.z * sin;
  864. return result;
  865. };
  866. Quaternion.FromArray = function (array, offset) {
  867. if (!offset) {
  868. offset = 0;
  869. }
  870. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  871. };
  872. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  873. var result = new Quaternion();
  874. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  875. return result;
  876. };
  877. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  878. var halfRoll = roll * 0.5;
  879. var halfPitch = pitch * 0.5;
  880. var halfYaw = yaw * 0.5;
  881. var sinRoll = Math.sin(halfRoll);
  882. var cosRoll = Math.cos(halfRoll);
  883. var sinPitch = Math.sin(halfPitch);
  884. var cosPitch = Math.cos(halfPitch);
  885. var sinYaw = Math.sin(halfYaw);
  886. var cosYaw = Math.cos(halfYaw);
  887. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  888. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  889. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  890. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  891. };
  892. Quaternion.Slerp = function (left, right, amount) {
  893. var num2;
  894. var num3;
  895. var num = amount;
  896. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  897. var flag = false;
  898. if (num4 < 0) {
  899. flag = true;
  900. num4 = -num4;
  901. }
  902. if (num4 > 0.999999) {
  903. num3 = 1 - num;
  904. num2 = flag ? -num : num;
  905. } else {
  906. var num5 = Math.acos(num4);
  907. var num6 = (1.0 / Math.sin(num5));
  908. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  909. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  910. }
  911. 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));
  912. };
  913. return Quaternion;
  914. })();
  915. BABYLON.Quaternion = Quaternion;
  916. var Matrix = (function () {
  917. function Matrix() {
  918. this.m = new Float32Array(16);
  919. }
  920. Matrix.prototype.isIdentity = function () {
  921. if (this.m[0] != 1.0 || this.m[5] != 1.0 || this.m[10] != 1.0 || this.m[15] != 1.0)
  922. return false;
  923. 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)
  924. return false;
  925. return true;
  926. };
  927. Matrix.prototype.determinant = function () {
  928. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  929. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  930. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  931. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  932. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  933. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  934. 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))));
  935. };
  936. Matrix.prototype.toArray = function () {
  937. return this.m;
  938. };
  939. Matrix.prototype.asArray = function () {
  940. return this.toArray();
  941. };
  942. Matrix.prototype.invert = function () {
  943. this.invertToRef(this);
  944. };
  945. Matrix.prototype.invertToRef = function (other) {
  946. var l1 = this.m[0];
  947. var l2 = this.m[1];
  948. var l3 = this.m[2];
  949. var l4 = this.m[3];
  950. var l5 = this.m[4];
  951. var l6 = this.m[5];
  952. var l7 = this.m[6];
  953. var l8 = this.m[7];
  954. var l9 = this.m[8];
  955. var l10 = this.m[9];
  956. var l11 = this.m[10];
  957. var l12 = this.m[11];
  958. var l13 = this.m[12];
  959. var l14 = this.m[13];
  960. var l15 = this.m[14];
  961. var l16 = this.m[15];
  962. var l17 = (l11 * l16) - (l12 * l15);
  963. var l18 = (l10 * l16) - (l12 * l14);
  964. var l19 = (l10 * l15) - (l11 * l14);
  965. var l20 = (l9 * l16) - (l12 * l13);
  966. var l21 = (l9 * l15) - (l11 * l13);
  967. var l22 = (l9 * l14) - (l10 * l13);
  968. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  969. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  970. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  971. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  972. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  973. var l28 = (l7 * l16) - (l8 * l15);
  974. var l29 = (l6 * l16) - (l8 * l14);
  975. var l30 = (l6 * l15) - (l7 * l14);
  976. var l31 = (l5 * l16) - (l8 * l13);
  977. var l32 = (l5 * l15) - (l7 * l13);
  978. var l33 = (l5 * l14) - (l6 * l13);
  979. var l34 = (l7 * l12) - (l8 * l11);
  980. var l35 = (l6 * l12) - (l8 * l10);
  981. var l36 = (l6 * l11) - (l7 * l10);
  982. var l37 = (l5 * l12) - (l8 * l9);
  983. var l38 = (l5 * l11) - (l7 * l9);
  984. var l39 = (l5 * l10) - (l6 * l9);
  985. other.m[0] = l23 * l27;
  986. other.m[4] = l24 * l27;
  987. other.m[8] = l25 * l27;
  988. other.m[12] = l26 * l27;
  989. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  990. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  991. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  992. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  993. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  994. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  995. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  996. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  997. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  998. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  999. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1000. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1001. };
  1002. Matrix.prototype.setTranslation = function (vector3) {
  1003. this.m[12] = vector3.x;
  1004. this.m[13] = vector3.y;
  1005. this.m[14] = vector3.z;
  1006. };
  1007. Matrix.prototype.multiply = function (other) {
  1008. var result = new Matrix();
  1009. this.multiplyToRef(other, result);
  1010. return result;
  1011. };
  1012. Matrix.prototype.copyFrom = function (other) {
  1013. for (var index = 0; index < 16; index++) {
  1014. this.m[index] = other.m[index];
  1015. }
  1016. };
  1017. Matrix.prototype.copyToArray = function (array, offset) {
  1018. if (typeof offset === "undefined") { offset = 0; }
  1019. for (var index = 0; index < 16; index++) {
  1020. array[offset + index] = this.m[index];
  1021. }
  1022. };
  1023. Matrix.prototype.multiplyToRef = function (other, result) {
  1024. this.multiplyToArray(other, result.m, 0);
  1025. };
  1026. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1027. var tm0 = this.m[0];
  1028. var tm1 = this.m[1];
  1029. var tm2 = this.m[2];
  1030. var tm3 = this.m[3];
  1031. var tm4 = this.m[4];
  1032. var tm5 = this.m[5];
  1033. var tm6 = this.m[6];
  1034. var tm7 = this.m[7];
  1035. var tm8 = this.m[8];
  1036. var tm9 = this.m[9];
  1037. var tm10 = this.m[10];
  1038. var tm11 = this.m[11];
  1039. var tm12 = this.m[12];
  1040. var tm13 = this.m[13];
  1041. var tm14 = this.m[14];
  1042. var tm15 = this.m[15];
  1043. var om0 = other.m[0];
  1044. var om1 = other.m[1];
  1045. var om2 = other.m[2];
  1046. var om3 = other.m[3];
  1047. var om4 = other.m[4];
  1048. var om5 = other.m[5];
  1049. var om6 = other.m[6];
  1050. var om7 = other.m[7];
  1051. var om8 = other.m[8];
  1052. var om9 = other.m[9];
  1053. var om10 = other.m[10];
  1054. var om11 = other.m[11];
  1055. var om12 = other.m[12];
  1056. var om13 = other.m[13];
  1057. var om14 = other.m[14];
  1058. var om15 = other.m[15];
  1059. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1060. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1061. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1062. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1063. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1064. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1065. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1066. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1067. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1068. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1069. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1070. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1071. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1072. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1073. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1074. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1075. };
  1076. Matrix.prototype.equals = function (value) {
  1077. 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]);
  1078. };
  1079. Matrix.prototype.clone = function () {
  1080. 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]);
  1081. };
  1082. Matrix.FromArray = function (array, offset) {
  1083. var result = new Matrix();
  1084. if (!offset) {
  1085. offset = 0;
  1086. }
  1087. Matrix.FromArrayToRef(array, offset, result);
  1088. return result;
  1089. };
  1090. Matrix.FromArrayToRef = function (array, offset, result) {
  1091. for (var index = 0; index < 16; index++) {
  1092. result.m[index] = array[index + offset];
  1093. }
  1094. };
  1095. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1096. result.m[0] = initialM11;
  1097. result.m[1] = initialM12;
  1098. result.m[2] = initialM13;
  1099. result.m[3] = initialM14;
  1100. result.m[4] = initialM21;
  1101. result.m[5] = initialM22;
  1102. result.m[6] = initialM23;
  1103. result.m[7] = initialM24;
  1104. result.m[8] = initialM31;
  1105. result.m[9] = initialM32;
  1106. result.m[10] = initialM33;
  1107. result.m[11] = initialM34;
  1108. result.m[12] = initialM41;
  1109. result.m[13] = initialM42;
  1110. result.m[14] = initialM43;
  1111. result.m[15] = initialM44;
  1112. };
  1113. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1114. var result = new Matrix();
  1115. result.m[0] = initialM11;
  1116. result.m[1] = initialM12;
  1117. result.m[2] = initialM13;
  1118. result.m[3] = initialM14;
  1119. result.m[4] = initialM21;
  1120. result.m[5] = initialM22;
  1121. result.m[6] = initialM23;
  1122. result.m[7] = initialM24;
  1123. result.m[8] = initialM31;
  1124. result.m[9] = initialM32;
  1125. result.m[10] = initialM33;
  1126. result.m[11] = initialM34;
  1127. result.m[12] = initialM41;
  1128. result.m[13] = initialM42;
  1129. result.m[14] = initialM43;
  1130. result.m[15] = initialM44;
  1131. return result;
  1132. };
  1133. Matrix.Identity = function () {
  1134. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1135. };
  1136. Matrix.IdentityToRef = function (result) {
  1137. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1138. };
  1139. Matrix.Zero = function () {
  1140. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1141. };
  1142. Matrix.RotationX = function (angle) {
  1143. var result = new Matrix();
  1144. Matrix.RotationXToRef(angle, result);
  1145. return result;
  1146. };
  1147. Matrix.RotationXToRef = function (angle, result) {
  1148. var s = Math.sin(angle);
  1149. var c = Math.cos(angle);
  1150. result.m[0] = 1.0;
  1151. result.m[15] = 1.0;
  1152. result.m[5] = c;
  1153. result.m[10] = c;
  1154. result.m[9] = -s;
  1155. result.m[6] = s;
  1156. result.m[1] = 0;
  1157. result.m[2] = 0;
  1158. result.m[3] = 0;
  1159. result.m[4] = 0;
  1160. result.m[7] = 0;
  1161. result.m[8] = 0;
  1162. result.m[11] = 0;
  1163. result.m[12] = 0;
  1164. result.m[13] = 0;
  1165. result.m[14] = 0;
  1166. };
  1167. Matrix.RotationY = function (angle) {
  1168. var result = new Matrix();
  1169. Matrix.RotationYToRef(angle, result);
  1170. return result;
  1171. };
  1172. Matrix.RotationYToRef = function (angle, result) {
  1173. var s = Math.sin(angle);
  1174. var c = Math.cos(angle);
  1175. result.m[5] = 1.0;
  1176. result.m[15] = 1.0;
  1177. result.m[0] = c;
  1178. result.m[2] = -s;
  1179. result.m[8] = s;
  1180. result.m[10] = c;
  1181. result.m[1] = 0;
  1182. result.m[3] = 0;
  1183. result.m[4] = 0;
  1184. result.m[6] = 0;
  1185. result.m[7] = 0;
  1186. result.m[9] = 0;
  1187. result.m[11] = 0;
  1188. result.m[12] = 0;
  1189. result.m[13] = 0;
  1190. result.m[14] = 0;
  1191. };
  1192. Matrix.RotationZ = function (angle) {
  1193. var result = new Matrix();
  1194. Matrix.RotationZToRef(angle, result);
  1195. return result;
  1196. };
  1197. Matrix.RotationZToRef = function (angle, result) {
  1198. var s = Math.sin(angle);
  1199. var c = Math.cos(angle);
  1200. result.m[10] = 1.0;
  1201. result.m[15] = 1.0;
  1202. result.m[0] = c;
  1203. result.m[1] = s;
  1204. result.m[4] = -s;
  1205. result.m[5] = c;
  1206. result.m[2] = 0;
  1207. result.m[3] = 0;
  1208. result.m[6] = 0;
  1209. result.m[7] = 0;
  1210. result.m[8] = 0;
  1211. result.m[9] = 0;
  1212. result.m[11] = 0;
  1213. result.m[12] = 0;
  1214. result.m[13] = 0;
  1215. result.m[14] = 0;
  1216. };
  1217. Matrix.RotationAxis = function (axis, angle) {
  1218. var s = Math.sin(-angle);
  1219. var c = Math.cos(-angle);
  1220. var c1 = 1 - c;
  1221. axis.normalize();
  1222. var result = Matrix.Zero();
  1223. result.m[0] = (axis.x * axis.x) * c1 + c;
  1224. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1225. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1226. result.m[3] = 0.0;
  1227. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1228. result.m[5] = (axis.y * axis.y) * c1 + c;
  1229. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1230. result.m[7] = 0.0;
  1231. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1232. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1233. result.m[10] = (axis.z * axis.z) * c1 + c;
  1234. result.m[11] = 0.0;
  1235. result.m[15] = 1.0;
  1236. return result;
  1237. };
  1238. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1239. var result = new Matrix();
  1240. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1241. return result;
  1242. };
  1243. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1244. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1245. this._tempQuaternion.toRotationMatrix(result);
  1246. };
  1247. Matrix.Scaling = function (x, y, z) {
  1248. var result = Matrix.Zero();
  1249. Matrix.ScalingToRef(x, y, z, result);
  1250. return result;
  1251. };
  1252. Matrix.ScalingToRef = function (x, y, z, result) {
  1253. result.m[0] = x;
  1254. result.m[1] = 0;
  1255. result.m[2] = 0;
  1256. result.m[3] = 0;
  1257. result.m[4] = 0;
  1258. result.m[5] = y;
  1259. result.m[6] = 0;
  1260. result.m[7] = 0;
  1261. result.m[8] = 0;
  1262. result.m[9] = 0;
  1263. result.m[10] = z;
  1264. result.m[11] = 0;
  1265. result.m[12] = 0;
  1266. result.m[13] = 0;
  1267. result.m[14] = 0;
  1268. result.m[15] = 1.0;
  1269. };
  1270. Matrix.Translation = function (x, y, z) {
  1271. var result = Matrix.Identity();
  1272. Matrix.TranslationToRef(x, y, z, result);
  1273. return result;
  1274. };
  1275. Matrix.TranslationToRef = function (x, y, z, result) {
  1276. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1277. };
  1278. Matrix.LookAtLH = function (eye, target, up) {
  1279. var result = Matrix.Zero();
  1280. Matrix.LookAtLHToRef(eye, target, up, result);
  1281. return result;
  1282. };
  1283. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1284. target.subtractToRef(eye, this._zAxis);
  1285. this._zAxis.normalize();
  1286. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1287. this._xAxis.normalize();
  1288. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1289. this._yAxis.normalize();
  1290. var ex = -Vector3.Dot(this._xAxis, eye);
  1291. var ey = -Vector3.Dot(this._yAxis, eye);
  1292. var ez = -Vector3.Dot(this._zAxis, eye);
  1293. 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);
  1294. };
  1295. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1296. var hw = 2.0 / width;
  1297. var hh = 2.0 / height;
  1298. var id = 1.0 / (zfar - znear);
  1299. var nid = znear / (znear - zfar);
  1300. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1301. };
  1302. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1303. var matrix = Matrix.Zero();
  1304. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1305. return matrix;
  1306. };
  1307. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1308. result.m[0] = 2.0 / (right - left);
  1309. result.m[1] = result.m[2] = result.m[3] = 0;
  1310. result.m[5] = 2.0 / (top - bottom);
  1311. result.m[4] = result.m[6] = result.m[7] = 0;
  1312. result.m[10] = -1.0 / (znear - zfar);
  1313. result.m[8] = result.m[9] = result.m[11] = 0;
  1314. result.m[12] = (left + right) / (left - right);
  1315. result.m[13] = (top + bottom) / (bottom - top);
  1316. result.m[14] = znear / (znear - zfar);
  1317. result.m[15] = 1.0;
  1318. };
  1319. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1320. var matrix = Matrix.Zero();
  1321. matrix.m[0] = (2.0 * znear) / width;
  1322. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1323. matrix.m[5] = (2.0 * znear) / height;
  1324. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1325. matrix.m[10] = -zfar / (znear - zfar);
  1326. matrix.m[8] = matrix.m[9] = 0.0;
  1327. matrix.m[11] = 1.0;
  1328. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1329. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1330. return matrix;
  1331. };
  1332. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1333. var matrix = Matrix.Zero();
  1334. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1335. return matrix;
  1336. };
  1337. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1338. var tan = 1.0 / (Math.tan(fov * 0.5));
  1339. result.m[0] = tan / aspect;
  1340. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1341. result.m[5] = tan;
  1342. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1343. result.m[8] = result.m[9] = 0.0;
  1344. result.m[10] = -zfar / (znear - zfar);
  1345. result.m[11] = 1.0;
  1346. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1347. result.m[14] = (znear * zfar) / (znear - zfar);
  1348. };
  1349. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1350. var cw = viewport.width;
  1351. var ch = viewport.height;
  1352. var cx = viewport.x;
  1353. var cy = viewport.y;
  1354. 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);
  1355. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1356. };
  1357. Matrix.Transpose = function (matrix) {
  1358. var result = new Matrix();
  1359. result.m[0] = matrix.m[0];
  1360. result.m[1] = matrix.m[4];
  1361. result.m[2] = matrix.m[8];
  1362. result.m[3] = matrix.m[12];
  1363. result.m[4] = matrix.m[1];
  1364. result.m[5] = matrix.m[5];
  1365. result.m[6] = matrix.m[9];
  1366. result.m[7] = matrix.m[13];
  1367. result.m[8] = matrix.m[2];
  1368. result.m[9] = matrix.m[6];
  1369. result.m[10] = matrix.m[10];
  1370. result.m[11] = matrix.m[14];
  1371. result.m[12] = matrix.m[3];
  1372. result.m[13] = matrix.m[7];
  1373. result.m[14] = matrix.m[11];
  1374. result.m[15] = matrix.m[15];
  1375. return result;
  1376. };
  1377. Matrix.Reflection = function (plane) {
  1378. var matrix = new Matrix();
  1379. Matrix.ReflectionToRef(plane, matrix);
  1380. return matrix;
  1381. };
  1382. Matrix.ReflectionToRef = function (plane, result) {
  1383. plane.normalize();
  1384. var x = plane.normal.x;
  1385. var y = plane.normal.y;
  1386. var z = plane.normal.z;
  1387. var temp = -2 * x;
  1388. var temp2 = -2 * y;
  1389. var temp3 = -2 * z;
  1390. result.m[0] = (temp * x) + 1;
  1391. result.m[1] = temp2 * x;
  1392. result.m[2] = temp3 * x;
  1393. result.m[3] = 0.0;
  1394. result.m[4] = temp * y;
  1395. result.m[5] = (temp2 * y) + 1;
  1396. result.m[6] = temp3 * y;
  1397. result.m[7] = 0.0;
  1398. result.m[8] = temp * z;
  1399. result.m[9] = temp2 * z;
  1400. result.m[10] = (temp3 * z) + 1;
  1401. result.m[11] = 0.0;
  1402. result.m[12] = temp * plane.d;
  1403. result.m[13] = temp2 * plane.d;
  1404. result.m[14] = temp3 * plane.d;
  1405. result.m[15] = 1.0;
  1406. };
  1407. Matrix._tempQuaternion = new Quaternion();
  1408. Matrix._xAxis = Vector3.Zero();
  1409. Matrix._yAxis = Vector3.Zero();
  1410. Matrix._zAxis = Vector3.Zero();
  1411. return Matrix;
  1412. })();
  1413. BABYLON.Matrix = Matrix;
  1414. var Plane = (function () {
  1415. function Plane(a, b, c, d) {
  1416. this.normal = new Vector3(a, b, c);
  1417. this.d = d;
  1418. }
  1419. Plane.prototype.asArray = function () {
  1420. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1421. };
  1422. Plane.prototype.clone = function () {
  1423. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1424. };
  1425. Plane.prototype.normalize = function () {
  1426. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1427. var magnitude = 0;
  1428. if (norm != 0) {
  1429. magnitude = 1.0 / norm;
  1430. }
  1431. this.normal.x *= magnitude;
  1432. this.normal.y *= magnitude;
  1433. this.normal.z *= magnitude;
  1434. this.d *= magnitude;
  1435. };
  1436. Plane.prototype.transform = function (transformation) {
  1437. var transposedMatrix = BABYLON.Matrix.Transpose(transformation);
  1438. var x = this.normal.x;
  1439. var y = this.normal.y;
  1440. var z = this.normal.z;
  1441. var d = this.d;
  1442. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1443. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1444. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1445. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1446. return new BABYLON.Plane(normalX, normalY, normalZ, finalD);
  1447. };
  1448. Plane.prototype.dotCoordinate = function (point) {
  1449. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1450. };
  1451. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1452. var x1 = point2.x - point1.x;
  1453. var y1 = point2.y - point1.y;
  1454. var z1 = point2.z - point1.z;
  1455. var x2 = point3.x - point1.x;
  1456. var y2 = point3.y - point1.y;
  1457. var z2 = point3.z - point1.z;
  1458. var yz = (y1 * z2) - (z1 * y2);
  1459. var xz = (z1 * x2) - (x1 * z2);
  1460. var xy = (x1 * y2) - (y1 * x2);
  1461. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1462. var invPyth;
  1463. if (pyth != 0) {
  1464. invPyth = 1.0 / pyth;
  1465. } else {
  1466. invPyth = 0;
  1467. }
  1468. this.normal.x = yz * invPyth;
  1469. this.normal.y = xz * invPyth;
  1470. this.normal.z = xy * invPyth;
  1471. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1472. };
  1473. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1474. var dot = Vector3.Dot(this.normal, direction);
  1475. return (dot <= epsilon);
  1476. };
  1477. Plane.prototype.signedDistanceTo = function (point) {
  1478. return Vector3.Dot(point, this.normal) + this.d;
  1479. };
  1480. Plane.FromArray = function (array) {
  1481. return new BABYLON.Plane(array[0], array[1], array[2], array[3]);
  1482. };
  1483. Plane.FromPoints = function (point1, point2, point3) {
  1484. var result = new BABYLON.Plane(0, 0, 0, 0);
  1485. result.copyFromPoints(point1, point2, point3);
  1486. return result;
  1487. };
  1488. Plane.FromPositionAndNormal = function (origin, normal) {
  1489. var result = new BABYLON.Plane(0, 0, 0, 0);
  1490. normal.normalize();
  1491. result.normal = normal;
  1492. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1493. return result;
  1494. };
  1495. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1496. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1497. return Vector3.Dot(point, normal) + d;
  1498. };
  1499. return Plane;
  1500. })();
  1501. BABYLON.Plane = Plane;
  1502. var Viewport = (function () {
  1503. function Viewport(x, y, width, height) {
  1504. this.x = x;
  1505. this.y = y;
  1506. this.width = width;
  1507. this.height = height;
  1508. }
  1509. Viewport.prototype.toGlobal = function (engine) {
  1510. var width = engine.getRenderWidth();
  1511. var height = engine.getRenderHeight();
  1512. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1513. };
  1514. return Viewport;
  1515. })();
  1516. BABYLON.Viewport = Viewport;
  1517. var Frustum = (function () {
  1518. function Frustum() {
  1519. }
  1520. Frustum.GetPlanes = function (transform) {
  1521. var frustumPlanes = [];
  1522. for (var index = 0; index < 6; index++) {
  1523. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1524. }
  1525. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1526. return frustumPlanes;
  1527. };
  1528. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1529. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1530. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1531. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1532. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1533. frustumPlanes[0].normalize();
  1534. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1535. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1536. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1537. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1538. frustumPlanes[1].normalize();
  1539. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1540. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1541. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1542. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1543. frustumPlanes[2].normalize();
  1544. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1545. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1546. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1547. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1548. frustumPlanes[3].normalize();
  1549. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1550. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1551. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1552. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1553. frustumPlanes[4].normalize();
  1554. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1555. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1556. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1557. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1558. frustumPlanes[5].normalize();
  1559. };
  1560. return Frustum;
  1561. })();
  1562. BABYLON.Frustum = Frustum;
  1563. var Ray = (function () {
  1564. function Ray(origin, direction) {
  1565. this.origin = origin;
  1566. this.direction = direction;
  1567. }
  1568. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1569. var d = 0.0;
  1570. var maxValue = Number.MAX_VALUE;
  1571. if (Math.abs(this.direction.x) < 0.0000001) {
  1572. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1573. return false;
  1574. }
  1575. } else {
  1576. var inv = 1.0 / this.direction.x;
  1577. var min = (minimum.x - this.origin.x) * inv;
  1578. var max = (maximum.x - this.origin.x) * inv;
  1579. if (min > max) {
  1580. var temp = min;
  1581. min = max;
  1582. max = temp;
  1583. }
  1584. d = Math.max(min, d);
  1585. maxValue = Math.min(max, maxValue);
  1586. if (d > maxValue) {
  1587. return false;
  1588. }
  1589. }
  1590. if (Math.abs(this.direction.y) < 0.0000001) {
  1591. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1592. return false;
  1593. }
  1594. } else {
  1595. inv = 1.0 / this.direction.y;
  1596. min = (minimum.y - this.origin.y) * inv;
  1597. max = (maximum.y - this.origin.y) * inv;
  1598. if (min > max) {
  1599. temp = min;
  1600. min = max;
  1601. max = temp;
  1602. }
  1603. d = Math.max(min, d);
  1604. maxValue = Math.min(max, maxValue);
  1605. if (d > maxValue) {
  1606. return false;
  1607. }
  1608. }
  1609. if (Math.abs(this.direction.z) < 0.0000001) {
  1610. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1611. return false;
  1612. }
  1613. } else {
  1614. inv = 1.0 / this.direction.z;
  1615. min = (minimum.z - this.origin.z) * inv;
  1616. max = (maximum.z - this.origin.z) * inv;
  1617. if (min > max) {
  1618. temp = min;
  1619. min = max;
  1620. max = temp;
  1621. }
  1622. d = Math.max(min, d);
  1623. maxValue = Math.min(max, maxValue);
  1624. if (d > maxValue) {
  1625. return false;
  1626. }
  1627. }
  1628. return true;
  1629. };
  1630. Ray.prototype.intersectsBox = function (box) {
  1631. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1632. };
  1633. Ray.prototype.intersectsSphere = function (sphere) {
  1634. var x = sphere.center.x - this.origin.x;
  1635. var y = sphere.center.y - this.origin.y;
  1636. var z = sphere.center.z - this.origin.z;
  1637. var pyth = (x * x) + (y * y) + (z * z);
  1638. var rr = sphere.radius * sphere.radius;
  1639. if (pyth <= rr) {
  1640. return true;
  1641. }
  1642. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1643. if (dot < 0.0) {
  1644. return false;
  1645. }
  1646. var temp = pyth - (dot * dot);
  1647. return temp <= rr;
  1648. };
  1649. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1650. if (!this._edge1) {
  1651. this._edge1 = BABYLON.Vector3.Zero();
  1652. this._edge2 = BABYLON.Vector3.Zero();
  1653. this._pvec = BABYLON.Vector3.Zero();
  1654. this._tvec = BABYLON.Vector3.Zero();
  1655. this._qvec = BABYLON.Vector3.Zero();
  1656. }
  1657. vertex1.subtractToRef(vertex0, this._edge1);
  1658. vertex2.subtractToRef(vertex0, this._edge2);
  1659. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1660. var det = Vector3.Dot(this._edge1, this._pvec);
  1661. if (det === 0) {
  1662. return null;
  1663. }
  1664. var invdet = 1 / det;
  1665. this.origin.subtractToRef(vertex0, this._tvec);
  1666. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1667. if (bu < 0 || bu > 1.0) {
  1668. return null;
  1669. }
  1670. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1671. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1672. if (bv < 0 || bu + bv > 1.0) {
  1673. return null;
  1674. }
  1675. return new BABYLON.IntersectionInfo(bu, bv, Vector3.Dot(this._edge2, this._qvec) * invdet);
  1676. };
  1677. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1678. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1679. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1680. var direction = end.subtract(start);
  1681. direction.normalize();
  1682. return new Ray(start, direction);
  1683. };
  1684. Ray.Transform = function (ray, matrix) {
  1685. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  1686. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  1687. return new Ray(newOrigin, newDirection);
  1688. };
  1689. return Ray;
  1690. })();
  1691. BABYLON.Ray = Ray;
  1692. (function (Space) {
  1693. Space[Space["LOCAL"] = 0] = "LOCAL";
  1694. Space[Space["WORLD"] = 1] = "WORLD";
  1695. })(BABYLON.Space || (BABYLON.Space = {}));
  1696. var Space = BABYLON.Space;
  1697. var Axis = (function () {
  1698. function Axis() {
  1699. }
  1700. Axis.X = new BABYLON.Vector3(1, 0, 0);
  1701. Axis.Y = new BABYLON.Vector3(0, 1, 0);
  1702. Axis.Z = new BABYLON.Vector3(0, 0, 1);
  1703. return Axis;
  1704. })();
  1705. BABYLON.Axis = Axis;
  1706. ;
  1707. })(BABYLON || (BABYLON = {}));
  1708. var BABYLON;
  1709. (function (BABYLON) {
  1710. var screenshotCanvas;
  1711. var fpsRange = 60;
  1712. var previousFramesDuration = [];
  1713. var fps = 60;
  1714. var deltaTime = 0;
  1715. var cloneValue = function (source, destinationObject) {
  1716. if (!source)
  1717. return null;
  1718. if (source instanceof BABYLON.Mesh) {
  1719. return null;
  1720. }
  1721. if (source instanceof BABYLON.SubMesh) {
  1722. return source.clone(destinationObject);
  1723. } else if (source.clone) {
  1724. return source.clone();
  1725. }
  1726. return null;
  1727. };
  1728. var Tools = (function () {
  1729. function Tools() {
  1730. }
  1731. Tools.GetFilename = function (path) {
  1732. var index = path.lastIndexOf("/");
  1733. if (index < 0)
  1734. return path;
  1735. return path.substring(index + 1);
  1736. };
  1737. Tools.GetDOMTextContent = function (element) {
  1738. var result = "";
  1739. var child = element.firstChild;
  1740. while (child) {
  1741. if (child.nodeType == 3) {
  1742. result += child.textContent;
  1743. }
  1744. child = child.nextSibling;
  1745. }
  1746. return result;
  1747. };
  1748. Tools.ToDegrees = function (angle) {
  1749. return angle * 180 / Math.PI;
  1750. };
  1751. Tools.ToRadians = function (angle) {
  1752. return angle * Math.PI / 180;
  1753. };
  1754. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  1755. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1756. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1757. for (var index = indexStart; index < indexStart + indexCount; index++) {
  1758. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  1759. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1760. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1761. }
  1762. return {
  1763. minimum: minimum,
  1764. maximum: maximum
  1765. };
  1766. };
  1767. Tools.ExtractMinAndMax = function (positions, start, count) {
  1768. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1769. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1770. for (var index = start; index < start + count; index++) {
  1771. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  1772. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1773. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1774. }
  1775. return {
  1776. minimum: minimum,
  1777. maximum: maximum
  1778. };
  1779. };
  1780. Tools.MakeArray = function (obj, allowsNullUndefined) {
  1781. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  1782. return undefined;
  1783. return Array.isArray(obj) ? obj : [obj];
  1784. };
  1785. Tools.GetPointerPrefix = function () {
  1786. var eventPrefix = "pointer";
  1787. if (!navigator.pointerEnabled) {
  1788. eventPrefix = "mouse";
  1789. }
  1790. return eventPrefix;
  1791. };
  1792. Tools.QueueNewFrame = function (func) {
  1793. if (window.requestAnimationFrame)
  1794. window.requestAnimationFrame(func);
  1795. else if (window.msRequestAnimationFrame)
  1796. window.msRequestAnimationFrame(func);
  1797. else if (window.webkitRequestAnimationFrame)
  1798. window.webkitRequestAnimationFrame(func);
  1799. else if (window.mozRequestAnimationFrame)
  1800. window.mozRequestAnimationFrame(func);
  1801. else if (window.oRequestAnimationFrame)
  1802. window.oRequestAnimationFrame(func);
  1803. else {
  1804. window.setTimeout(func, 16);
  1805. }
  1806. };
  1807. Tools.RequestFullscreen = function (element) {
  1808. if (element.requestFullscreen)
  1809. element.requestFullscreen();
  1810. else if (element.msRequestFullscreen)
  1811. element.msRequestFullscreen();
  1812. else if (element.webkitRequestFullscreen)
  1813. element.webkitRequestFullscreen();
  1814. else if (element.mozRequestFullScreen)
  1815. element.mozRequestFullScreen();
  1816. };
  1817. Tools.ExitFullscreen = function () {
  1818. if (document.exitFullscreen) {
  1819. document.exitFullscreen();
  1820. } else if (document.mozCancelFullScreen) {
  1821. document.mozCancelFullScreen();
  1822. } else if (document.webkitCancelFullScreen) {
  1823. document.webkitCancelFullScreen();
  1824. } else if (document.msCancelFullScreen) {
  1825. document.msCancelFullScreen();
  1826. }
  1827. };
  1828. Tools.CleanUrl = function (url) {
  1829. url = url.replace(/#/mg, "%23");
  1830. return url;
  1831. };
  1832. Tools.LoadImage = function (url, onload, onerror, database) {
  1833. url = Tools.CleanUrl(url);
  1834. var img = new Image();
  1835. if (url.substr(0, 5) != "data:")
  1836. img.crossOrigin = 'anonymous';
  1837. img.onload = function () {
  1838. onload(img);
  1839. };
  1840. img.onerror = function (err) {
  1841. onerror(img, err);
  1842. };
  1843. var noIndexedDB = function () {
  1844. img.src = url;
  1845. };
  1846. var loadFromIndexedDB = function () {
  1847. database.loadImageFromDB(url, img);
  1848. };
  1849. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  1850. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1851. } else {
  1852. if (url.indexOf("file:") === -1) {
  1853. noIndexedDB();
  1854. } else {
  1855. try {
  1856. var textureName = url.substring(5);
  1857. var blobURL;
  1858. try {
  1859. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  1860. } catch (ex) {
  1861. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  1862. }
  1863. img.src = blobURL;
  1864. } catch (e) {
  1865. Tools.Log("Error while trying to load texture: " + textureName);
  1866. img.src = null;
  1867. }
  1868. }
  1869. }
  1870. return img;
  1871. };
  1872. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  1873. url = Tools.CleanUrl(url);
  1874. var noIndexedDB = function () {
  1875. var request = new XMLHttpRequest();
  1876. var loadUrl = Tools.BaseUrl + url;
  1877. request.open('GET', loadUrl, true);
  1878. if (useArrayBuffer) {
  1879. request.responseType = "arraybuffer";
  1880. }
  1881. request.onprogress = progressCallBack;
  1882. request.onreadystatechange = function () {
  1883. if (request.readyState == 4) {
  1884. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  1885. callback(!useArrayBuffer ? request.responseText : request.response);
  1886. } else {
  1887. if (onError) {
  1888. onError();
  1889. } else {
  1890. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  1891. }
  1892. }
  1893. }
  1894. };
  1895. request.send(null);
  1896. };
  1897. var loadFromIndexedDB = function () {
  1898. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  1899. };
  1900. if (url.indexOf("file:") !== -1) {
  1901. var fileName = url.substring(5);
  1902. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  1903. } else {
  1904. if (database && database.enableSceneOffline) {
  1905. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1906. } else {
  1907. noIndexedDB();
  1908. }
  1909. }
  1910. };
  1911. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  1912. var reader = new FileReader();
  1913. reader.onload = function (e) {
  1914. callback(e.target.result);
  1915. };
  1916. reader.onprogress = progressCallback;
  1917. reader.readAsDataURL(fileToLoad);
  1918. };
  1919. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  1920. var reader = new FileReader();
  1921. reader.onload = function (e) {
  1922. callback(e.target.result);
  1923. };
  1924. reader.onprogress = progressCallBack;
  1925. if (!useArrayBuffer) {
  1926. reader.readAsText(fileToLoad);
  1927. } else {
  1928. reader.readAsArrayBuffer(fileToLoad);
  1929. }
  1930. };
  1931. Tools.CheckExtends = function (v, min, max) {
  1932. if (v.x < min.x)
  1933. min.x = v.x;
  1934. if (v.y < min.y)
  1935. min.y = v.y;
  1936. if (v.z < min.z)
  1937. min.z = v.z;
  1938. if (v.x > max.x)
  1939. max.x = v.x;
  1940. if (v.y > max.y)
  1941. max.y = v.y;
  1942. if (v.z > max.z)
  1943. max.z = v.z;
  1944. };
  1945. Tools.WithinEpsilon = function (a, b) {
  1946. var num = a - b;
  1947. return -1.401298E-45 <= num && num <= 1.401298E-45;
  1948. };
  1949. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  1950. for (var prop in source) {
  1951. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  1952. continue;
  1953. }
  1954. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  1955. continue;
  1956. }
  1957. var sourceValue = source[prop];
  1958. var typeOfSourceValue = typeof sourceValue;
  1959. if (typeOfSourceValue == "function") {
  1960. continue;
  1961. }
  1962. if (typeOfSourceValue == "object") {
  1963. if (sourceValue instanceof Array) {
  1964. destination[prop] = [];
  1965. if (sourceValue.length > 0) {
  1966. if (typeof sourceValue[0] == "object") {
  1967. for (var index = 0; index < sourceValue.length; index++) {
  1968. var clonedValue = cloneValue(sourceValue[index], destination);
  1969. if (destination[prop].indexOf(clonedValue) === -1) {
  1970. destination[prop].push(clonedValue);
  1971. }
  1972. }
  1973. } else {
  1974. destination[prop] = sourceValue.slice(0);
  1975. }
  1976. }
  1977. } else {
  1978. destination[prop] = cloneValue(sourceValue, destination);
  1979. }
  1980. } else {
  1981. destination[prop] = sourceValue;
  1982. }
  1983. }
  1984. };
  1985. Tools.IsEmpty = function (obj) {
  1986. for (var i in obj) {
  1987. return false;
  1988. }
  1989. return true;
  1990. };
  1991. Tools.RegisterTopRootEvents = function (events) {
  1992. for (var index = 0; index < events.length; index++) {
  1993. var event = events[index];
  1994. window.addEventListener(event.name, event.handler, false);
  1995. try {
  1996. if (window.parent) {
  1997. window.parent.addEventListener(event.name, event.handler, false);
  1998. }
  1999. } catch (e) {
  2000. }
  2001. }
  2002. };
  2003. Tools.UnregisterTopRootEvents = function (events) {
  2004. for (var index = 0; index < events.length; index++) {
  2005. var event = events[index];
  2006. window.removeEventListener(event.name, event.handler);
  2007. try {
  2008. if (window.parent) {
  2009. window.parent.removeEventListener(event.name, event.handler);
  2010. }
  2011. } catch (e) {
  2012. }
  2013. }
  2014. };
  2015. Tools.GetFps = function () {
  2016. return fps;
  2017. };
  2018. Tools.GetDeltaTime = function () {
  2019. return deltaTime;
  2020. };
  2021. Tools._MeasureFps = function () {
  2022. previousFramesDuration.push((new Date).getTime());
  2023. var length = previousFramesDuration.length;
  2024. if (length >= 2) {
  2025. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  2026. }
  2027. if (length >= fpsRange) {
  2028. if (length > fpsRange) {
  2029. previousFramesDuration.splice(0, 1);
  2030. length = previousFramesDuration.length;
  2031. }
  2032. var sum = 0;
  2033. for (var id = 0; id < length - 1; id++) {
  2034. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  2035. }
  2036. fps = 1000.0 / (sum / (length - 1));
  2037. }
  2038. };
  2039. Tools.CreateScreenshot = function (engine, camera, size) {
  2040. var width;
  2041. var height;
  2042. var scene = camera.getScene();
  2043. var previousCamera = null;
  2044. if (scene.activeCamera !== camera) {
  2045. previousCamera = scene.activeCamera;
  2046. scene.activeCamera = camera;
  2047. }
  2048. if (size.precision) {
  2049. width = Math.round(engine.getRenderWidth() * size.precision);
  2050. height = Math.round(width / engine.getAspectRatio(camera));
  2051. size = { width: width, height: height };
  2052. } else if (size.width && size.height) {
  2053. width = size.width;
  2054. height = size.height;
  2055. } else if (size.width && !size.height) {
  2056. width = size.width;
  2057. height = Math.round(width / engine.getAspectRatio(camera));
  2058. size = { width: width, height: height };
  2059. } else if (size.height && !size.width) {
  2060. height = size.height;
  2061. width = Math.round(height * engine.getAspectRatio(camera));
  2062. size = { width: width, height: height };
  2063. } else if (!isNaN(size)) {
  2064. height = size;
  2065. width = size;
  2066. } else {
  2067. Tools.Error("Invalid 'size' parameter !");
  2068. return;
  2069. }
  2070. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2071. texture.renderList = engine.scenes[0].meshes;
  2072. texture.onAfterRender = function () {
  2073. var numberOfChannelsByLine = width * 4;
  2074. var halfHeight = height / 2;
  2075. var data = engine.readPixels(0, 0, width, height);
  2076. for (var i = 0; i < halfHeight; i++) {
  2077. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2078. var currentCell = j + i * numberOfChannelsByLine;
  2079. var targetLine = height - i - 1;
  2080. var targetCell = j + targetLine * numberOfChannelsByLine;
  2081. var temp = data[currentCell];
  2082. data[currentCell] = data[targetCell];
  2083. data[targetCell] = temp;
  2084. }
  2085. }
  2086. if (!screenshotCanvas) {
  2087. screenshotCanvas = document.createElement('canvas');
  2088. }
  2089. screenshotCanvas.width = width;
  2090. screenshotCanvas.height = height;
  2091. var context = screenshotCanvas.getContext('2d');
  2092. var imageData = context.createImageData(width, height);
  2093. imageData.data.set(data);
  2094. context.putImageData(imageData, 0, 0);
  2095. var base64Image = screenshotCanvas.toDataURL();
  2096. if (("download" in document.createElement("a"))) {
  2097. var a = window.document.createElement("a");
  2098. a.href = base64Image;
  2099. var date = new Date();
  2100. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2101. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2102. window.document.body.appendChild(a);
  2103. a.addEventListener("click", function () {
  2104. a.parentElement.removeChild(a);
  2105. });
  2106. a.click();
  2107. } else {
  2108. var newWindow = window.open("");
  2109. var img = newWindow.document.createElement("img");
  2110. img.src = base64Image;
  2111. newWindow.document.body.appendChild(img);
  2112. }
  2113. };
  2114. texture.render(true);
  2115. texture.dispose();
  2116. if (previousCamera) {
  2117. scene.activeCamera = previousCamera;
  2118. }
  2119. };
  2120. Tools.ValidateXHRData = function (xhr, dataType) {
  2121. if (typeof dataType === "undefined") { dataType = 7; }
  2122. try {
  2123. if (dataType & 1) {
  2124. if (xhr.responseText && xhr.responseText.length > 0) {
  2125. return true;
  2126. } else if (dataType === 1) {
  2127. return false;
  2128. }
  2129. }
  2130. if (dataType & 2) {
  2131. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2132. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2133. return true;
  2134. } else if (dataType === 2) {
  2135. return false;
  2136. }
  2137. }
  2138. if (dataType & 4) {
  2139. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2140. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2141. return true;
  2142. } else {
  2143. return false;
  2144. }
  2145. }
  2146. } catch (e) {
  2147. }
  2148. return false;
  2149. };
  2150. Object.defineProperty(Tools, "NoneLogLevel", {
  2151. get: function () {
  2152. return Tools._NoneLogLevel;
  2153. },
  2154. enumerable: true,
  2155. configurable: true
  2156. });
  2157. Object.defineProperty(Tools, "MessageLogLevel", {
  2158. get: function () {
  2159. return Tools._MessageLogLevel;
  2160. },
  2161. enumerable: true,
  2162. configurable: true
  2163. });
  2164. Object.defineProperty(Tools, "WarningLogLevel", {
  2165. get: function () {
  2166. return Tools._WarningLogLevel;
  2167. },
  2168. enumerable: true,
  2169. configurable: true
  2170. });
  2171. Object.defineProperty(Tools, "ErrorLogLevel", {
  2172. get: function () {
  2173. return Tools._ErrorLogLevel;
  2174. },
  2175. enumerable: true,
  2176. configurable: true
  2177. });
  2178. Object.defineProperty(Tools, "AllLogLevel", {
  2179. get: function () {
  2180. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2181. },
  2182. enumerable: true,
  2183. configurable: true
  2184. });
  2185. Tools._FormatMessage = function (message) {
  2186. var padStr = function (i) {
  2187. return (i < 10) ? "0" + i : "" + i;
  2188. };
  2189. var date = new Date();
  2190. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2191. };
  2192. Tools._LogDisabled = function (message) {
  2193. };
  2194. Tools._LogEnabled = function (message) {
  2195. console.log(Tools._FormatMessage(message));
  2196. };
  2197. Tools._WarnDisabled = function (message) {
  2198. };
  2199. Tools._WarnEnabled = function (message) {
  2200. console.warn(Tools._FormatMessage(message));
  2201. };
  2202. Tools._ErrorDisabled = function (message) {
  2203. };
  2204. Tools._ErrorEnabled = function (message) {
  2205. console.error(Tools._FormatMessage(message));
  2206. };
  2207. Object.defineProperty(Tools, "LogLevels", {
  2208. set: function (level) {
  2209. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2210. Tools.Log = Tools._LogEnabled;
  2211. } else {
  2212. Tools.Log = Tools._LogDisabled;
  2213. }
  2214. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2215. Tools.Warn = Tools._WarnEnabled;
  2216. } else {
  2217. Tools.Warn = Tools._WarnDisabled;
  2218. }
  2219. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2220. Tools.Error = Tools._ErrorEnabled;
  2221. } else {
  2222. Tools.Error = Tools._ErrorDisabled;
  2223. }
  2224. },
  2225. enumerable: true,
  2226. configurable: true
  2227. });
  2228. Tools.BaseUrl = "";
  2229. Tools.GetExponantOfTwo = function (value, max) {
  2230. var count = 1;
  2231. do {
  2232. count *= 2;
  2233. } while(count < value);
  2234. if (count > max)
  2235. count = max;
  2236. return count;
  2237. };
  2238. Tools._NoneLogLevel = 0;
  2239. Tools._MessageLogLevel = 1;
  2240. Tools._WarningLogLevel = 2;
  2241. Tools._ErrorLogLevel = 4;
  2242. Tools.Log = Tools._LogEnabled;
  2243. Tools.Warn = Tools._WarnEnabled;
  2244. Tools.Error = Tools._ErrorEnabled;
  2245. return Tools;
  2246. })();
  2247. BABYLON.Tools = Tools;
  2248. })(BABYLON || (BABYLON = {}));
  2249. var BABYLON;
  2250. (function (BABYLON) {
  2251. var _DepthCullingState = (function () {
  2252. function _DepthCullingState() {
  2253. this._isDepthTestDirty = false;
  2254. this._isDepthMaskDirty = false;
  2255. this._isDepthFuncDirty = false;
  2256. this._isCullFaceDirty = false;
  2257. this._isCullDirty = false;
  2258. }
  2259. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2260. get: function () {
  2261. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2262. },
  2263. enumerable: true,
  2264. configurable: true
  2265. });
  2266. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2267. get: function () {
  2268. return this._cullFace;
  2269. },
  2270. set: function (value) {
  2271. if (this._cullFace === value) {
  2272. return;
  2273. }
  2274. this._cullFace = value;
  2275. this._isCullFaceDirty = true;
  2276. },
  2277. enumerable: true,
  2278. configurable: true
  2279. });
  2280. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2281. get: function () {
  2282. return this._cull;
  2283. },
  2284. set: function (value) {
  2285. if (this._cull === value) {
  2286. return;
  2287. }
  2288. this._cull = value;
  2289. this._isCullDirty = true;
  2290. },
  2291. enumerable: true,
  2292. configurable: true
  2293. });
  2294. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2295. get: function () {
  2296. return this._depthFunc;
  2297. },
  2298. set: function (value) {
  2299. if (this._depthFunc === value) {
  2300. return;
  2301. }
  2302. this._depthFunc = value;
  2303. this._isDepthFuncDirty = true;
  2304. },
  2305. enumerable: true,
  2306. configurable: true
  2307. });
  2308. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2309. get: function () {
  2310. return this._depthMask;
  2311. },
  2312. set: function (value) {
  2313. if (this._depthMask === value) {
  2314. return;
  2315. }
  2316. this._depthMask = value;
  2317. this._isDepthMaskDirty = true;
  2318. },
  2319. enumerable: true,
  2320. configurable: true
  2321. });
  2322. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  2323. get: function () {
  2324. return this._depthTest;
  2325. },
  2326. set: function (value) {
  2327. if (this._depthTest === value) {
  2328. return;
  2329. }
  2330. this._depthTest = value;
  2331. this._isDepthTestDirty = true;
  2332. },
  2333. enumerable: true,
  2334. configurable: true
  2335. });
  2336. _DepthCullingState.prototype.reset = function () {
  2337. this._depthMask = true;
  2338. this._depthTest = true;
  2339. this._depthFunc = null;
  2340. this._cull = null;
  2341. this._cullFace = null;
  2342. this._isDepthTestDirty = true;
  2343. this._isDepthMaskDirty = true;
  2344. this._isDepthFuncDirty = false;
  2345. this._isCullFaceDirty = false;
  2346. this._isCullDirty = false;
  2347. };
  2348. _DepthCullingState.prototype.apply = function (gl) {
  2349. if (!this.isDirty) {
  2350. return;
  2351. }
  2352. if (this._isCullDirty) {
  2353. if (this.cull === true) {
  2354. gl.enable(gl.CULL_FACE);
  2355. } else if (this.cull === false) {
  2356. gl.disable(gl.CULL_FACE);
  2357. }
  2358. this._isCullDirty = false;
  2359. }
  2360. if (this._isCullFaceDirty) {
  2361. gl.cullFace(this.cullFace);
  2362. this._isCullFaceDirty = false;
  2363. }
  2364. if (this._isDepthMaskDirty) {
  2365. gl.depthMask(this.depthMask);
  2366. this._isDepthMaskDirty = false;
  2367. }
  2368. if (this._isDepthTestDirty) {
  2369. if (this.depthTest === true) {
  2370. gl.enable(gl.DEPTH_TEST);
  2371. } else if (this.depthTest === false) {
  2372. gl.disable(gl.DEPTH_TEST);
  2373. }
  2374. this._isDepthTestDirty = false;
  2375. }
  2376. if (this._isDepthFuncDirty) {
  2377. gl.depthFunc(this.depthFunc);
  2378. this._isDepthFuncDirty = false;
  2379. }
  2380. };
  2381. return _DepthCullingState;
  2382. })();
  2383. BABYLON._DepthCullingState = _DepthCullingState;
  2384. var _AlphaState = (function () {
  2385. function _AlphaState() {
  2386. this._isAlphaBlendDirty = false;
  2387. this._isBlendFunctionParametersDirty = false;
  2388. this._alphaBlend = false;
  2389. this._blendFunctionParameters = new Array(4);
  2390. }
  2391. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  2392. get: function () {
  2393. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  2394. },
  2395. enumerable: true,
  2396. configurable: true
  2397. });
  2398. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  2399. get: function () {
  2400. return this._alphaBlend;
  2401. },
  2402. set: function (value) {
  2403. if (this._alphaBlend === value) {
  2404. return;
  2405. }
  2406. this._alphaBlend = value;
  2407. this._isAlphaBlendDirty = true;
  2408. },
  2409. enumerable: true,
  2410. configurable: true
  2411. });
  2412. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  2413. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  2414. return;
  2415. }
  2416. this._blendFunctionParameters[0] = value0;
  2417. this._blendFunctionParameters[1] = value1;
  2418. this._blendFunctionParameters[2] = value2;
  2419. this._blendFunctionParameters[3] = value3;
  2420. this._isBlendFunctionParametersDirty = true;
  2421. };
  2422. _AlphaState.prototype.reset = function () {
  2423. this._alphaBlend = false;
  2424. this._blendFunctionParameters[0] = null;
  2425. this._blendFunctionParameters[1] = null;
  2426. this._blendFunctionParameters[2] = null;
  2427. this._blendFunctionParameters[3] = null;
  2428. this._isAlphaBlendDirty = true;
  2429. this._isBlendFunctionParametersDirty = false;
  2430. };
  2431. _AlphaState.prototype.apply = function (gl) {
  2432. if (!this.isDirty) {
  2433. return;
  2434. }
  2435. if (this._isAlphaBlendDirty) {
  2436. if (this._alphaBlend === true) {
  2437. gl.enable(gl.BLEND);
  2438. } else if (this._alphaBlend === false) {
  2439. gl.disable(gl.BLEND);
  2440. }
  2441. this._isAlphaBlendDirty = false;
  2442. }
  2443. if (this._isBlendFunctionParametersDirty) {
  2444. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  2445. this._isBlendFunctionParametersDirty = false;
  2446. }
  2447. };
  2448. return _AlphaState;
  2449. })();
  2450. BABYLON._AlphaState = _AlphaState;
  2451. var compileShader = function (gl, source, type, defines) {
  2452. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2453. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  2454. gl.compileShader(shader);
  2455. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2456. throw new Error(gl.getShaderInfoLog(shader));
  2457. }
  2458. return shader;
  2459. };
  2460. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  2461. var magFilter = gl.NEAREST;
  2462. var minFilter = gl.NEAREST;
  2463. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  2464. magFilter = gl.LINEAR;
  2465. if (generateMipMaps) {
  2466. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2467. } else {
  2468. minFilter = gl.LINEAR;
  2469. }
  2470. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  2471. magFilter = gl.LINEAR;
  2472. if (generateMipMaps) {
  2473. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2474. } else {
  2475. minFilter = gl.LINEAR;
  2476. }
  2477. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  2478. magFilter = gl.NEAREST;
  2479. if (generateMipMaps) {
  2480. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2481. } else {
  2482. minFilter = gl.NEAREST;
  2483. }
  2484. }
  2485. return {
  2486. min: minFilter,
  2487. mag: magFilter
  2488. };
  2489. };
  2490. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  2491. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  2492. var engine = scene.getEngine();
  2493. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  2494. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  2495. gl.bindTexture(gl.TEXTURE_2D, texture);
  2496. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2497. processFunction(potWidth, potHeight);
  2498. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  2499. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2500. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2501. if (!noMipmap && !isCompressed) {
  2502. gl.generateMipmap(gl.TEXTURE_2D);
  2503. }
  2504. gl.bindTexture(gl.TEXTURE_2D, null);
  2505. engine._activeTexturesCache = [];
  2506. texture._baseWidth = width;
  2507. texture._baseHeight = height;
  2508. texture._width = potWidth;
  2509. texture._height = potHeight;
  2510. texture.isReady = true;
  2511. scene._removePendingData(texture);
  2512. };
  2513. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  2514. var img;
  2515. var onload = function () {
  2516. loadedImages[index] = img;
  2517. loadedImages._internalCount++;
  2518. scene._removePendingData(img);
  2519. if (loadedImages._internalCount == 6) {
  2520. onfinish(loadedImages);
  2521. }
  2522. };
  2523. var onerror = function () {
  2524. scene._removePendingData(img);
  2525. };
  2526. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  2527. scene._addPendingData(img);
  2528. };
  2529. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  2530. var loadedImages = [];
  2531. loadedImages._internalCount = 0;
  2532. for (var index = 0; index < 6; index++) {
  2533. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  2534. }
  2535. };
  2536. var EngineCapabilities = (function () {
  2537. function EngineCapabilities() {
  2538. }
  2539. return EngineCapabilities;
  2540. })();
  2541. BABYLON.EngineCapabilities = EngineCapabilities;
  2542. var Engine = (function () {
  2543. function Engine(canvas, antialias, options) {
  2544. var _this = this;
  2545. this.isFullscreen = false;
  2546. this.isPointerLock = false;
  2547. this.forceWireframe = false;
  2548. this.cullBackFaces = true;
  2549. this.renderEvenInBackground = true;
  2550. this.scenes = new Array();
  2551. this._windowIsBackground = false;
  2552. this._runningLoop = false;
  2553. this._loadingDivBackgroundColor = "black";
  2554. this._depthCullingState = new _DepthCullingState();
  2555. this._alphaState = new _AlphaState();
  2556. this._loadedTexturesCache = new Array();
  2557. this._activeTexturesCache = new Array();
  2558. this._compiledEffects = {};
  2559. this._renderingCanvas = canvas;
  2560. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2561. options = options || {};
  2562. options.antialias = antialias;
  2563. try {
  2564. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  2565. } catch (e) {
  2566. throw new Error("WebGL not supported");
  2567. }
  2568. if (!this._gl) {
  2569. throw new Error("WebGL not supported");
  2570. }
  2571. this._onBlur = function () {
  2572. _this._windowIsBackground = true;
  2573. };
  2574. this._onFocus = function () {
  2575. _this._windowIsBackground = false;
  2576. };
  2577. window.addEventListener("blur", this._onBlur);
  2578. window.addEventListener("focus", this._onFocus);
  2579. this._workingCanvas = document.createElement("canvas");
  2580. this._workingContext = this._workingCanvas.getContext("2d");
  2581. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  2582. this.resize();
  2583. this._caps = new EngineCapabilities();
  2584. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  2585. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  2586. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  2587. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  2588. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  2589. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  2590. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  2591. 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');
  2592. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  2593. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  2594. this.setDepthBuffer(true);
  2595. this.setDepthFunctionToLessOrEqual();
  2596. this.setDepthWrite(true);
  2597. this._onFullscreenChange = function () {
  2598. if (document.fullscreen !== undefined) {
  2599. _this.isFullscreen = document.fullscreen;
  2600. } else if (document.mozFullScreen !== undefined) {
  2601. _this.isFullscreen = document.mozFullScreen;
  2602. } else if (document.webkitIsFullScreen !== undefined) {
  2603. _this.isFullscreen = document.webkitIsFullScreen;
  2604. } else if (document.msIsFullScreen !== undefined) {
  2605. _this.isFullscreen = document.msIsFullScreen;
  2606. }
  2607. if (_this.isFullscreen && _this._pointerLockRequested) {
  2608. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  2609. if (canvas.requestPointerLock) {
  2610. canvas.requestPointerLock();
  2611. }
  2612. }
  2613. };
  2614. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  2615. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  2616. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  2617. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  2618. this._onPointerLockChange = function () {
  2619. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  2620. };
  2621. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  2622. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  2623. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  2624. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  2625. }
  2626. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  2627. get: function () {
  2628. return Engine._ALPHA_DISABLE;
  2629. },
  2630. enumerable: true,
  2631. configurable: true
  2632. });
  2633. Object.defineProperty(Engine, "ALPHA_ADD", {
  2634. get: function () {
  2635. return Engine._ALPHA_ADD;
  2636. },
  2637. enumerable: true,
  2638. configurable: true
  2639. });
  2640. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  2641. get: function () {
  2642. return Engine._ALPHA_COMBINE;
  2643. },
  2644. enumerable: true,
  2645. configurable: true
  2646. });
  2647. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  2648. get: function () {
  2649. return Engine._DELAYLOADSTATE_NONE;
  2650. },
  2651. enumerable: true,
  2652. configurable: true
  2653. });
  2654. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  2655. get: function () {
  2656. return Engine._DELAYLOADSTATE_LOADED;
  2657. },
  2658. enumerable: true,
  2659. configurable: true
  2660. });
  2661. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  2662. get: function () {
  2663. return Engine._DELAYLOADSTATE_LOADING;
  2664. },
  2665. enumerable: true,
  2666. configurable: true
  2667. });
  2668. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  2669. get: function () {
  2670. return Engine._DELAYLOADSTATE_NOTLOADED;
  2671. },
  2672. enumerable: true,
  2673. configurable: true
  2674. });
  2675. Object.defineProperty(Engine, "Version", {
  2676. get: function () {
  2677. return "1.14.0";
  2678. },
  2679. enumerable: true,
  2680. configurable: true
  2681. });
  2682. Engine.prototype.getAspectRatio = function (camera) {
  2683. var viewport = camera.viewport;
  2684. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  2685. };
  2686. Engine.prototype.getRenderWidth = function () {
  2687. if (this._currentRenderTarget) {
  2688. return this._currentRenderTarget._width;
  2689. }
  2690. return this._renderingCanvas.width;
  2691. };
  2692. Engine.prototype.getRenderHeight = function () {
  2693. if (this._currentRenderTarget) {
  2694. return this._currentRenderTarget._height;
  2695. }
  2696. return this._renderingCanvas.height;
  2697. };
  2698. Engine.prototype.getRenderingCanvas = function () {
  2699. return this._renderingCanvas;
  2700. };
  2701. Engine.prototype.getRenderingCanvasClientRect = function () {
  2702. return this._renderingCanvas.getBoundingClientRect();
  2703. };
  2704. Engine.prototype.setHardwareScalingLevel = function (level) {
  2705. this._hardwareScalingLevel = level;
  2706. this.resize();
  2707. };
  2708. Engine.prototype.getHardwareScalingLevel = function () {
  2709. return this._hardwareScalingLevel;
  2710. };
  2711. Engine.prototype.getLoadedTexturesCache = function () {
  2712. return this._loadedTexturesCache;
  2713. };
  2714. Engine.prototype.getCaps = function () {
  2715. return this._caps;
  2716. };
  2717. Engine.prototype.setDepthFunctionToGreater = function () {
  2718. this._depthCullingState.depthFunc = this._gl.GREATER;
  2719. };
  2720. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  2721. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  2722. };
  2723. Engine.prototype.setDepthFunctionToLess = function () {
  2724. this._depthCullingState.depthFunc = this._gl.LESS;
  2725. };
  2726. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  2727. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  2728. };
  2729. Engine.prototype.stopRenderLoop = function () {
  2730. this._renderFunction = null;
  2731. this._runningLoop = false;
  2732. };
  2733. Engine.prototype._renderLoop = function () {
  2734. var _this = this;
  2735. var shouldRender = true;
  2736. if (!this.renderEvenInBackground && this._windowIsBackground) {
  2737. shouldRender = false;
  2738. }
  2739. if (shouldRender) {
  2740. this.beginFrame();
  2741. if (this._renderFunction) {
  2742. this._renderFunction();
  2743. }
  2744. this.endFrame();
  2745. }
  2746. if (this._runningLoop) {
  2747. BABYLON.Tools.QueueNewFrame(function () {
  2748. _this._renderLoop();
  2749. });
  2750. }
  2751. };
  2752. Engine.prototype.runRenderLoop = function (renderFunction) {
  2753. var _this = this;
  2754. this._runningLoop = true;
  2755. this._renderFunction = renderFunction;
  2756. BABYLON.Tools.QueueNewFrame(function () {
  2757. _this._renderLoop();
  2758. });
  2759. };
  2760. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  2761. if (this.isFullscreen) {
  2762. BABYLON.Tools.ExitFullscreen();
  2763. } else {
  2764. this._pointerLockRequested = requestPointerLock;
  2765. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  2766. }
  2767. };
  2768. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  2769. this.applyStates();
  2770. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  2771. if (this._depthCullingState.depthMask) {
  2772. this._gl.clearDepth(1.0);
  2773. }
  2774. var mode = 0;
  2775. if (backBuffer)
  2776. mode |= this._gl.COLOR_BUFFER_BIT;
  2777. if (depthStencil && this._depthCullingState.depthMask)
  2778. mode |= this._gl.DEPTH_BUFFER_BIT;
  2779. this._gl.clear(mode);
  2780. };
  2781. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  2782. var width = requiredWidth || this._renderingCanvas.width;
  2783. var height = requiredHeight || this._renderingCanvas.height;
  2784. var x = viewport.x || 0;
  2785. var y = viewport.y || 0;
  2786. this._cachedViewport = viewport;
  2787. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  2788. };
  2789. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  2790. this._cachedViewport = null;
  2791. this._gl.viewport(x, y, width, height);
  2792. };
  2793. Engine.prototype.beginFrame = function () {
  2794. BABYLON.Tools._MeasureFps();
  2795. };
  2796. Engine.prototype.endFrame = function () {
  2797. this.flushFramebuffer();
  2798. };
  2799. Engine.prototype.resize = function () {
  2800. this._renderingCanvas.width = this._renderingCanvas.clientWidth / this._hardwareScalingLevel;
  2801. this._renderingCanvas.height = this._renderingCanvas.clientHeight / this._hardwareScalingLevel;
  2802. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2803. };
  2804. Engine.prototype.bindFramebuffer = function (texture) {
  2805. this._currentRenderTarget = texture;
  2806. var gl = this._gl;
  2807. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  2808. this._gl.viewport(0, 0, texture._width, texture._height);
  2809. this.wipeCaches();
  2810. };
  2811. Engine.prototype.unBindFramebuffer = function (texture) {
  2812. this._currentRenderTarget = null;
  2813. if (texture.generateMipMaps) {
  2814. var gl = this._gl;
  2815. gl.bindTexture(gl.TEXTURE_2D, texture);
  2816. gl.generateMipmap(gl.TEXTURE_2D);
  2817. gl.bindTexture(gl.TEXTURE_2D, null);
  2818. }
  2819. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2820. };
  2821. Engine.prototype.flushFramebuffer = function () {
  2822. this._gl.flush();
  2823. };
  2824. Engine.prototype.restoreDefaultFramebuffer = function () {
  2825. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2826. this.setViewport(this._cachedViewport);
  2827. this.wipeCaches();
  2828. };
  2829. Engine.prototype._resetVertexBufferBinding = function () {
  2830. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  2831. this._cachedVertexBuffers = null;
  2832. };
  2833. Engine.prototype.createVertexBuffer = function (vertices) {
  2834. var vbo = this._gl.createBuffer();
  2835. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2836. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  2837. this._resetVertexBufferBinding();
  2838. vbo.references = 1;
  2839. return vbo;
  2840. };
  2841. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  2842. var vbo = this._gl.createBuffer();
  2843. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2844. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2845. this._resetVertexBufferBinding();
  2846. vbo.references = 1;
  2847. return vbo;
  2848. };
  2849. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, length) {
  2850. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2851. if (vertices instanceof Float32Array) {
  2852. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  2853. } else {
  2854. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  2855. }
  2856. this._resetVertexBufferBinding();
  2857. };
  2858. Engine.prototype._resetIndexBufferBinding = function () {
  2859. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  2860. this._cachedIndexBuffer = null;
  2861. };
  2862. Engine.prototype.createIndexBuffer = function (indices) {
  2863. var vbo = this._gl.createBuffer();
  2864. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  2865. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  2866. this._resetIndexBufferBinding();
  2867. vbo.references = 1;
  2868. return vbo;
  2869. };
  2870. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  2871. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  2872. this._cachedVertexBuffers = vertexBuffer;
  2873. this._cachedEffectForVertexBuffers = effect;
  2874. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2875. var offset = 0;
  2876. for (var index = 0; index < vertexDeclaration.length; index++) {
  2877. var order = effect.getAttributeLocation(index);
  2878. if (order >= 0) {
  2879. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  2880. }
  2881. offset += vertexDeclaration[index] * 4;
  2882. }
  2883. }
  2884. if (this._cachedIndexBuffer !== indexBuffer) {
  2885. this._cachedIndexBuffer = indexBuffer;
  2886. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2887. }
  2888. };
  2889. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  2890. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  2891. this._cachedVertexBuffers = vertexBuffers;
  2892. this._cachedEffectForVertexBuffers = effect;
  2893. var attributes = effect.getAttributesNames();
  2894. for (var index = 0; index < attributes.length; index++) {
  2895. var order = effect.getAttributeLocation(index);
  2896. if (order >= 0) {
  2897. var vertexBuffer = vertexBuffers[attributes[index]];
  2898. if (!vertexBuffer) {
  2899. continue;
  2900. }
  2901. var stride = vertexBuffer.getStrideSize();
  2902. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  2903. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  2904. }
  2905. }
  2906. }
  2907. if (this._cachedIndexBuffer !== indexBuffer) {
  2908. this._cachedIndexBuffer = indexBuffer;
  2909. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2910. }
  2911. };
  2912. Engine.prototype._releaseBuffer = function (buffer) {
  2913. buffer.references--;
  2914. if (buffer.references === 0) {
  2915. this._gl.deleteBuffer(buffer);
  2916. return true;
  2917. }
  2918. return false;
  2919. };
  2920. Engine.prototype.createInstancesBuffer = function (capacity) {
  2921. var buffer = this._gl.createBuffer();
  2922. buffer.capacity = capacity;
  2923. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  2924. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2925. return buffer;
  2926. };
  2927. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  2928. this._gl.deleteBuffer(buffer);
  2929. };
  2930. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  2931. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  2932. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2933. for (var index = 0; index < 4; index++) {
  2934. var offsetLocation = offsetLocations[index];
  2935. this._gl.enableVertexAttribArray(offsetLocation);
  2936. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  2937. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  2938. }
  2939. };
  2940. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  2941. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  2942. for (var index = 0; index < 4; index++) {
  2943. var offsetLocation = offsetLocations[index];
  2944. this._gl.disableVertexAttribArray(offsetLocation);
  2945. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  2946. }
  2947. };
  2948. Engine.prototype.applyStates = function () {
  2949. this._depthCullingState.apply(this._gl);
  2950. this._alphaState.apply(this._gl);
  2951. };
  2952. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  2953. this.applyStates();
  2954. if (instancesCount) {
  2955. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2, instancesCount);
  2956. return;
  2957. }
  2958. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  2959. };
  2960. Engine.prototype._releaseEffect = function (effect) {
  2961. if (this._compiledEffects[effect._key]) {
  2962. delete this._compiledEffects[effect._key];
  2963. if (effect.getProgram()) {
  2964. this._gl.deleteProgram(effect.getProgram());
  2965. }
  2966. }
  2967. };
  2968. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  2969. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  2970. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  2971. var name = vertex + "+" + fragment + "@" + defines;
  2972. if (this._compiledEffects[name]) {
  2973. return this._compiledEffects[name];
  2974. }
  2975. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  2976. effect._key = name;
  2977. this._compiledEffects[name] = effect;
  2978. return effect;
  2979. };
  2980. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  2981. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  2982. if (typeof samplers === "undefined") { samplers = []; }
  2983. if (typeof defines === "undefined") { defines = ""; }
  2984. return this.createEffect({
  2985. vertex: "particles",
  2986. fragmentElement: fragmentName
  2987. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  2988. };
  2989. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  2990. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  2991. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  2992. var shaderProgram = this._gl.createProgram();
  2993. this._gl.attachShader(shaderProgram, vertexShader);
  2994. this._gl.attachShader(shaderProgram, fragmentShader);
  2995. this._gl.linkProgram(shaderProgram);
  2996. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  2997. if (!linked) {
  2998. var error = this._gl.getProgramInfoLog(shaderProgram);
  2999. if (error) {
  3000. throw new Error(error);
  3001. }
  3002. }
  3003. this._gl.deleteShader(vertexShader);
  3004. this._gl.deleteShader(fragmentShader);
  3005. return shaderProgram;
  3006. };
  3007. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3008. var results = [];
  3009. for (var index = 0; index < uniformsNames.length; index++) {
  3010. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3011. }
  3012. return results;
  3013. };
  3014. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3015. var results = [];
  3016. for (var index = 0; index < attributesNames.length; index++) {
  3017. try {
  3018. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3019. } catch (e) {
  3020. results.push(-1);
  3021. }
  3022. }
  3023. return results;
  3024. };
  3025. Engine.prototype.enableEffect = function (effect) {
  3026. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3027. return;
  3028. }
  3029. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3030. this._gl.useProgram(effect.getProgram());
  3031. for (var i in this._vertexAttribArrays) {
  3032. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3033. continue;
  3034. }
  3035. this._vertexAttribArrays[i] = false;
  3036. this._gl.disableVertexAttribArray(i);
  3037. }
  3038. var attributesCount = effect.getAttributesCount();
  3039. for (var index = 0; index < attributesCount; index++) {
  3040. var order = effect.getAttributeLocation(index);
  3041. if (order >= 0) {
  3042. this._vertexAttribArrays[order] = true;
  3043. this._gl.enableVertexAttribArray(order);
  3044. }
  3045. }
  3046. this._currentEffect = effect;
  3047. };
  3048. Engine.prototype.setArray = function (uniform, array) {
  3049. if (!uniform)
  3050. return;
  3051. this._gl.uniform1fv(uniform, array);
  3052. };
  3053. Engine.prototype.setMatrices = function (uniform, matrices) {
  3054. if (!uniform)
  3055. return;
  3056. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3057. };
  3058. Engine.prototype.setMatrix = function (uniform, matrix) {
  3059. if (!uniform)
  3060. return;
  3061. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3062. };
  3063. Engine.prototype.setFloat = function (uniform, value) {
  3064. if (!uniform)
  3065. return;
  3066. this._gl.uniform1f(uniform, value);
  3067. };
  3068. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3069. if (!uniform)
  3070. return;
  3071. this._gl.uniform2f(uniform, x, y);
  3072. };
  3073. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3074. if (!uniform)
  3075. return;
  3076. this._gl.uniform3f(uniform, x, y, z);
  3077. };
  3078. Engine.prototype.setBool = function (uniform, bool) {
  3079. if (!uniform)
  3080. return;
  3081. this._gl.uniform1i(uniform, bool);
  3082. };
  3083. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3084. if (!uniform)
  3085. return;
  3086. this._gl.uniform4f(uniform, x, y, z, w);
  3087. };
  3088. Engine.prototype.setColor3 = function (uniform, color3) {
  3089. if (!uniform)
  3090. return;
  3091. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3092. };
  3093. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3094. if (!uniform)
  3095. return;
  3096. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3097. };
  3098. Engine.prototype.setState = function (culling, force) {
  3099. if (this._depthCullingState.cull !== culling || force) {
  3100. if (culling) {
  3101. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3102. this._depthCullingState.cull = true;
  3103. } else {
  3104. this._depthCullingState.cull = false;
  3105. }
  3106. }
  3107. };
  3108. Engine.prototype.setDepthBuffer = function (enable) {
  3109. this._depthCullingState.depthTest = enable;
  3110. };
  3111. Engine.prototype.getDepthWrite = function () {
  3112. return this._depthCullingState.depthMask;
  3113. };
  3114. Engine.prototype.setDepthWrite = function (enable) {
  3115. this._depthCullingState.depthMask = enable;
  3116. };
  3117. Engine.prototype.setColorWrite = function (enable) {
  3118. this._gl.colorMask(enable, enable, enable, enable);
  3119. };
  3120. Engine.prototype.setAlphaMode = function (mode) {
  3121. switch (mode) {
  3122. case BABYLON.Engine.ALPHA_DISABLE:
  3123. this.setDepthWrite(true);
  3124. this._alphaState.alphaBlend = false;
  3125. break;
  3126. case BABYLON.Engine.ALPHA_COMBINE:
  3127. this.setDepthWrite(false);
  3128. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3129. this._alphaState.alphaBlend = true;
  3130. break;
  3131. case BABYLON.Engine.ALPHA_ADD:
  3132. this.setDepthWrite(false);
  3133. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3134. this._alphaState.alphaBlend = true;
  3135. break;
  3136. }
  3137. };
  3138. Engine.prototype.setAlphaTesting = function (enable) {
  3139. this._alphaTest = enable;
  3140. };
  3141. Engine.prototype.getAlphaTesting = function () {
  3142. return this._alphaTest;
  3143. };
  3144. Engine.prototype.wipeCaches = function () {
  3145. this._activeTexturesCache = [];
  3146. this._currentEffect = null;
  3147. this._depthCullingState.reset();
  3148. this._alphaState.reset();
  3149. this._cachedVertexBuffers = null;
  3150. this._cachedIndexBuffer = null;
  3151. this._cachedEffectForVertexBuffers = null;
  3152. };
  3153. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3154. var gl = this._gl;
  3155. gl.bindTexture(gl.TEXTURE_2D, texture);
  3156. var magFilter = gl.NEAREST;
  3157. var minFilter = gl.NEAREST;
  3158. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3159. magFilter = gl.LINEAR;
  3160. minFilter = gl.LINEAR;
  3161. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3162. magFilter = gl.LINEAR;
  3163. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3164. }
  3165. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3166. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3167. gl.bindTexture(gl.TEXTURE_2D, null);
  3168. };
  3169. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  3170. var _this = this;
  3171. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3172. if (typeof onLoad === "undefined") { onLoad = null; }
  3173. if (typeof onError === "undefined") { onError = null; }
  3174. if (typeof buffer === "undefined") { buffer = null; }
  3175. var texture = this._gl.createTexture();
  3176. var extension;
  3177. var fromData = false;
  3178. if (url.substr(0, 5) === "data:") {
  3179. fromData = true;
  3180. }
  3181. if (!fromData)
  3182. extension = url.substr(url.length - 4, 4).toLowerCase();
  3183. else {
  3184. var oldUrl = url;
  3185. fromData = oldUrl.split(':');
  3186. url = oldUrl;
  3187. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  3188. }
  3189. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3190. var isTGA = (extension === ".tga");
  3191. scene._addPendingData(texture);
  3192. texture.url = url;
  3193. texture.noMipmap = noMipmap;
  3194. texture.references = 1;
  3195. this._loadedTexturesCache.push(texture);
  3196. var onerror = function () {
  3197. scene._removePendingData(texture);
  3198. if (onError) {
  3199. onError();
  3200. }
  3201. };
  3202. if (isTGA) {
  3203. var callback = function (arrayBuffer) {
  3204. var data = new Uint8Array(arrayBuffer);
  3205. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3206. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3207. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3208. if (onLoad) {
  3209. onLoad();
  3210. }
  3211. }, samplingMode);
  3212. };
  3213. if (!(fromData instanceof Array))
  3214. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3215. callback(arrayBuffer);
  3216. }, onerror, scene.database, true);
  3217. else
  3218. callback(buffer);
  3219. } else if (isDDS) {
  3220. var callback = function (data) {
  3221. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3222. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3223. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3224. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3225. if (onLoad) {
  3226. onLoad();
  3227. }
  3228. }, samplingMode);
  3229. };
  3230. if (!(fromData instanceof Array))
  3231. BABYLON.Tools.LoadFile(url, function (data) {
  3232. callback(data);
  3233. }, onerror, scene.database, true);
  3234. else
  3235. callback(buffer);
  3236. } else {
  3237. var onload = function (img) {
  3238. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3239. var isPot = (img.width == potWidth && img.height == potHeight);
  3240. if (!isPot) {
  3241. _this._workingCanvas.width = potWidth;
  3242. _this._workingCanvas.height = potHeight;
  3243. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3244. }
  3245. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3246. if (onLoad) {
  3247. onLoad();
  3248. }
  3249. }, samplingMode);
  3250. };
  3251. if (!(fromData instanceof Array))
  3252. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3253. else
  3254. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  3255. }
  3256. return texture;
  3257. };
  3258. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  3259. var texture = this._gl.createTexture();
  3260. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  3261. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  3262. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3263. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3264. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3265. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3266. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3267. this._activeTexturesCache = [];
  3268. texture._baseWidth = width;
  3269. texture._baseHeight = height;
  3270. texture._width = width;
  3271. texture._height = height;
  3272. texture.isReady = false;
  3273. texture.generateMipMaps = generateMipMaps;
  3274. texture.references = 1;
  3275. this._loadedTexturesCache.push(texture);
  3276. return texture;
  3277. };
  3278. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  3279. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3280. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3281. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  3282. if (texture.generateMipMaps) {
  3283. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3284. }
  3285. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3286. this._activeTexturesCache = [];
  3287. texture.isReady = true;
  3288. };
  3289. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  3290. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3291. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1);
  3292. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  3293. if (!texture._workingCanvas) {
  3294. texture._workingCanvas = document.createElement("canvas");
  3295. texture._workingContext = texture._workingCanvas.getContext("2d");
  3296. texture._workingCanvas.width = texture._width;
  3297. texture._workingCanvas.height = texture._height;
  3298. }
  3299. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  3300. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3301. } else {
  3302. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3303. }
  3304. if (texture.generateMipMaps) {
  3305. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3306. }
  3307. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3308. this._activeTexturesCache = [];
  3309. texture.isReady = true;
  3310. };
  3311. Engine.prototype.createRenderTargetTexture = function (size, options) {
  3312. var generateMipMaps = false;
  3313. var generateDepthBuffer = true;
  3314. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3315. if (options !== undefined) {
  3316. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  3317. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3318. if (options.samplingMode !== undefined) {
  3319. samplingMode = options.samplingMode;
  3320. }
  3321. }
  3322. var gl = this._gl;
  3323. var texture = gl.createTexture();
  3324. gl.bindTexture(gl.TEXTURE_2D, texture);
  3325. var width = size.width || size;
  3326. var height = size.height || size;
  3327. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3328. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3329. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3330. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3331. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3332. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  3333. var depthBuffer;
  3334. if (generateDepthBuffer) {
  3335. depthBuffer = gl.createRenderbuffer();
  3336. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  3337. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3338. }
  3339. var framebuffer = gl.createFramebuffer();
  3340. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  3341. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3342. if (generateDepthBuffer) {
  3343. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  3344. }
  3345. gl.bindTexture(gl.TEXTURE_2D, null);
  3346. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3347. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3348. texture._framebuffer = framebuffer;
  3349. if (generateDepthBuffer) {
  3350. texture._depthBuffer = depthBuffer;
  3351. }
  3352. texture._width = width;
  3353. texture._height = height;
  3354. texture.isReady = true;
  3355. texture.generateMipMaps = generateMipMaps;
  3356. texture.references = 1;
  3357. this._activeTexturesCache = [];
  3358. this._loadedTexturesCache.push(texture);
  3359. return texture;
  3360. };
  3361. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  3362. var _this = this;
  3363. var gl = this._gl;
  3364. var texture = gl.createTexture();
  3365. texture.isCube = true;
  3366. texture.url = rootUrl;
  3367. texture.references = 1;
  3368. this._loadedTexturesCache.push(texture);
  3369. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  3370. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3371. if (isDDS) {
  3372. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  3373. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3374. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3375. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3376. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3377. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  3378. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  3379. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3380. }
  3381. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3382. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3383. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3384. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3385. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3386. _this._activeTexturesCache = [];
  3387. texture._width = info.width;
  3388. texture._height = info.height;
  3389. texture.isReady = true;
  3390. }, null, null, true);
  3391. } else {
  3392. cascadeLoad(rootUrl, scene, function (imgs) {
  3393. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  3394. var height = width;
  3395. _this._workingCanvas.width = width;
  3396. _this._workingCanvas.height = height;
  3397. var faces = [
  3398. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3399. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3400. ];
  3401. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3402. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3403. for (var index = 0; index < faces.length; index++) {
  3404. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3405. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  3406. }
  3407. if (!noMipmap) {
  3408. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3409. }
  3410. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3411. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  3412. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3413. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3414. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3415. _this._activeTexturesCache = [];
  3416. texture._width = width;
  3417. texture._height = height;
  3418. texture.isReady = true;
  3419. }, extensions);
  3420. }
  3421. return texture;
  3422. };
  3423. Engine.prototype._releaseTexture = function (texture) {
  3424. var gl = this._gl;
  3425. if (texture._framebuffer) {
  3426. gl.deleteFramebuffer(texture._framebuffer);
  3427. }
  3428. if (texture._depthBuffer) {
  3429. gl.deleteRenderbuffer(texture._depthBuffer);
  3430. }
  3431. gl.deleteTexture(texture);
  3432. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3433. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3434. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3435. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3436. this._activeTexturesCache[channel] = null;
  3437. }
  3438. var index = this._loadedTexturesCache.indexOf(texture);
  3439. if (index !== -1) {
  3440. this._loadedTexturesCache.splice(index, 1);
  3441. }
  3442. };
  3443. Engine.prototype.bindSamplers = function (effect) {
  3444. this._gl.useProgram(effect.getProgram());
  3445. var samplers = effect.getSamplers();
  3446. for (var index = 0; index < samplers.length; index++) {
  3447. var uniform = effect.getUniform(samplers[index]);
  3448. this._gl.uniform1i(uniform, index);
  3449. }
  3450. this._currentEffect = null;
  3451. };
  3452. Engine.prototype._bindTexture = function (channel, texture) {
  3453. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3454. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3455. this._activeTexturesCache[channel] = null;
  3456. };
  3457. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  3458. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3459. };
  3460. Engine.prototype.setTexture = function (channel, texture) {
  3461. if (channel < 0) {
  3462. return;
  3463. }
  3464. if (!texture || !texture.isReady()) {
  3465. if (this._activeTexturesCache[channel] != null) {
  3466. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3467. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3468. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3469. this._activeTexturesCache[channel] = null;
  3470. }
  3471. return;
  3472. }
  3473. if (texture instanceof BABYLON.VideoTexture) {
  3474. if (texture.update()) {
  3475. this._activeTexturesCache[channel] = null;
  3476. }
  3477. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  3478. texture.delayLoad();
  3479. return;
  3480. }
  3481. if (this._activeTexturesCache[channel] == texture) {
  3482. return;
  3483. }
  3484. this._activeTexturesCache[channel] = texture;
  3485. var internalTexture = texture.getInternalTexture();
  3486. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3487. if (internalTexture.isCube) {
  3488. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3489. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3490. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3491. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3492. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3493. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3494. }
  3495. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3496. } else {
  3497. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  3498. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3499. internalTexture._cachedWrapU = texture.wrapU;
  3500. switch (texture.wrapU) {
  3501. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3502. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3503. break;
  3504. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3505. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3506. break;
  3507. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3508. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3509. break;
  3510. }
  3511. }
  3512. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3513. internalTexture._cachedWrapV = texture.wrapV;
  3514. switch (texture.wrapV) {
  3515. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3516. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3517. break;
  3518. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3519. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  3520. break;
  3521. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3522. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  3523. break;
  3524. }
  3525. }
  3526. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3527. }
  3528. };
  3529. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  3530. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3531. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  3532. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  3533. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  3534. }
  3535. };
  3536. Engine.prototype.readPixels = function (x, y, width, height) {
  3537. var data = new Uint8Array(height * width * 4);
  3538. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  3539. return data;
  3540. };
  3541. Engine.prototype.dispose = function () {
  3542. this.hideLoadingUI();
  3543. this.stopRenderLoop();
  3544. while (this.scenes.length) {
  3545. this.scenes[0].dispose();
  3546. }
  3547. for (var name in this._compiledEffects) {
  3548. this._gl.deleteProgram(this._compiledEffects[name]._program);
  3549. }
  3550. for (var i in this._vertexAttribArrays) {
  3551. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3552. continue;
  3553. }
  3554. this._gl.disableVertexAttribArray(i);
  3555. }
  3556. window.removeEventListener("blur", this._onBlur);
  3557. window.removeEventListener("focus", this._onFocus);
  3558. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  3559. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  3560. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  3561. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  3562. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  3563. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  3564. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  3565. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  3566. };
  3567. Engine.prototype.displayLoadingUI = function () {
  3568. var _this = this;
  3569. this._loadingDiv = document.createElement("div");
  3570. this._loadingDiv.style.opacity = "0";
  3571. this._loadingDiv.style.transition = "opacity 1.5s ease";
  3572. this._loadingTextDiv = document.createElement("div");
  3573. this._loadingTextDiv.style.position = "absolute";
  3574. this._loadingTextDiv.style.left = "0";
  3575. this._loadingTextDiv.style.top = "50%";
  3576. this._loadingTextDiv.style.marginTop = "80px";
  3577. this._loadingTextDiv.style.width = "100%";
  3578. this._loadingTextDiv.style.height = "20px";
  3579. this._loadingTextDiv.style.fontFamily = "Arial";
  3580. this._loadingTextDiv.style.fontSize = "14px";
  3581. this._loadingTextDiv.style.color = "white";
  3582. this._loadingTextDiv.style.textAlign = "center";
  3583. this._loadingTextDiv.innerHTML = "Loading";
  3584. this._loadingDiv.appendChild(this._loadingTextDiv);
  3585. var imgBack = new Image();
  3586. 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==";
  3587. imgBack.style.position = "absolute";
  3588. imgBack.style.left = "50%";
  3589. imgBack.style.top = "50%";
  3590. imgBack.style.marginLeft = "-50px";
  3591. imgBack.style.marginTop = "-50px";
  3592. imgBack.style.transition = "transform 1.0s ease";
  3593. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  3594. var deg = 360;
  3595. var onTransitionEnd = function () {
  3596. deg += 360;
  3597. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  3598. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  3599. };
  3600. imgBack.addEventListener("transitionend", onTransitionEnd);
  3601. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  3602. this._loadingDiv.appendChild(imgBack);
  3603. var imgFront = new Image();
  3604. 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=";
  3605. imgFront.style.position = "absolute";
  3606. imgFront.style.left = "50%";
  3607. imgFront.style.top = "50%";
  3608. imgFront.style.marginLeft = "-50px";
  3609. imgFront.style.marginTop = "-50px";
  3610. this._loadingDiv.appendChild(imgFront);
  3611. this._resizeLoadingUI = function () {
  3612. var canvasRect = _this.getRenderingCanvasClientRect();
  3613. _this._loadingDiv.style.position = "absolute";
  3614. _this._loadingDiv.style.left = canvasRect.left + "px";
  3615. _this._loadingDiv.style.top = canvasRect.top + "px";
  3616. _this._loadingDiv.style.width = canvasRect.width + "px";
  3617. _this._loadingDiv.style.height = canvasRect.height + "px";
  3618. };
  3619. this._resizeLoadingUI();
  3620. window.addEventListener("resize", this._resizeLoadingUI);
  3621. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3622. document.body.appendChild(this._loadingDiv);
  3623. setTimeout(function () {
  3624. _this._loadingDiv.style.opacity = "1";
  3625. imgBack.style.transform = "rotateZ(360deg)";
  3626. imgBack.style.webkitTransform = "rotateZ(360deg)";
  3627. }, 0);
  3628. };
  3629. Object.defineProperty(Engine.prototype, "loadingUIText", {
  3630. set: function (text) {
  3631. if (!this._loadingDiv) {
  3632. return;
  3633. }
  3634. this._loadingTextDiv.innerHTML = text;
  3635. },
  3636. enumerable: true,
  3637. configurable: true
  3638. });
  3639. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  3640. get: function () {
  3641. return this._loadingDivBackgroundColor;
  3642. },
  3643. set: function (color) {
  3644. this._loadingDivBackgroundColor = color;
  3645. if (!this._loadingDiv) {
  3646. return;
  3647. }
  3648. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3649. },
  3650. enumerable: true,
  3651. configurable: true
  3652. });
  3653. Engine.prototype.hideLoadingUI = function () {
  3654. var _this = this;
  3655. if (!this._loadingDiv) {
  3656. return;
  3657. }
  3658. var onTransitionEnd = function () {
  3659. if (!_this._loadingDiv) {
  3660. return;
  3661. }
  3662. document.body.removeChild(_this._loadingDiv);
  3663. window.removeEventListener("resize", _this._resizeLoadingUI);
  3664. _this._loadingDiv = null;
  3665. };
  3666. this._loadingDiv.style.opacity = "0";
  3667. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  3668. };
  3669. Engine.isSupported = function () {
  3670. try {
  3671. var tempcanvas = document.createElement("canvas");
  3672. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  3673. return gl != null && !!window.WebGLRenderingContext;
  3674. } catch (e) {
  3675. return false;
  3676. }
  3677. };
  3678. Engine._ALPHA_DISABLE = 0;
  3679. Engine._ALPHA_ADD = 1;
  3680. Engine._ALPHA_COMBINE = 2;
  3681. Engine._DELAYLOADSTATE_NONE = 0;
  3682. Engine._DELAYLOADSTATE_LOADED = 1;
  3683. Engine._DELAYLOADSTATE_LOADING = 2;
  3684. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  3685. Engine.Epsilon = 0.001;
  3686. Engine.CollisionsEpsilon = 0.001;
  3687. Engine.ShadersRepository = "Babylon/Shaders/";
  3688. return Engine;
  3689. })();
  3690. BABYLON.Engine = Engine;
  3691. })(BABYLON || (BABYLON = {}));
  3692. var BABYLON;
  3693. (function (BABYLON) {
  3694. var Node = (function () {
  3695. function Node(name, scene) {
  3696. this.state = "";
  3697. this.animations = new Array();
  3698. this._childrenFlag = -1;
  3699. this._isEnabled = true;
  3700. this._isReady = true;
  3701. this._currentRenderId = -1;
  3702. this.name = name;
  3703. this.id = name;
  3704. this._scene = scene;
  3705. this._initCache();
  3706. }
  3707. Node.prototype.getScene = function () {
  3708. return this._scene;
  3709. };
  3710. Node.prototype.getEngine = function () {
  3711. return this._scene.getEngine();
  3712. };
  3713. Node.prototype.getWorldMatrix = function () {
  3714. return BABYLON.Matrix.Identity();
  3715. };
  3716. Node.prototype._initCache = function () {
  3717. this._cache = {};
  3718. this._cache.parent = undefined;
  3719. };
  3720. Node.prototype.updateCache = function (force) {
  3721. if (!force && this.isSynchronized())
  3722. return;
  3723. this._cache.parent = this.parent;
  3724. this._updateCache();
  3725. };
  3726. Node.prototype._updateCache = function (ignoreParentClass) {
  3727. };
  3728. Node.prototype._isSynchronized = function () {
  3729. return true;
  3730. };
  3731. Node.prototype.isSynchronizedWithParent = function () {
  3732. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  3733. };
  3734. Node.prototype.isSynchronized = function (updateCache) {
  3735. var check = this.hasNewParent();
  3736. check = check || !this.isSynchronizedWithParent();
  3737. check = check || !this._isSynchronized();
  3738. if (updateCache)
  3739. this.updateCache(true);
  3740. return !check;
  3741. };
  3742. Node.prototype.hasNewParent = function (update) {
  3743. if (this._cache.parent === this.parent)
  3744. return false;
  3745. if (update)
  3746. this._cache.parent = this.parent;
  3747. return true;
  3748. };
  3749. Node.prototype.isReady = function () {
  3750. return this._isReady;
  3751. };
  3752. Node.prototype.isEnabled = function () {
  3753. if (!this._isEnabled) {
  3754. return false;
  3755. }
  3756. if (this.parent) {
  3757. return this.parent.isEnabled();
  3758. }
  3759. return true;
  3760. };
  3761. Node.prototype.setEnabled = function (value) {
  3762. this._isEnabled = value;
  3763. };
  3764. Node.prototype.isDescendantOf = function (ancestor) {
  3765. if (this.parent) {
  3766. if (this.parent === ancestor) {
  3767. return true;
  3768. }
  3769. return this.parent.isDescendantOf(ancestor);
  3770. }
  3771. return false;
  3772. };
  3773. Node.prototype._getDescendants = function (list, results) {
  3774. for (var index = 0; index < list.length; index++) {
  3775. var item = list[index];
  3776. if (item.isDescendantOf(this)) {
  3777. results.push(item);
  3778. }
  3779. }
  3780. };
  3781. Node.prototype.getDescendants = function () {
  3782. var results = [];
  3783. this._getDescendants(this._scene.meshes, results);
  3784. this._getDescendants(this._scene.lights, results);
  3785. this._getDescendants(this._scene.cameras, results);
  3786. return results;
  3787. };
  3788. Node.prototype._setReady = function (state) {
  3789. if (state == this._isReady) {
  3790. return;
  3791. }
  3792. if (!state) {
  3793. this._isReady = false;
  3794. return;
  3795. }
  3796. this._isReady = true;
  3797. if (this.onReady) {
  3798. this.onReady(this);
  3799. }
  3800. };
  3801. return Node;
  3802. })();
  3803. BABYLON.Node = Node;
  3804. })(BABYLON || (BABYLON = {}));
  3805. var BABYLON;
  3806. (function (BABYLON) {
  3807. var BoundingSphere = (function () {
  3808. function BoundingSphere(minimum, maximum) {
  3809. this.minimum = minimum;
  3810. this.maximum = maximum;
  3811. this._tempRadiusVector = BABYLON.Vector3.Zero();
  3812. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  3813. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  3814. this.radius = distance * 0.5;
  3815. this.centerWorld = BABYLON.Vector3.Zero();
  3816. this._update(BABYLON.Matrix.Identity());
  3817. }
  3818. BoundingSphere.prototype._update = function (world) {
  3819. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  3820. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  3821. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  3822. };
  3823. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  3824. for (var i = 0; i < 6; i++) {
  3825. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  3826. return false;
  3827. }
  3828. return true;
  3829. };
  3830. BoundingSphere.prototype.intersectsPoint = function (point) {
  3831. var x = this.centerWorld.x - point.x;
  3832. var y = this.centerWorld.y - point.y;
  3833. var z = this.centerWorld.z - point.z;
  3834. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3835. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  3836. return false;
  3837. return true;
  3838. };
  3839. BoundingSphere.Intersects = function (sphere0, sphere1) {
  3840. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  3841. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  3842. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  3843. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3844. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  3845. return false;
  3846. return true;
  3847. };
  3848. return BoundingSphere;
  3849. })();
  3850. BABYLON.BoundingSphere = BoundingSphere;
  3851. })(BABYLON || (BABYLON = {}));
  3852. var BABYLON;
  3853. (function (BABYLON) {
  3854. var BoundingBox = (function () {
  3855. function BoundingBox(minimum, maximum) {
  3856. this.minimum = minimum;
  3857. this.maximum = maximum;
  3858. this.vectors = new Array();
  3859. this.vectorsWorld = new Array();
  3860. this.vectors.push(this.minimum.clone());
  3861. this.vectors.push(this.maximum.clone());
  3862. this.vectors.push(this.minimum.clone());
  3863. this.vectors[2].x = this.maximum.x;
  3864. this.vectors.push(this.minimum.clone());
  3865. this.vectors[3].y = this.maximum.y;
  3866. this.vectors.push(this.minimum.clone());
  3867. this.vectors[4].z = this.maximum.z;
  3868. this.vectors.push(this.maximum.clone());
  3869. this.vectors[5].z = this.minimum.z;
  3870. this.vectors.push(this.maximum.clone());
  3871. this.vectors[6].x = this.minimum.x;
  3872. this.vectors.push(this.maximum.clone());
  3873. this.vectors[7].y = this.minimum.y;
  3874. this.center = this.maximum.add(this.minimum).scale(0.5);
  3875. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  3876. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  3877. for (var index = 0; index < this.vectors.length; index++) {
  3878. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  3879. }
  3880. this.minimumWorld = BABYLON.Vector3.Zero();
  3881. this.maximumWorld = BABYLON.Vector3.Zero();
  3882. this._update(BABYLON.Matrix.Identity());
  3883. }
  3884. BoundingBox.prototype.getWorldMatrix = function () {
  3885. return this._worldMatrix;
  3886. };
  3887. BoundingBox.prototype._update = function (world) {
  3888. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  3889. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  3890. for (var index = 0; index < this.vectors.length; index++) {
  3891. var v = this.vectorsWorld[index];
  3892. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  3893. if (v.x < this.minimumWorld.x)
  3894. this.minimumWorld.x = v.x;
  3895. if (v.y < this.minimumWorld.y)
  3896. this.minimumWorld.y = v.y;
  3897. if (v.z < this.minimumWorld.z)
  3898. this.minimumWorld.z = v.z;
  3899. if (v.x > this.maximumWorld.x)
  3900. this.maximumWorld.x = v.x;
  3901. if (v.y > this.maximumWorld.y)
  3902. this.maximumWorld.y = v.y;
  3903. if (v.z > this.maximumWorld.z)
  3904. this.maximumWorld.z = v.z;
  3905. }
  3906. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  3907. this.center.scaleInPlace(0.5);
  3908. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  3909. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  3910. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  3911. this._worldMatrix = world;
  3912. };
  3913. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  3914. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  3915. };
  3916. BoundingBox.prototype.intersectsPoint = function (point) {
  3917. var delta = BABYLON.Engine.Epsilon;
  3918. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  3919. return false;
  3920. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  3921. return false;
  3922. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  3923. return false;
  3924. return true;
  3925. };
  3926. BoundingBox.prototype.intersectsSphere = function (sphere) {
  3927. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  3928. };
  3929. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  3930. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  3931. return false;
  3932. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  3933. return false;
  3934. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  3935. return false;
  3936. return true;
  3937. };
  3938. BoundingBox.Intersects = function (box0, box1) {
  3939. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  3940. return false;
  3941. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  3942. return false;
  3943. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  3944. return false;
  3945. return true;
  3946. };
  3947. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  3948. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  3949. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  3950. return (num <= (sphereRadius * sphereRadius));
  3951. };
  3952. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  3953. for (var p = 0; p < 6; p++) {
  3954. var inCount = 8;
  3955. for (var i = 0; i < 8; i++) {
  3956. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  3957. --inCount;
  3958. } else {
  3959. break;
  3960. }
  3961. }
  3962. if (inCount == 0)
  3963. return false;
  3964. }
  3965. return true;
  3966. };
  3967. return BoundingBox;
  3968. })();
  3969. BABYLON.BoundingBox = BoundingBox;
  3970. })(BABYLON || (BABYLON = {}));
  3971. var BABYLON;
  3972. (function (BABYLON) {
  3973. var computeBoxExtents = function (axis, box) {
  3974. var p = BABYLON.Vector3.Dot(box.center, axis);
  3975. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  3976. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  3977. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  3978. var r = r0 + r1 + r2;
  3979. return {
  3980. min: p - r,
  3981. max: p + r
  3982. };
  3983. };
  3984. var extentsOverlap = function (min0, max0, min1, max1) {
  3985. return !(min0 > max1 || min1 > max0);
  3986. };
  3987. var axisOverlap = function (axis, box0, box1) {
  3988. var result0 = computeBoxExtents(axis, box0);
  3989. var result1 = computeBoxExtents(axis, box1);
  3990. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  3991. };
  3992. var BoundingInfo = (function () {
  3993. function BoundingInfo(minimum, maximum) {
  3994. this.minimum = minimum;
  3995. this.maximum = maximum;
  3996. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  3997. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  3998. }
  3999. BoundingInfo.prototype._update = function (world) {
  4000. this.boundingBox._update(world);
  4001. this.boundingSphere._update(world);
  4002. };
  4003. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  4004. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  4005. return false;
  4006. return this.boundingBox.isInFrustum(frustumPlanes);
  4007. };
  4008. BoundingInfo.prototype._checkCollision = function (collider) {
  4009. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  4010. };
  4011. BoundingInfo.prototype.intersectsPoint = function (point) {
  4012. if (!this.boundingSphere.centerWorld) {
  4013. return false;
  4014. }
  4015. if (!this.boundingSphere.intersectsPoint(point)) {
  4016. return false;
  4017. }
  4018. if (!this.boundingBox.intersectsPoint(point)) {
  4019. return false;
  4020. }
  4021. return true;
  4022. };
  4023. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  4024. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  4025. return false;
  4026. }
  4027. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  4028. return false;
  4029. }
  4030. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  4031. return false;
  4032. }
  4033. if (!precise) {
  4034. return true;
  4035. }
  4036. var box0 = this.boundingBox;
  4037. var box1 = boundingInfo.boundingBox;
  4038. if (!axisOverlap(box0.directions[0], box0, box1))
  4039. return false;
  4040. if (!axisOverlap(box0.directions[1], box0, box1))
  4041. return false;
  4042. if (!axisOverlap(box0.directions[2], box0, box1))
  4043. return false;
  4044. if (!axisOverlap(box1.directions[0], box0, box1))
  4045. return false;
  4046. if (!axisOverlap(box1.directions[1], box0, box1))
  4047. return false;
  4048. if (!axisOverlap(box1.directions[2], box0, box1))
  4049. return false;
  4050. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  4051. return false;
  4052. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  4053. return false;
  4054. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  4055. return false;
  4056. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  4057. return false;
  4058. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  4059. return false;
  4060. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  4061. return false;
  4062. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  4063. return false;
  4064. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  4065. return false;
  4066. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  4067. return false;
  4068. return true;
  4069. };
  4070. return BoundingInfo;
  4071. })();
  4072. BABYLON.BoundingInfo = BoundingInfo;
  4073. })(BABYLON || (BABYLON = {}));
  4074. var __extends = this.__extends || function (d, b) {
  4075. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4076. function __() { this.constructor = d; }
  4077. __.prototype = b.prototype;
  4078. d.prototype = new __();
  4079. };
  4080. var BABYLON;
  4081. (function (BABYLON) {
  4082. var Light = (function (_super) {
  4083. __extends(Light, _super);
  4084. function Light(name, scene) {
  4085. _super.call(this, name, scene);
  4086. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  4087. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  4088. this.intensity = 1.0;
  4089. this.range = Number.MAX_VALUE;
  4090. this.includedOnlyMeshes = new Array();
  4091. this.excludedMeshes = new Array();
  4092. this._excludedMeshesIds = new Array();
  4093. this._includedOnlyMeshesIds = new Array();
  4094. scene.lights.push(this);
  4095. }
  4096. Light.prototype.getShadowGenerator = function () {
  4097. return this._shadowGenerator;
  4098. };
  4099. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4100. };
  4101. Light.prototype._getWorldMatrix = function () {
  4102. return BABYLON.Matrix.Identity();
  4103. };
  4104. Light.prototype.canAffectMesh = function (mesh) {
  4105. if (!mesh) {
  4106. return true;
  4107. }
  4108. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4109. return false;
  4110. }
  4111. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4112. return false;
  4113. }
  4114. return true;
  4115. };
  4116. Light.prototype.getWorldMatrix = function () {
  4117. this._currentRenderId = this.getScene().getRenderId();
  4118. var worldMatrix = this._getWorldMatrix();
  4119. if (this.parent && this.parent.getWorldMatrix) {
  4120. if (!this._parentedWorldMatrix) {
  4121. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4122. }
  4123. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4124. return this._parentedWorldMatrix;
  4125. }
  4126. return worldMatrix;
  4127. };
  4128. Light.prototype.dispose = function () {
  4129. if (this._shadowGenerator) {
  4130. this._shadowGenerator.dispose();
  4131. this._shadowGenerator = null;
  4132. }
  4133. var index = this.getScene().lights.indexOf(this);
  4134. this.getScene().lights.splice(index, 1);
  4135. };
  4136. return Light;
  4137. })(BABYLON.Node);
  4138. BABYLON.Light = Light;
  4139. })(BABYLON || (BABYLON = {}));
  4140. var __extends = this.__extends || function (d, b) {
  4141. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4142. function __() { this.constructor = d; }
  4143. __.prototype = b.prototype;
  4144. d.prototype = new __();
  4145. };
  4146. var BABYLON;
  4147. (function (BABYLON) {
  4148. var PointLight = (function (_super) {
  4149. __extends(PointLight, _super);
  4150. function PointLight(name, position, scene) {
  4151. _super.call(this, name, scene);
  4152. this.position = position;
  4153. }
  4154. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  4155. if (this.parent && this.parent.getWorldMatrix) {
  4156. if (!this._transformedPosition) {
  4157. this._transformedPosition = BABYLON.Vector3.Zero();
  4158. }
  4159. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4160. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  4161. return;
  4162. }
  4163. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  4164. };
  4165. PointLight.prototype.getShadowGenerator = function () {
  4166. return null;
  4167. };
  4168. PointLight.prototype._getWorldMatrix = function () {
  4169. if (!this._worldMatrix) {
  4170. this._worldMatrix = BABYLON.Matrix.Identity();
  4171. }
  4172. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4173. return this._worldMatrix;
  4174. };
  4175. return PointLight;
  4176. })(BABYLON.Light);
  4177. BABYLON.PointLight = PointLight;
  4178. })(BABYLON || (BABYLON = {}));
  4179. var __extends = this.__extends || function (d, b) {
  4180. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4181. function __() { this.constructor = d; }
  4182. __.prototype = b.prototype;
  4183. d.prototype = new __();
  4184. };
  4185. var BABYLON;
  4186. (function (BABYLON) {
  4187. var SpotLight = (function (_super) {
  4188. __extends(SpotLight, _super);
  4189. function SpotLight(name, position, direction, angle, exponent, scene) {
  4190. _super.call(this, name, scene);
  4191. this.position = position;
  4192. this.direction = direction;
  4193. this.angle = angle;
  4194. this.exponent = exponent;
  4195. }
  4196. SpotLight.prototype.setDirectionToTarget = function (target) {
  4197. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4198. return this.direction;
  4199. };
  4200. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  4201. var normalizeDirection;
  4202. if (this.parent && this.parent.getWorldMatrix) {
  4203. if (!this._transformedDirection) {
  4204. this._transformedDirection = BABYLON.Vector3.Zero();
  4205. }
  4206. if (!this._transformedPosition) {
  4207. this._transformedPosition = BABYLON.Vector3.Zero();
  4208. }
  4209. var parentWorldMatrix = this.parent.getWorldMatrix();
  4210. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  4211. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  4212. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  4213. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  4214. } else {
  4215. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  4216. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4217. }
  4218. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  4219. };
  4220. SpotLight.prototype._getWorldMatrix = function () {
  4221. if (!this._worldMatrix) {
  4222. this._worldMatrix = BABYLON.Matrix.Identity();
  4223. }
  4224. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4225. return this._worldMatrix;
  4226. };
  4227. return SpotLight;
  4228. })(BABYLON.Light);
  4229. BABYLON.SpotLight = SpotLight;
  4230. })(BABYLON || (BABYLON = {}));
  4231. var __extends = this.__extends || function (d, b) {
  4232. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4233. function __() { this.constructor = d; }
  4234. __.prototype = b.prototype;
  4235. d.prototype = new __();
  4236. };
  4237. var BABYLON;
  4238. (function (BABYLON) {
  4239. var DirectionalLight = (function (_super) {
  4240. __extends(DirectionalLight, _super);
  4241. function DirectionalLight(name, direction, scene) {
  4242. _super.call(this, name, scene);
  4243. this.direction = direction;
  4244. this.position = direction.scale(-1);
  4245. }
  4246. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  4247. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4248. return this.direction;
  4249. };
  4250. DirectionalLight.prototype._computeTransformedPosition = function () {
  4251. if (this.parent && this.parent.getWorldMatrix) {
  4252. if (!this._transformedPosition) {
  4253. this._transformedPosition = BABYLON.Vector3.Zero();
  4254. }
  4255. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4256. return true;
  4257. }
  4258. return false;
  4259. };
  4260. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  4261. if (this.parent && this.parent.getWorldMatrix) {
  4262. if (!this._transformedDirection) {
  4263. this._transformedDirection = BABYLON.Vector3.Zero();
  4264. }
  4265. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  4266. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  4267. return;
  4268. }
  4269. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  4270. };
  4271. DirectionalLight.prototype._getWorldMatrix = function () {
  4272. if (!this._worldMatrix) {
  4273. this._worldMatrix = BABYLON.Matrix.Identity();
  4274. }
  4275. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4276. return this._worldMatrix;
  4277. };
  4278. return DirectionalLight;
  4279. })(BABYLON.Light);
  4280. BABYLON.DirectionalLight = DirectionalLight;
  4281. })(BABYLON || (BABYLON = {}));
  4282. var BABYLON;
  4283. (function (BABYLON) {
  4284. var ShadowGenerator = (function () {
  4285. function ShadowGenerator(mapSize, light) {
  4286. var _this = this;
  4287. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4288. this._darkness = 0;
  4289. this._transparencyShadow = false;
  4290. this._viewMatrix = BABYLON.Matrix.Zero();
  4291. this._projectionMatrix = BABYLON.Matrix.Zero();
  4292. this._transformMatrix = BABYLON.Matrix.Zero();
  4293. this._worldViewProjection = BABYLON.Matrix.Zero();
  4294. this._light = light;
  4295. this._scene = light.getScene();
  4296. light._shadowGenerator = this;
  4297. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  4298. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4299. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4300. this._shadowMap.renderParticles = false;
  4301. var renderSubMesh = function (subMesh) {
  4302. var mesh = subMesh.getRenderingMesh();
  4303. var scene = _this._scene;
  4304. var engine = scene.getEngine();
  4305. engine.setState(subMesh.getMaterial().backFaceCulling);
  4306. var batch = mesh._getInstancesRenderList(subMesh._id);
  4307. if (batch.mustReturn) {
  4308. return;
  4309. }
  4310. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  4311. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  4312. engine.enableEffect(_this._effect);
  4313. mesh._bind(subMesh, _this._effect, false);
  4314. var material = subMesh.getMaterial();
  4315. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  4316. if (material && material.needAlphaTesting()) {
  4317. var alphaTexture = material.getAlphaTestTexture();
  4318. _this._effect.setTexture("diffuseSampler", alphaTexture);
  4319. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  4320. }
  4321. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  4322. if (useBones) {
  4323. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  4324. }
  4325. if (hardwareInstancedRendering) {
  4326. mesh._renderWithInstances(subMesh, false, batch, _this._effect, engine);
  4327. } else {
  4328. if (batch.renderSelf[subMesh._id]) {
  4329. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  4330. mesh._draw(subMesh, true);
  4331. }
  4332. if (batch.visibleInstances[subMesh._id]) {
  4333. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  4334. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  4335. _this._effect.setMatrix("world", instance.getWorldMatrix());
  4336. mesh._draw(subMesh, true);
  4337. }
  4338. }
  4339. }
  4340. } else {
  4341. _this._shadowMap.resetRefreshCounter();
  4342. }
  4343. };
  4344. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  4345. var index;
  4346. for (index = 0; index < opaqueSubMeshes.length; index++) {
  4347. renderSubMesh(opaqueSubMeshes.data[index]);
  4348. }
  4349. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  4350. renderSubMesh(alphaTestSubMeshes.data[index]);
  4351. }
  4352. if (_this._transparencyShadow) {
  4353. for (index = 0; index < transparentSubMeshes.length; index++) {
  4354. renderSubMesh(transparentSubMeshes.data[index]);
  4355. }
  4356. }
  4357. };
  4358. }
  4359. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  4360. get: function () {
  4361. return ShadowGenerator._FILTER_NONE;
  4362. },
  4363. enumerable: true,
  4364. configurable: true
  4365. });
  4366. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  4367. get: function () {
  4368. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  4369. },
  4370. enumerable: true,
  4371. configurable: true
  4372. });
  4373. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  4374. get: function () {
  4375. return ShadowGenerator._FILTER_POISSONSAMPLING;
  4376. },
  4377. enumerable: true,
  4378. configurable: true
  4379. });
  4380. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  4381. get: function () {
  4382. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4383. },
  4384. set: function (value) {
  4385. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  4386. },
  4387. enumerable: true,
  4388. configurable: true
  4389. });
  4390. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  4391. get: function () {
  4392. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  4393. },
  4394. set: function (value) {
  4395. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  4396. },
  4397. enumerable: true,
  4398. configurable: true
  4399. });
  4400. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  4401. var defines = [];
  4402. if (this.useVarianceShadowMap) {
  4403. defines.push("#define VSM");
  4404. }
  4405. var attribs = [BABYLON.VertexBuffer.PositionKind];
  4406. var mesh = subMesh.getMesh();
  4407. var material = subMesh.getMaterial();
  4408. if (material && material.needAlphaTesting()) {
  4409. defines.push("#define ALPHATEST");
  4410. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  4411. attribs.push(BABYLON.VertexBuffer.UVKind);
  4412. defines.push("#define UV1");
  4413. }
  4414. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  4415. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  4416. defines.push("#define UV2");
  4417. }
  4418. }
  4419. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  4420. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  4421. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  4422. defines.push("#define BONES");
  4423. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  4424. }
  4425. if (useInstances) {
  4426. defines.push("#define INSTANCES");
  4427. attribs.push("world0");
  4428. attribs.push("world1");
  4429. attribs.push("world2");
  4430. attribs.push("world3");
  4431. }
  4432. var join = defines.join("\n");
  4433. if (this._cachedDefines != join) {
  4434. this._cachedDefines = join;
  4435. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  4436. }
  4437. return this._effect.isReady();
  4438. };
  4439. ShadowGenerator.prototype.getShadowMap = function () {
  4440. return this._shadowMap;
  4441. };
  4442. ShadowGenerator.prototype.getLight = function () {
  4443. return this._light;
  4444. };
  4445. ShadowGenerator.prototype.getTransformMatrix = function () {
  4446. var lightPosition = this._light.position;
  4447. var lightDirection = this._light.direction;
  4448. if (this._light._computeTransformedPosition()) {
  4449. lightPosition = this._light._transformedPosition;
  4450. }
  4451. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  4452. this._cachedPosition = lightPosition.clone();
  4453. this._cachedDirection = lightDirection.clone();
  4454. var activeCamera = this._scene.activeCamera;
  4455. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  4456. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  4457. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  4458. }
  4459. return this._transformMatrix;
  4460. };
  4461. ShadowGenerator.prototype.getDarkness = function () {
  4462. return this._darkness;
  4463. };
  4464. ShadowGenerator.prototype.setDarkness = function (darkness) {
  4465. if (darkness >= 1.0)
  4466. this._darkness = 1.0;
  4467. else if (darkness <= 0.0)
  4468. this._darkness = 0.0;
  4469. else
  4470. this._darkness = darkness;
  4471. };
  4472. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  4473. this._transparencyShadow = hasShadow;
  4474. };
  4475. ShadowGenerator.prototype.dispose = function () {
  4476. this._shadowMap.dispose();
  4477. };
  4478. ShadowGenerator._FILTER_NONE = 0;
  4479. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  4480. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  4481. return ShadowGenerator;
  4482. })();
  4483. BABYLON.ShadowGenerator = ShadowGenerator;
  4484. })(BABYLON || (BABYLON = {}));
  4485. var __extends = this.__extends || function (d, b) {
  4486. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4487. function __() { this.constructor = d; }
  4488. __.prototype = b.prototype;
  4489. d.prototype = new __();
  4490. };
  4491. var BABYLON;
  4492. (function (BABYLON) {
  4493. var HemisphericLight = (function (_super) {
  4494. __extends(HemisphericLight, _super);
  4495. function HemisphericLight(name, direction, scene) {
  4496. _super.call(this, name, scene);
  4497. this.direction = direction;
  4498. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  4499. }
  4500. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  4501. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  4502. return this.direction;
  4503. };
  4504. HemisphericLight.prototype.getShadowGenerator = function () {
  4505. return null;
  4506. };
  4507. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  4508. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4509. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  4510. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  4511. };
  4512. HemisphericLight.prototype._getWorldMatrix = function () {
  4513. if (!this._worldMatrix) {
  4514. this._worldMatrix = BABYLON.Matrix.Identity();
  4515. }
  4516. return this._worldMatrix;
  4517. };
  4518. return HemisphericLight;
  4519. })(BABYLON.Light);
  4520. BABYLON.HemisphericLight = HemisphericLight;
  4521. })(BABYLON || (BABYLON = {}));
  4522. var BABYLON;
  4523. (function (BABYLON) {
  4524. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  4525. if (boxMin.x > sphereCenter.x + sphereRadius)
  4526. return false;
  4527. if (sphereCenter.x - sphereRadius > boxMax.x)
  4528. return false;
  4529. if (boxMin.y > sphereCenter.y + sphereRadius)
  4530. return false;
  4531. if (sphereCenter.y - sphereRadius > boxMax.y)
  4532. return false;
  4533. if (boxMin.z > sphereCenter.z + sphereRadius)
  4534. return false;
  4535. if (sphereCenter.z - sphereRadius > boxMax.z)
  4536. return false;
  4537. return true;
  4538. };
  4539. var getLowestRoot = function (a, b, c, maxR) {
  4540. var determinant = b * b - 4.0 * a * c;
  4541. var result = { root: 0, found: false };
  4542. if (determinant < 0)
  4543. return result;
  4544. var sqrtD = Math.sqrt(determinant);
  4545. var r1 = (-b - sqrtD) / (2.0 * a);
  4546. var r2 = (-b + sqrtD) / (2.0 * a);
  4547. if (r1 > r2) {
  4548. var temp = r2;
  4549. r2 = r1;
  4550. r1 = temp;
  4551. }
  4552. if (r1 > 0 && r1 < maxR) {
  4553. result.root = r1;
  4554. result.found = true;
  4555. return result;
  4556. }
  4557. if (r2 > 0 && r2 < maxR) {
  4558. result.root = r2;
  4559. result.found = true;
  4560. return result;
  4561. }
  4562. return result;
  4563. };
  4564. var Collider = (function () {
  4565. function Collider() {
  4566. this.radius = new BABYLON.Vector3(1, 1, 1);
  4567. this.retry = 0;
  4568. this.basePointWorld = BABYLON.Vector3.Zero();
  4569. this.velocityWorld = BABYLON.Vector3.Zero();
  4570. this.normalizedVelocity = BABYLON.Vector3.Zero();
  4571. this._collisionPoint = BABYLON.Vector3.Zero();
  4572. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  4573. this._tempVector = BABYLON.Vector3.Zero();
  4574. this._tempVector2 = BABYLON.Vector3.Zero();
  4575. this._tempVector3 = BABYLON.Vector3.Zero();
  4576. this._tempVector4 = BABYLON.Vector3.Zero();
  4577. this._edge = BABYLON.Vector3.Zero();
  4578. this._baseToVertex = BABYLON.Vector3.Zero();
  4579. this._destinationPoint = BABYLON.Vector3.Zero();
  4580. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  4581. this._displacementVector = BABYLON.Vector3.Zero();
  4582. }
  4583. Collider.prototype._initialize = function (source, dir, e) {
  4584. this.velocity = dir;
  4585. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  4586. this.basePoint = source;
  4587. source.multiplyToRef(this.radius, this.basePointWorld);
  4588. dir.multiplyToRef(this.radius, this.velocityWorld);
  4589. this.velocityWorldLength = this.velocityWorld.length();
  4590. this.epsilon = e;
  4591. this.collisionFound = false;
  4592. };
  4593. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  4594. pa.subtractToRef(point, this._tempVector);
  4595. pb.subtractToRef(point, this._tempVector2);
  4596. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  4597. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4598. if (d < 0)
  4599. return false;
  4600. pc.subtractToRef(point, this._tempVector3);
  4601. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  4602. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4603. if (d < 0)
  4604. return false;
  4605. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  4606. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4607. return d >= 0;
  4608. };
  4609. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  4610. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  4611. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  4612. if (distance > this.velocityWorldLength + max + sphereRadius) {
  4613. return false;
  4614. }
  4615. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  4616. return false;
  4617. return true;
  4618. };
  4619. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  4620. var t0;
  4621. var embeddedInPlane = false;
  4622. if (!subMesh._trianglePlanes) {
  4623. subMesh._trianglePlanes = [];
  4624. }
  4625. if (!subMesh._trianglePlanes[faceIndex]) {
  4626. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  4627. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  4628. }
  4629. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  4630. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  4631. return;
  4632. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  4633. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  4634. if (normalDotVelocity == 0) {
  4635. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  4636. return;
  4637. embeddedInPlane = true;
  4638. t0 = 0;
  4639. } else {
  4640. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4641. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4642. if (t0 > t1) {
  4643. var temp = t1;
  4644. t1 = t0;
  4645. t0 = temp;
  4646. }
  4647. if (t0 > 1.0 || t1 < 0.0)
  4648. return;
  4649. if (t0 < 0)
  4650. t0 = 0;
  4651. if (t0 > 1.0)
  4652. t0 = 1.0;
  4653. }
  4654. this._collisionPoint.copyFromFloats(0, 0, 0);
  4655. var found = false;
  4656. var t = 1.0;
  4657. if (!embeddedInPlane) {
  4658. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  4659. this.velocity.scaleToRef(t0, this._tempVector);
  4660. this._planeIntersectionPoint.addInPlace(this._tempVector);
  4661. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  4662. found = true;
  4663. t = t0;
  4664. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  4665. }
  4666. }
  4667. if (!found) {
  4668. var velocitySquaredLength = this.velocity.lengthSquared();
  4669. var a = velocitySquaredLength;
  4670. this.basePoint.subtractToRef(p1, this._tempVector);
  4671. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4672. var c = this._tempVector.lengthSquared() - 1.0;
  4673. var lowestRoot = getLowestRoot(a, b, c, t);
  4674. if (lowestRoot.found) {
  4675. t = lowestRoot.root;
  4676. found = true;
  4677. this._collisionPoint.copyFrom(p1);
  4678. }
  4679. this.basePoint.subtractToRef(p2, this._tempVector);
  4680. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4681. c = this._tempVector.lengthSquared() - 1.0;
  4682. lowestRoot = getLowestRoot(a, b, c, t);
  4683. if (lowestRoot.found) {
  4684. t = lowestRoot.root;
  4685. found = true;
  4686. this._collisionPoint.copyFrom(p2);
  4687. }
  4688. this.basePoint.subtractToRef(p3, this._tempVector);
  4689. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4690. c = this._tempVector.lengthSquared() - 1.0;
  4691. lowestRoot = getLowestRoot(a, b, c, t);
  4692. if (lowestRoot.found) {
  4693. t = lowestRoot.root;
  4694. found = true;
  4695. this._collisionPoint.copyFrom(p3);
  4696. }
  4697. p2.subtractToRef(p1, this._edge);
  4698. p1.subtractToRef(this.basePoint, this._baseToVertex);
  4699. var edgeSquaredLength = this._edge.lengthSquared();
  4700. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4701. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4702. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4703. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4704. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4705. lowestRoot = getLowestRoot(a, b, c, t);
  4706. if (lowestRoot.found) {
  4707. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4708. if (f >= 0.0 && f <= 1.0) {
  4709. t = lowestRoot.root;
  4710. found = true;
  4711. this._edge.scaleInPlace(f);
  4712. p1.addToRef(this._edge, this._collisionPoint);
  4713. }
  4714. }
  4715. p3.subtractToRef(p2, this._edge);
  4716. p2.subtractToRef(this.basePoint, this._baseToVertex);
  4717. edgeSquaredLength = this._edge.lengthSquared();
  4718. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4719. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4720. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4721. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4722. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4723. lowestRoot = getLowestRoot(a, b, c, t);
  4724. if (lowestRoot.found) {
  4725. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4726. if (f >= 0.0 && f <= 1.0) {
  4727. t = lowestRoot.root;
  4728. found = true;
  4729. this._edge.scaleInPlace(f);
  4730. p2.addToRef(this._edge, this._collisionPoint);
  4731. }
  4732. }
  4733. p1.subtractToRef(p3, this._edge);
  4734. p3.subtractToRef(this.basePoint, this._baseToVertex);
  4735. edgeSquaredLength = this._edge.lengthSquared();
  4736. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4737. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4738. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4739. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4740. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4741. lowestRoot = getLowestRoot(a, b, c, t);
  4742. if (lowestRoot.found) {
  4743. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4744. if (f >= 0.0 && f <= 1.0) {
  4745. t = lowestRoot.root;
  4746. found = true;
  4747. this._edge.scaleInPlace(f);
  4748. p3.addToRef(this._edge, this._collisionPoint);
  4749. }
  4750. }
  4751. }
  4752. if (found) {
  4753. var distToCollision = t * this.velocity.length();
  4754. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  4755. if (!this.intersectionPoint) {
  4756. this.intersectionPoint = this._collisionPoint.clone();
  4757. } else {
  4758. this.intersectionPoint.copyFrom(this._collisionPoint);
  4759. }
  4760. this.nearestDistance = distToCollision;
  4761. this.collisionFound = true;
  4762. this.collidedMesh = subMesh.getMesh();
  4763. }
  4764. }
  4765. };
  4766. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  4767. for (var i = indexStart; i < indexEnd; i += 3) {
  4768. var p1 = pts[indices[i] - decal];
  4769. var p2 = pts[indices[i + 1] - decal];
  4770. var p3 = pts[indices[i + 2] - decal];
  4771. this._testTriangle(i, subMesh, p3, p2, p1);
  4772. }
  4773. };
  4774. Collider.prototype._getResponse = function (pos, vel) {
  4775. pos.addToRef(vel, this._destinationPoint);
  4776. vel.scaleInPlace((this.nearestDistance / vel.length()));
  4777. this.basePoint.addToRef(vel, pos);
  4778. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  4779. this._slidePlaneNormal.normalize();
  4780. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  4781. pos.addInPlace(this._displacementVector);
  4782. this.intersectionPoint.addInPlace(this._displacementVector);
  4783. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  4784. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  4785. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  4786. };
  4787. return Collider;
  4788. })();
  4789. BABYLON.Collider = Collider;
  4790. })(BABYLON || (BABYLON = {}));
  4791. var __extends = this.__extends || function (d, b) {
  4792. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4793. function __() { this.constructor = d; }
  4794. __.prototype = b.prototype;
  4795. d.prototype = new __();
  4796. };
  4797. var BABYLON;
  4798. (function (BABYLON) {
  4799. var Camera = (function (_super) {
  4800. __extends(Camera, _super);
  4801. function Camera(name, position, scene) {
  4802. _super.call(this, name, scene);
  4803. this.position = position;
  4804. this.upVector = BABYLON.Vector3.Up();
  4805. this.orthoLeft = null;
  4806. this.orthoRight = null;
  4807. this.orthoBottom = null;
  4808. this.orthoTop = null;
  4809. this.fov = 0.8;
  4810. this.minZ = 1.0;
  4811. this.maxZ = 10000.0;
  4812. this.inertia = 0.9;
  4813. this.mode = Camera.PERSPECTIVE_CAMERA;
  4814. this.isIntermediate = false;
  4815. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  4816. this.subCameras = [];
  4817. this.layerMask = 0xFFFFFFFF;
  4818. this._computedViewMatrix = BABYLON.Matrix.Identity();
  4819. this._projectionMatrix = new BABYLON.Matrix();
  4820. this._postProcesses = new Array();
  4821. this._postProcessesTakenIndices = [];
  4822. scene.cameras.push(this);
  4823. if (!scene.activeCamera) {
  4824. scene.activeCamera = this;
  4825. }
  4826. }
  4827. Camera.prototype._initCache = function () {
  4828. _super.prototype._initCache.call(this);
  4829. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4830. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4831. this._cache.mode = undefined;
  4832. this._cache.minZ = undefined;
  4833. this._cache.maxZ = undefined;
  4834. this._cache.fov = undefined;
  4835. this._cache.aspectRatio = undefined;
  4836. this._cache.orthoLeft = undefined;
  4837. this._cache.orthoRight = undefined;
  4838. this._cache.orthoBottom = undefined;
  4839. this._cache.orthoTop = undefined;
  4840. this._cache.renderWidth = undefined;
  4841. this._cache.renderHeight = undefined;
  4842. };
  4843. Camera.prototype._updateCache = function (ignoreParentClass) {
  4844. if (!ignoreParentClass) {
  4845. _super.prototype._updateCache.call(this);
  4846. }
  4847. var engine = this.getEngine();
  4848. this._cache.position.copyFrom(this.position);
  4849. this._cache.upVector.copyFrom(this.upVector);
  4850. this._cache.mode = this.mode;
  4851. this._cache.minZ = this.minZ;
  4852. this._cache.maxZ = this.maxZ;
  4853. this._cache.fov = this.fov;
  4854. this._cache.aspectRatio = engine.getAspectRatio(this);
  4855. this._cache.orthoLeft = this.orthoLeft;
  4856. this._cache.orthoRight = this.orthoRight;
  4857. this._cache.orthoBottom = this.orthoBottom;
  4858. this._cache.orthoTop = this.orthoTop;
  4859. this._cache.renderWidth = engine.getRenderWidth();
  4860. this._cache.renderHeight = engine.getRenderHeight();
  4861. };
  4862. Camera.prototype._updateFromScene = function () {
  4863. this.updateCache();
  4864. this._update();
  4865. };
  4866. Camera.prototype._isSynchronized = function () {
  4867. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  4868. };
  4869. Camera.prototype._isSynchronizedViewMatrix = function () {
  4870. if (!_super.prototype._isSynchronized.call(this))
  4871. return false;
  4872. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  4873. };
  4874. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  4875. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  4876. if (!check) {
  4877. return false;
  4878. }
  4879. var engine = this.getEngine();
  4880. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4881. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  4882. } else {
  4883. 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();
  4884. }
  4885. return check;
  4886. };
  4887. Camera.prototype.attachControl = function (element) {
  4888. };
  4889. Camera.prototype.detachControl = function (element) {
  4890. };
  4891. Camera.prototype._update = function () {
  4892. };
  4893. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  4894. if (typeof insertAt === "undefined") { insertAt = null; }
  4895. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  4896. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  4897. return 0;
  4898. }
  4899. if (insertAt == null || insertAt < 0) {
  4900. this._postProcesses.push(postProcess);
  4901. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  4902. return this._postProcesses.length - 1;
  4903. }
  4904. var add = 0;
  4905. if (this._postProcesses[insertAt]) {
  4906. var start = this._postProcesses.length - 1;
  4907. for (var i = start; i >= insertAt + 1; --i) {
  4908. this._postProcesses[i + 1] = this._postProcesses[i];
  4909. }
  4910. add = 1;
  4911. }
  4912. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  4913. if (this._postProcessesTakenIndices[i] < insertAt) {
  4914. continue;
  4915. }
  4916. start = this._postProcessesTakenIndices.length - 1;
  4917. for (var j = start; j >= i; --j) {
  4918. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  4919. }
  4920. this._postProcessesTakenIndices[i] = insertAt;
  4921. break;
  4922. }
  4923. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  4924. this._postProcessesTakenIndices.push(insertAt);
  4925. }
  4926. var result = insertAt + add;
  4927. this._postProcesses[result] = postProcess;
  4928. return result;
  4929. };
  4930. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  4931. if (typeof atIndices === "undefined") { atIndices = null; }
  4932. var result = [];
  4933. if (!atIndices) {
  4934. var length = this._postProcesses.length;
  4935. for (var i = 0; i < length; i++) {
  4936. if (this._postProcesses[i] !== postProcess) {
  4937. continue;
  4938. }
  4939. delete this._postProcesses[i];
  4940. var index = this._postProcessesTakenIndices.indexOf(i);
  4941. this._postProcessesTakenIndices.splice(index, 1);
  4942. }
  4943. } else {
  4944. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  4945. for (i = 0; i < atIndices.length; i++) {
  4946. var foundPostProcess = this._postProcesses[atIndices[i]];
  4947. if (foundPostProcess !== postProcess) {
  4948. result.push(i);
  4949. continue;
  4950. }
  4951. delete this._postProcesses[atIndices[i]];
  4952. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  4953. this._postProcessesTakenIndices.splice(index, 1);
  4954. }
  4955. }
  4956. return result;
  4957. };
  4958. Camera.prototype.getWorldMatrix = function () {
  4959. if (!this._worldMatrix) {
  4960. this._worldMatrix = BABYLON.Matrix.Identity();
  4961. }
  4962. var viewMatrix = this.getViewMatrix();
  4963. viewMatrix.invertToRef(this._worldMatrix);
  4964. return this._worldMatrix;
  4965. };
  4966. Camera.prototype._getViewMatrix = function () {
  4967. return BABYLON.Matrix.Identity();
  4968. };
  4969. Camera.prototype.getViewMatrix = function () {
  4970. this._computedViewMatrix = this._computeViewMatrix();
  4971. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  4972. return this._computedViewMatrix;
  4973. }
  4974. if (!this._worldMatrix) {
  4975. this._worldMatrix = BABYLON.Matrix.Identity();
  4976. }
  4977. this._computedViewMatrix.invertToRef(this._worldMatrix);
  4978. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  4979. this._computedViewMatrix.invert();
  4980. this._currentRenderId = this.getScene().getRenderId();
  4981. return this._computedViewMatrix;
  4982. };
  4983. Camera.prototype._computeViewMatrix = function (force) {
  4984. if (!force && this._isSynchronizedViewMatrix()) {
  4985. return this._computedViewMatrix;
  4986. }
  4987. this._computedViewMatrix = this._getViewMatrix();
  4988. if (!this.parent || !this.parent.getWorldMatrix) {
  4989. this._currentRenderId = this.getScene().getRenderId();
  4990. }
  4991. return this._computedViewMatrix;
  4992. };
  4993. Camera.prototype.getProjectionMatrix = function (force) {
  4994. if (!force && this._isSynchronizedProjectionMatrix()) {
  4995. return this._projectionMatrix;
  4996. }
  4997. var engine = this.getEngine();
  4998. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4999. if (this.minZ <= 0) {
  5000. this.minZ = 0.1;
  5001. }
  5002. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  5003. return this._projectionMatrix;
  5004. }
  5005. var halfWidth = engine.getRenderWidth() / 2.0;
  5006. var halfHeight = engine.getRenderHeight() / 2.0;
  5007. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  5008. return this._projectionMatrix;
  5009. };
  5010. Camera.prototype.dispose = function () {
  5011. var index = this.getScene().cameras.indexOf(this);
  5012. this.getScene().cameras.splice(index, 1);
  5013. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5014. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  5015. }
  5016. };
  5017. Camera.PERSPECTIVE_CAMERA = 0;
  5018. Camera.ORTHOGRAPHIC_CAMERA = 1;
  5019. return Camera;
  5020. })(BABYLON.Node);
  5021. BABYLON.Camera = Camera;
  5022. })(BABYLON || (BABYLON = {}));
  5023. var __extends = this.__extends || function (d, b) {
  5024. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5025. function __() { this.constructor = d; }
  5026. __.prototype = b.prototype;
  5027. d.prototype = new __();
  5028. };
  5029. var BABYLON;
  5030. (function (BABYLON) {
  5031. var TargetCamera = (function (_super) {
  5032. __extends(TargetCamera, _super);
  5033. function TargetCamera(name, position, scene) {
  5034. _super.call(this, name, position, scene);
  5035. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5036. this.cameraRotation = new BABYLON.Vector2(0, 0);
  5037. this.rotation = new BABYLON.Vector3(0, 0, 0);
  5038. this.speed = 2.0;
  5039. this.noRotationConstraint = false;
  5040. this.lockedTarget = null;
  5041. this._currentTarget = BABYLON.Vector3.Zero();
  5042. this._viewMatrix = BABYLON.Matrix.Zero();
  5043. this._camMatrix = BABYLON.Matrix.Zero();
  5044. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  5045. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  5046. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  5047. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  5048. this._lookAtTemp = BABYLON.Matrix.Zero();
  5049. this._tempMatrix = BABYLON.Matrix.Zero();
  5050. }
  5051. TargetCamera.prototype._getLockedTargetPosition = function () {
  5052. if (!this.lockedTarget) {
  5053. return null;
  5054. }
  5055. return this.lockedTarget.position || this.lockedTarget;
  5056. };
  5057. TargetCamera.prototype._initCache = function () {
  5058. _super.prototype._initCache.call(this);
  5059. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5060. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5061. };
  5062. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  5063. if (!ignoreParentClass) {
  5064. _super.prototype._updateCache.call(this);
  5065. }
  5066. var lockedTargetPosition = this._getLockedTargetPosition();
  5067. if (!lockedTargetPosition) {
  5068. this._cache.lockedTarget = null;
  5069. } else {
  5070. if (!this._cache.lockedTarget) {
  5071. this._cache.lockedTarget = lockedTargetPosition.clone();
  5072. } else {
  5073. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  5074. }
  5075. }
  5076. this._cache.rotation.copyFrom(this.rotation);
  5077. };
  5078. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  5079. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  5080. return false;
  5081. }
  5082. var lockedTargetPosition = this._getLockedTargetPosition();
  5083. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  5084. };
  5085. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  5086. return this.speed * ((BABYLON.Tools.GetDeltaTime() / (BABYLON.Tools.GetFps() * 10.0)));
  5087. };
  5088. TargetCamera.prototype.setTarget = function (target) {
  5089. this.upVector.normalize();
  5090. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  5091. this._camMatrix.invert();
  5092. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  5093. var vDir = target.subtract(this.position);
  5094. if (vDir.x >= 0.0) {
  5095. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5096. } else {
  5097. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5098. }
  5099. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5100. if (isNaN(this.rotation.x)) {
  5101. this.rotation.x = 0;
  5102. }
  5103. if (isNaN(this.rotation.y)) {
  5104. this.rotation.y = 0;
  5105. }
  5106. if (isNaN(this.rotation.z)) {
  5107. this.rotation.z = 0;
  5108. }
  5109. };
  5110. TargetCamera.prototype.getTarget = function () {
  5111. return this._currentTarget;
  5112. };
  5113. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5114. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5115. };
  5116. TargetCamera.prototype._updatePosition = function () {
  5117. this.position.addInPlace(this.cameraDirection);
  5118. };
  5119. TargetCamera.prototype._update = function () {
  5120. var needToMove = this._decideIfNeedsToMove();
  5121. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5122. if (needToMove) {
  5123. this._updatePosition();
  5124. }
  5125. if (needToRotate) {
  5126. this.rotation.x += this.cameraRotation.x;
  5127. this.rotation.y += this.cameraRotation.y;
  5128. if (!this.noRotationConstraint) {
  5129. var limit = (Math.PI / 2) * 0.95;
  5130. if (this.rotation.x > limit)
  5131. this.rotation.x = limit;
  5132. if (this.rotation.x < -limit)
  5133. this.rotation.x = -limit;
  5134. }
  5135. }
  5136. if (needToMove) {
  5137. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  5138. this.cameraDirection.x = 0;
  5139. }
  5140. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  5141. this.cameraDirection.y = 0;
  5142. }
  5143. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  5144. this.cameraDirection.z = 0;
  5145. }
  5146. this.cameraDirection.scaleInPlace(this.inertia);
  5147. }
  5148. if (needToRotate) {
  5149. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  5150. this.cameraRotation.x = 0;
  5151. }
  5152. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  5153. this.cameraRotation.y = 0;
  5154. }
  5155. this.cameraRotation.scaleInPlace(this.inertia);
  5156. }
  5157. };
  5158. TargetCamera.prototype._getViewMatrix = function () {
  5159. if (!this.lockedTarget) {
  5160. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  5161. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  5162. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5163. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  5164. this._lookAtTemp.invert();
  5165. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  5166. } else {
  5167. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5168. }
  5169. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  5170. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  5171. } else {
  5172. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  5173. }
  5174. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  5175. return this._viewMatrix;
  5176. };
  5177. return TargetCamera;
  5178. })(BABYLON.Camera);
  5179. BABYLON.TargetCamera = TargetCamera;
  5180. })(BABYLON || (BABYLON = {}));
  5181. var __extends = this.__extends || function (d, b) {
  5182. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5183. function __() { this.constructor = d; }
  5184. __.prototype = b.prototype;
  5185. d.prototype = new __();
  5186. };
  5187. var BABYLON;
  5188. (function (BABYLON) {
  5189. var FollowCamera = (function (_super) {
  5190. __extends(FollowCamera, _super);
  5191. function FollowCamera(name, position, scene) {
  5192. _super.call(this, name, position, scene);
  5193. this.radius = 12;
  5194. this.rotationOffset = 0;
  5195. this.heightOffset = 4;
  5196. this.cameraAcceleration = 0.05;
  5197. this.maxCameraSpeed = 20;
  5198. }
  5199. FollowCamera.prototype.getRadians = function (degrees) {
  5200. return degrees * Math.PI / 180;
  5201. };
  5202. FollowCamera.prototype.follow = function (cameraTarget) {
  5203. if (!cameraTarget)
  5204. return;
  5205. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  5206. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  5207. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  5208. var dx = targetX - this.position.x;
  5209. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  5210. var dz = (targetZ) - this.position.z;
  5211. var vx = dx * this.cameraAcceleration * 2;
  5212. var vy = dy * this.cameraAcceleration;
  5213. var vz = dz * this.cameraAcceleration * 2;
  5214. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  5215. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5216. }
  5217. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  5218. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5219. }
  5220. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  5221. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5222. }
  5223. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  5224. this.setTarget(cameraTarget.position);
  5225. };
  5226. FollowCamera.prototype._update = function () {
  5227. _super.prototype._update.call(this);
  5228. this.follow(this.target);
  5229. };
  5230. return FollowCamera;
  5231. })(BABYLON.TargetCamera);
  5232. BABYLON.FollowCamera = FollowCamera;
  5233. })(BABYLON || (BABYLON = {}));
  5234. var __extends = this.__extends || function (d, b) {
  5235. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5236. function __() { this.constructor = d; }
  5237. __.prototype = b.prototype;
  5238. d.prototype = new __();
  5239. };
  5240. var BABYLON;
  5241. (function (BABYLON) {
  5242. var FreeCamera = (function (_super) {
  5243. __extends(FreeCamera, _super);
  5244. function FreeCamera(name, position, scene) {
  5245. _super.call(this, name, position, scene);
  5246. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  5247. this.keysUp = [38];
  5248. this.keysDown = [40];
  5249. this.keysLeft = [37];
  5250. this.keysRight = [39];
  5251. this.checkCollisions = false;
  5252. this.applyGravity = false;
  5253. this.angularSensibility = 2000.0;
  5254. this._keys = [];
  5255. this._collider = new BABYLON.Collider();
  5256. this._needMoveForGravity = true;
  5257. this._oldPosition = BABYLON.Vector3.Zero();
  5258. this._diffPosition = BABYLON.Vector3.Zero();
  5259. this._newPosition = BABYLON.Vector3.Zero();
  5260. }
  5261. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  5262. var _this = this;
  5263. var previousPosition;
  5264. var engine = this.getEngine();
  5265. if (this._attachedElement) {
  5266. return;
  5267. }
  5268. this._attachedElement = element;
  5269. if (this._onMouseDown === undefined) {
  5270. this._onMouseDown = function (evt) {
  5271. previousPosition = {
  5272. x: evt.clientX,
  5273. y: evt.clientY
  5274. };
  5275. if (!noPreventDefault) {
  5276. evt.preventDefault();
  5277. }
  5278. };
  5279. this._onMouseUp = function (evt) {
  5280. previousPosition = null;
  5281. if (!noPreventDefault) {
  5282. evt.preventDefault();
  5283. }
  5284. };
  5285. this._onMouseOut = function (evt) {
  5286. previousPosition = null;
  5287. _this._keys = [];
  5288. if (!noPreventDefault) {
  5289. evt.preventDefault();
  5290. }
  5291. };
  5292. this._onMouseMove = function (evt) {
  5293. if (!previousPosition && !engine.isPointerLock) {
  5294. return;
  5295. }
  5296. var offsetX;
  5297. var offsetY;
  5298. if (!engine.isPointerLock) {
  5299. offsetX = evt.clientX - previousPosition.x;
  5300. offsetY = evt.clientY - previousPosition.y;
  5301. } else {
  5302. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5303. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5304. }
  5305. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  5306. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  5307. previousPosition = {
  5308. x: evt.clientX,
  5309. y: evt.clientY
  5310. };
  5311. if (!noPreventDefault) {
  5312. evt.preventDefault();
  5313. }
  5314. };
  5315. this._onKeyDown = function (evt) {
  5316. 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) {
  5317. var index = _this._keys.indexOf(evt.keyCode);
  5318. if (index === -1) {
  5319. _this._keys.push(evt.keyCode);
  5320. }
  5321. if (!noPreventDefault) {
  5322. evt.preventDefault();
  5323. }
  5324. }
  5325. };
  5326. this._onKeyUp = function (evt) {
  5327. 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) {
  5328. var index = _this._keys.indexOf(evt.keyCode);
  5329. if (index >= 0) {
  5330. _this._keys.splice(index, 1);
  5331. }
  5332. if (!noPreventDefault) {
  5333. evt.preventDefault();
  5334. }
  5335. }
  5336. };
  5337. this._onLostFocus = function () {
  5338. _this._keys = [];
  5339. };
  5340. this._reset = function () {
  5341. _this._keys = [];
  5342. previousPosition = null;
  5343. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5344. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  5345. };
  5346. }
  5347. element.addEventListener("mousedown", this._onMouseDown, false);
  5348. element.addEventListener("mouseup", this._onMouseUp, false);
  5349. element.addEventListener("mouseout", this._onMouseOut, false);
  5350. element.addEventListener("mousemove", this._onMouseMove, false);
  5351. BABYLON.Tools.RegisterTopRootEvents([
  5352. { name: "keydown", handler: this._onKeyDown },
  5353. { name: "keyup", handler: this._onKeyUp },
  5354. { name: "blur", handler: this._onLostFocus }
  5355. ]);
  5356. };
  5357. FreeCamera.prototype.detachControl = function (element) {
  5358. if (this._attachedElement != element) {
  5359. return;
  5360. }
  5361. element.removeEventListener("mousedown", this._onMouseDown);
  5362. element.removeEventListener("mouseup", this._onMouseUp);
  5363. element.removeEventListener("mouseout", this._onMouseOut);
  5364. element.removeEventListener("mousemove", this._onMouseMove);
  5365. BABYLON.Tools.UnregisterTopRootEvents([
  5366. { name: "keydown", handler: this._onKeyDown },
  5367. { name: "keyup", handler: this._onKeyUp },
  5368. { name: "blur", handler: this._onLostFocus }
  5369. ]);
  5370. this._attachedElement = null;
  5371. if (this._reset) {
  5372. this._reset();
  5373. }
  5374. };
  5375. FreeCamera.prototype._collideWithWorld = function (velocity) {
  5376. var globalPosition;
  5377. if (this.parent) {
  5378. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  5379. } else {
  5380. globalPosition = this.position;
  5381. }
  5382. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  5383. this._collider.radius = this.ellipsoid;
  5384. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  5385. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  5386. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  5387. this.position.addInPlace(this._diffPosition);
  5388. if (this.onCollide) {
  5389. this.onCollide(this._collider.collidedMesh);
  5390. }
  5391. }
  5392. };
  5393. FreeCamera.prototype._checkInputs = function () {
  5394. if (!this._localDirection) {
  5395. this._localDirection = BABYLON.Vector3.Zero();
  5396. this._transformedDirection = BABYLON.Vector3.Zero();
  5397. }
  5398. for (var index = 0; index < this._keys.length; index++) {
  5399. var keyCode = this._keys[index];
  5400. var speed = this._computeLocalCameraSpeed();
  5401. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5402. this._localDirection.copyFromFloats(-speed, 0, 0);
  5403. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5404. this._localDirection.copyFromFloats(0, 0, speed);
  5405. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5406. this._localDirection.copyFromFloats(speed, 0, 0);
  5407. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5408. this._localDirection.copyFromFloats(0, 0, -speed);
  5409. }
  5410. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  5411. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  5412. this.cameraDirection.addInPlace(this._transformedDirection);
  5413. }
  5414. };
  5415. FreeCamera.prototype._decideIfNeedsToMove = function () {
  5416. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5417. };
  5418. FreeCamera.prototype._updatePosition = function () {
  5419. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  5420. this._collideWithWorld(this.cameraDirection);
  5421. if (this.applyGravity) {
  5422. var oldPosition = this.position;
  5423. this._collideWithWorld(this.getScene().gravity);
  5424. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  5425. }
  5426. } else {
  5427. this.position.addInPlace(this.cameraDirection);
  5428. }
  5429. };
  5430. FreeCamera.prototype._update = function () {
  5431. this._checkInputs();
  5432. _super.prototype._update.call(this);
  5433. };
  5434. return FreeCamera;
  5435. })(BABYLON.TargetCamera);
  5436. BABYLON.FreeCamera = FreeCamera;
  5437. })(BABYLON || (BABYLON = {}));
  5438. var __extends = this.__extends || function (d, b) {
  5439. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5440. function __() { this.constructor = d; }
  5441. __.prototype = b.prototype;
  5442. d.prototype = new __();
  5443. };
  5444. var BABYLON;
  5445. (function (BABYLON) {
  5446. var TouchCamera = (function (_super) {
  5447. __extends(TouchCamera, _super);
  5448. function TouchCamera(name, position, scene) {
  5449. _super.call(this, name, position, scene);
  5450. this._offsetX = null;
  5451. this._offsetY = null;
  5452. this._pointerCount = 0;
  5453. this._pointerPressed = [];
  5454. this.angularSensibility = 200000.0;
  5455. this.moveSensibility = 500.0;
  5456. }
  5457. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5458. var _this = this;
  5459. var previousPosition;
  5460. if (this._attachedCanvas) {
  5461. return;
  5462. }
  5463. this._attachedCanvas = canvas;
  5464. if (this._onPointerDown === undefined) {
  5465. this._onPointerDown = function (evt) {
  5466. if (!noPreventDefault) {
  5467. evt.preventDefault();
  5468. }
  5469. _this._pointerPressed.push(evt.pointerId);
  5470. if (_this._pointerPressed.length !== 1) {
  5471. return;
  5472. }
  5473. previousPosition = {
  5474. x: evt.clientX,
  5475. y: evt.clientY
  5476. };
  5477. };
  5478. this._onPointerUp = function (evt) {
  5479. if (!noPreventDefault) {
  5480. evt.preventDefault();
  5481. }
  5482. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5483. if (index === -1) {
  5484. return;
  5485. }
  5486. _this._pointerPressed.splice(index, 1);
  5487. if (index != 0) {
  5488. return;
  5489. }
  5490. previousPosition = null;
  5491. _this._offsetX = null;
  5492. _this._offsetY = null;
  5493. };
  5494. this._onPointerMove = function (evt) {
  5495. if (!noPreventDefault) {
  5496. evt.preventDefault();
  5497. }
  5498. if (!previousPosition) {
  5499. return;
  5500. }
  5501. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5502. if (index != 0) {
  5503. return;
  5504. }
  5505. _this._offsetX = evt.clientX - previousPosition.x;
  5506. _this._offsetY = -(evt.clientY - previousPosition.y);
  5507. };
  5508. this._onLostFocus = function () {
  5509. _this._offsetX = null;
  5510. _this._offsetY = null;
  5511. };
  5512. }
  5513. canvas.addEventListener("pointerdown", this._onPointerDown);
  5514. canvas.addEventListener("pointerup", this._onPointerUp);
  5515. canvas.addEventListener("pointerout", this._onPointerUp);
  5516. canvas.addEventListener("pointermove", this._onPointerMove);
  5517. BABYLON.Tools.RegisterTopRootEvents([
  5518. { name: "blur", handler: this._onLostFocus }
  5519. ]);
  5520. };
  5521. TouchCamera.prototype.detachControl = function (canvas) {
  5522. if (this._attachedCanvas != canvas) {
  5523. return;
  5524. }
  5525. canvas.removeEventListener("pointerdown", this._onPointerDown);
  5526. canvas.removeEventListener("pointerup", this._onPointerUp);
  5527. canvas.removeEventListener("pointerout", this._onPointerUp);
  5528. canvas.removeEventListener("pointermove", this._onPointerMove);
  5529. BABYLON.Tools.UnregisterTopRootEvents([
  5530. { name: "blur", handler: this._onLostFocus }
  5531. ]);
  5532. this._attachedCanvas = null;
  5533. };
  5534. TouchCamera.prototype._checkInputs = function () {
  5535. if (!this._offsetX) {
  5536. return;
  5537. }
  5538. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  5539. if (this._pointerPressed.length > 1) {
  5540. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  5541. } else {
  5542. var speed = this._computeLocalCameraSpeed();
  5543. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5544. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5545. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5546. }
  5547. };
  5548. return TouchCamera;
  5549. })(BABYLON.FreeCamera);
  5550. BABYLON.TouchCamera = TouchCamera;
  5551. })(BABYLON || (BABYLON = {}));
  5552. var __extends = this.__extends || function (d, b) {
  5553. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5554. function __() { this.constructor = d; }
  5555. __.prototype = b.prototype;
  5556. d.prototype = new __();
  5557. };
  5558. var BABYLON;
  5559. (function (BABYLON) {
  5560. var DeviceOrientationCamera = (function (_super) {
  5561. __extends(DeviceOrientationCamera, _super);
  5562. function DeviceOrientationCamera(name, position, scene) {
  5563. var _this = this;
  5564. _super.call(this, name, position, scene);
  5565. this._offsetX = null;
  5566. this._offsetY = null;
  5567. this._orientationGamma = 0;
  5568. this._orientationBeta = 0;
  5569. this._initialOrientationGamma = 0;
  5570. this._initialOrientationBeta = 0;
  5571. this.angularSensibility = 10000.0;
  5572. this.moveSensibility = 50.0;
  5573. window.addEventListener("resize", function () {
  5574. _this._initialOrientationGamma = null;
  5575. }, false);
  5576. }
  5577. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5578. var _this = this;
  5579. if (this._attachedCanvas) {
  5580. return;
  5581. }
  5582. this._attachedCanvas = canvas;
  5583. if (!this._orientationChanged) {
  5584. this._orientationChanged = function (evt) {
  5585. if (!_this._initialOrientationGamma) {
  5586. _this._initialOrientationGamma = evt.gamma;
  5587. _this._initialOrientationBeta = evt.beta;
  5588. }
  5589. _this._orientationGamma = evt.gamma;
  5590. _this._orientationBeta = evt.beta;
  5591. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  5592. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  5593. };
  5594. }
  5595. window.addEventListener("deviceorientation", this._orientationChanged);
  5596. };
  5597. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  5598. if (this._attachedCanvas != canvas) {
  5599. return;
  5600. }
  5601. window.removeEventListener("deviceorientation", this._orientationChanged);
  5602. this._attachedCanvas = null;
  5603. this._orientationGamma = 0;
  5604. this._orientationBeta = 0;
  5605. this._initialOrientationGamma = 0;
  5606. this._initialOrientationBeta = 0;
  5607. };
  5608. DeviceOrientationCamera.prototype._checkInputs = function () {
  5609. if (!this._offsetX) {
  5610. return;
  5611. }
  5612. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  5613. var speed = this._computeLocalCameraSpeed();
  5614. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5615. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5616. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5617. };
  5618. return DeviceOrientationCamera;
  5619. })(BABYLON.FreeCamera);
  5620. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  5621. })(BABYLON || (BABYLON = {}));
  5622. var __extends = this.__extends || function (d, b) {
  5623. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5624. function __() { this.constructor = d; }
  5625. __.prototype = b.prototype;
  5626. d.prototype = new __();
  5627. };
  5628. var BABYLON;
  5629. (function (BABYLON) {
  5630. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  5631. var ArcRotateCamera = (function (_super) {
  5632. __extends(ArcRotateCamera, _super);
  5633. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  5634. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  5635. this.alpha = alpha;
  5636. this.beta = beta;
  5637. this.radius = radius;
  5638. this.target = target;
  5639. this.inertialAlphaOffset = 0;
  5640. this.inertialBetaOffset = 0;
  5641. this.inertialRadiusOffset = 0;
  5642. this.lowerAlphaLimit = null;
  5643. this.upperAlphaLimit = null;
  5644. this.lowerBetaLimit = 0.01;
  5645. this.upperBetaLimit = Math.PI;
  5646. this.lowerRadiusLimit = null;
  5647. this.upperRadiusLimit = null;
  5648. this.angularSensibility = 1000.0;
  5649. this.wheelPrecision = 3.0;
  5650. this.keysUp = [38];
  5651. this.keysDown = [40];
  5652. this.keysLeft = [37];
  5653. this.keysRight = [39];
  5654. this.zoomOnFactor = 1;
  5655. this.targetScreenOffset = BABYLON.Vector2.Zero();
  5656. this._keys = [];
  5657. this._viewMatrix = new BABYLON.Matrix();
  5658. this.checkCollisions = false;
  5659. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  5660. this._collider = new BABYLON.Collider();
  5661. this._previousPosition = BABYLON.Vector3.Zero();
  5662. this._collisionVelocity = BABYLON.Vector3.Zero();
  5663. this._newPosition = BABYLON.Vector3.Zero();
  5664. this.pinchPrecision = 20;
  5665. this.getViewMatrix();
  5666. }
  5667. ArcRotateCamera.prototype._getTargetPosition = function () {
  5668. return this.target.position || this.target;
  5669. };
  5670. ArcRotateCamera.prototype._initCache = function () {
  5671. _super.prototype._initCache.call(this);
  5672. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5673. this._cache.alpha = undefined;
  5674. this._cache.beta = undefined;
  5675. this._cache.radius = undefined;
  5676. this._cache.targetScreenOffset = undefined;
  5677. };
  5678. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  5679. if (!ignoreParentClass) {
  5680. _super.prototype._updateCache.call(this);
  5681. }
  5682. this._cache.target.copyFrom(this._getTargetPosition());
  5683. this._cache.alpha = this.alpha;
  5684. this._cache.beta = this.beta;
  5685. this._cache.radius = this.radius;
  5686. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  5687. };
  5688. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  5689. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  5690. return false;
  5691. 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);
  5692. };
  5693. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  5694. var _this = this;
  5695. var previousPosition;
  5696. var pointerId;
  5697. var pinchStarted = false;
  5698. var pinchPointX1, pinchPointX2;
  5699. if (this._attachedElement) {
  5700. return;
  5701. }
  5702. this._attachedElement = element;
  5703. var engine = this.getEngine();
  5704. if (this._onPointerDown === undefined) {
  5705. this._onPointerDown = function (evt) {
  5706. if (pointerId) {
  5707. return;
  5708. }
  5709. pointerId = evt.pointerId;
  5710. previousPosition = {
  5711. x: evt.clientX,
  5712. y: evt.clientY
  5713. };
  5714. if (!noPreventDefault) {
  5715. evt.preventDefault();
  5716. }
  5717. };
  5718. this._onPointerUp = function (evt) {
  5719. previousPosition = null;
  5720. pointerId = null;
  5721. if (!noPreventDefault) {
  5722. evt.preventDefault();
  5723. }
  5724. };
  5725. this._onPointerMove = function (evt) {
  5726. if (!previousPosition) {
  5727. return;
  5728. }
  5729. if (pointerId !== evt.pointerId) {
  5730. return;
  5731. }
  5732. if (pinchStarted) {
  5733. return;
  5734. }
  5735. var offsetX = evt.clientX - previousPosition.x;
  5736. var offsetY = evt.clientY - previousPosition.y;
  5737. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5738. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5739. previousPosition = {
  5740. x: evt.clientX,
  5741. y: evt.clientY
  5742. };
  5743. if (!noPreventDefault) {
  5744. evt.preventDefault();
  5745. }
  5746. };
  5747. this._onMouseMove = function (evt) {
  5748. if (!engine.isPointerLock) {
  5749. return;
  5750. }
  5751. if (pinchStarted) {
  5752. return;
  5753. }
  5754. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5755. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5756. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5757. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5758. if (!noPreventDefault) {
  5759. evt.preventDefault();
  5760. }
  5761. };
  5762. this._wheel = function (event) {
  5763. var delta = 0;
  5764. if (event.wheelDelta) {
  5765. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  5766. } else if (event.detail) {
  5767. delta = -event.detail / _this.wheelPrecision;
  5768. }
  5769. if (delta)
  5770. _this.inertialRadiusOffset += delta;
  5771. if (event.preventDefault) {
  5772. if (!noPreventDefault) {
  5773. event.preventDefault();
  5774. }
  5775. }
  5776. };
  5777. this._onKeyDown = function (evt) {
  5778. 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) {
  5779. var index = _this._keys.indexOf(evt.keyCode);
  5780. if (index === -1) {
  5781. _this._keys.push(evt.keyCode);
  5782. }
  5783. if (evt.preventDefault) {
  5784. if (!noPreventDefault) {
  5785. evt.preventDefault();
  5786. }
  5787. }
  5788. }
  5789. };
  5790. this._onKeyUp = function (evt) {
  5791. 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) {
  5792. var index = _this._keys.indexOf(evt.keyCode);
  5793. if (index >= 0) {
  5794. _this._keys.splice(index, 1);
  5795. }
  5796. if (evt.preventDefault) {
  5797. if (!noPreventDefault) {
  5798. evt.preventDefault();
  5799. }
  5800. }
  5801. }
  5802. };
  5803. this._onLostFocus = function () {
  5804. _this._keys = [];
  5805. pointerId = null;
  5806. };
  5807. this._onGestureStart = function (e) {
  5808. if (window.MSGesture === undefined) {
  5809. return;
  5810. }
  5811. if (!_this._MSGestureHandler) {
  5812. _this._MSGestureHandler = new MSGesture();
  5813. _this._MSGestureHandler.target = element;
  5814. }
  5815. _this._MSGestureHandler.addPointer(e.pointerId);
  5816. };
  5817. this._onGesture = function (e) {
  5818. _this.radius *= e.scale;
  5819. if (e.preventDefault) {
  5820. if (!noPreventDefault) {
  5821. e.stopPropagation();
  5822. e.preventDefault();
  5823. }
  5824. }
  5825. };
  5826. this._reset = function () {
  5827. _this._keys = [];
  5828. _this.inertialAlphaOffset = 0;
  5829. _this.inertialBetaOffset = 0;
  5830. _this.inertialRadiusOffset = 0;
  5831. previousPosition = null;
  5832. pointerId = null;
  5833. };
  5834. this._touchStart = function (event) {
  5835. if (event.touches.length == 2) {
  5836. pinchStarted = true;
  5837. _this._pinchStart(event);
  5838. }
  5839. };
  5840. this._touchMove = function (event) {
  5841. if (pinchStarted) {
  5842. _this._pinchMove(event);
  5843. }
  5844. };
  5845. this._touchEnd = function (event) {
  5846. if (pinchStarted) {
  5847. _this._pinchEnd(event);
  5848. }
  5849. };
  5850. this._pinchStart = function (event) {
  5851. pinchPointX1 = event.touches[0].clientX;
  5852. pinchPointX2 = event.touches[1].clientX;
  5853. pinchStarted = true;
  5854. };
  5855. this._pinchMove = function (event) {
  5856. var delta = 0;
  5857. var direction = 1;
  5858. var distanceXOrigine, distanceXNow;
  5859. if (event.touches.length != 2)
  5860. return;
  5861. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  5862. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  5863. if (distanceXNow < distanceXOrigine) {
  5864. direction = -1;
  5865. }
  5866. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  5867. _this.inertialRadiusOffset += delta;
  5868. pinchPointX1 = event.touches[0].clientX;
  5869. pinchPointX2 = event.touches[1].clientX;
  5870. };
  5871. this._pinchEnd = function (event) {
  5872. pinchStarted = false;
  5873. };
  5874. }
  5875. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  5876. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  5877. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  5878. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  5879. element.addEventListener("mousemove", this._onMouseMove, false);
  5880. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  5881. element.addEventListener("MSGestureChange", this._onGesture, false);
  5882. element.addEventListener('mousewheel', this._wheel, false);
  5883. element.addEventListener('DOMMouseScroll', this._wheel, false);
  5884. element.addEventListener('touchstart', this._touchStart, false);
  5885. element.addEventListener('touchmove', this._touchMove, false);
  5886. element.addEventListener('touchend', this._touchEnd, false);
  5887. BABYLON.Tools.RegisterTopRootEvents([
  5888. { name: "keydown", handler: this._onKeyDown },
  5889. { name: "keyup", handler: this._onKeyUp },
  5890. { name: "blur", handler: this._onLostFocus }
  5891. ]);
  5892. };
  5893. ArcRotateCamera.prototype.detachControl = function (element) {
  5894. if (this._attachedElement != element) {
  5895. return;
  5896. }
  5897. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  5898. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  5899. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  5900. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  5901. element.removeEventListener("mousemove", this._onMouseMove);
  5902. element.removeEventListener("MSPointerDown", this._onGestureStart);
  5903. element.removeEventListener("MSGestureChange", this._onGesture);
  5904. element.removeEventListener('mousewheel', this._wheel);
  5905. element.removeEventListener('DOMMouseScroll', this._wheel);
  5906. element.removeEventListener('touchstart', this._touchStart);
  5907. element.removeEventListener('touchmove', this._touchMove);
  5908. element.removeEventListener('touchend', this._touchEnd);
  5909. BABYLON.Tools.UnregisterTopRootEvents([
  5910. { name: "keydown", handler: this._onKeyDown },
  5911. { name: "keyup", handler: this._onKeyUp },
  5912. { name: "blur", handler: this._onLostFocus }
  5913. ]);
  5914. this._MSGestureHandler = null;
  5915. this._attachedElement = null;
  5916. if (this._reset) {
  5917. this._reset();
  5918. }
  5919. };
  5920. ArcRotateCamera.prototype._update = function () {
  5921. for (var index = 0; index < this._keys.length; index++) {
  5922. var keyCode = this._keys[index];
  5923. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5924. this.inertialAlphaOffset -= 0.01;
  5925. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5926. this.inertialBetaOffset -= 0.01;
  5927. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5928. this.inertialAlphaOffset += 0.01;
  5929. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5930. this.inertialBetaOffset += 0.01;
  5931. }
  5932. }
  5933. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  5934. this.alpha += this.inertialAlphaOffset;
  5935. this.beta += this.inertialBetaOffset;
  5936. this.radius -= this.inertialRadiusOffset;
  5937. this.inertialAlphaOffset *= this.inertia;
  5938. this.inertialBetaOffset *= this.inertia;
  5939. this.inertialRadiusOffset *= this.inertia;
  5940. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  5941. this.inertialAlphaOffset = 0;
  5942. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  5943. this.inertialBetaOffset = 0;
  5944. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  5945. this.inertialRadiusOffset = 0;
  5946. }
  5947. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  5948. this.alpha = this.lowerAlphaLimit;
  5949. }
  5950. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  5951. this.alpha = this.upperAlphaLimit;
  5952. }
  5953. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  5954. this.beta = this.lowerBetaLimit;
  5955. }
  5956. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  5957. this.beta = this.upperBetaLimit;
  5958. }
  5959. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  5960. this.radius = this.lowerRadiusLimit;
  5961. }
  5962. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  5963. this.radius = this.upperRadiusLimit;
  5964. }
  5965. };
  5966. ArcRotateCamera.prototype.setPosition = function (position) {
  5967. var radiusv3 = position.subtract(this._getTargetPosition());
  5968. this.radius = radiusv3.length();
  5969. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  5970. if (radiusv3.z < 0) {
  5971. this.alpha = 2 * Math.PI - this.alpha;
  5972. }
  5973. this.beta = Math.acos(radiusv3.y / this.radius);
  5974. };
  5975. ArcRotateCamera.prototype._getViewMatrix = function () {
  5976. var cosa = Math.cos(this.alpha);
  5977. var sina = Math.sin(this.alpha);
  5978. var cosb = Math.cos(this.beta);
  5979. var sinb = Math.sin(this.beta);
  5980. var target = this._getTargetPosition();
  5981. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  5982. if (this.checkCollisions) {
  5983. this._collider.radius = this.collisionRadius;
  5984. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  5985. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  5986. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  5987. this.position.copyFrom(this._previousPosition);
  5988. this.alpha = this._previousAlpha;
  5989. this.beta = this._previousBeta;
  5990. this.radius = this._previousRadius;
  5991. if (this.onCollide) {
  5992. this.onCollide(this._collider.collidedMesh);
  5993. }
  5994. }
  5995. }
  5996. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  5997. this._previousAlpha = this.alpha;
  5998. this._previousBeta = this.beta;
  5999. this._previousRadius = this.radius;
  6000. this._previousPosition.copyFrom(this.position);
  6001. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  6002. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  6003. return this._viewMatrix;
  6004. };
  6005. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  6006. meshes = meshes || this.getScene().meshes;
  6007. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  6008. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  6009. this.radius = distance * this.zoomOnFactor;
  6010. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  6011. };
  6012. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  6013. var meshesOrMinMaxVector;
  6014. var distance;
  6015. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  6016. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  6017. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  6018. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  6019. } else {
  6020. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  6021. distance = meshesOrMinMaxVectorAndDistance.distance;
  6022. }
  6023. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  6024. this.maxZ = distance * 2;
  6025. };
  6026. return ArcRotateCamera;
  6027. })(BABYLON.Camera);
  6028. BABYLON.ArcRotateCamera = ArcRotateCamera;
  6029. })(BABYLON || (BABYLON = {}));
  6030. var BABYLON;
  6031. (function (BABYLON) {
  6032. var Scene = (function () {
  6033. function Scene(engine) {
  6034. this.autoClear = true;
  6035. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6036. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  6037. this.forceWireframe = false;
  6038. this.cameraToUseForPointers = null;
  6039. this.fogMode = BABYLON.Scene.FOGMODE_NONE;
  6040. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6041. this.fogDensity = 0.1;
  6042. this.fogStart = 0;
  6043. this.fogEnd = 1000.0;
  6044. this.lightsEnabled = true;
  6045. this.lights = new Array();
  6046. this.cameras = new Array();
  6047. this.activeCameras = new Array();
  6048. this.meshes = new Array();
  6049. this._geometries = new Array();
  6050. this.materials = new Array();
  6051. this.multiMaterials = new Array();
  6052. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  6053. this.texturesEnabled = true;
  6054. this.textures = new Array();
  6055. this.particlesEnabled = true;
  6056. this.particleSystems = new Array();
  6057. this.spriteManagers = new Array();
  6058. this.layers = new Array();
  6059. this.skeletons = new Array();
  6060. this.lensFlareSystems = new Array();
  6061. this.collisionsEnabled = true;
  6062. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  6063. this.postProcessesEnabled = true;
  6064. this.renderTargetsEnabled = true;
  6065. this.customRenderTargets = new Array();
  6066. this.importedMeshesFiles = new Array();
  6067. this._actionManagers = new Array();
  6068. this._meshesForIntersections = new BABYLON.SmartArray(256);
  6069. this.proceduralTexturesEnabled = true;
  6070. this._proceduralTextures = new Array();
  6071. this._totalVertices = 0;
  6072. this._activeVertices = 0;
  6073. this._activeParticles = 0;
  6074. this._lastFrameDuration = 0;
  6075. this._evaluateActiveMeshesDuration = 0;
  6076. this._renderTargetsDuration = 0;
  6077. this._particlesDuration = 0;
  6078. this._renderDuration = 0;
  6079. this._spritesDuration = 0;
  6080. this._animationRatio = 0;
  6081. this._renderId = 0;
  6082. this._executeWhenReadyTimeoutId = -1;
  6083. this._toBeDisposed = new BABYLON.SmartArray(256);
  6084. this._onReadyCallbacks = new Array();
  6085. this._pendingData = [];
  6086. this._onBeforeRenderCallbacks = new Array();
  6087. this._activeMeshes = new BABYLON.SmartArray(256);
  6088. this._processedMaterials = new BABYLON.SmartArray(256);
  6089. this._renderTargets = new BABYLON.SmartArray(256);
  6090. this._activeParticleSystems = new BABYLON.SmartArray(256);
  6091. this._activeSkeletons = new BABYLON.SmartArray(32);
  6092. this._activeAnimatables = new Array();
  6093. this._transformMatrix = BABYLON.Matrix.Zero();
  6094. this._scaledPosition = BABYLON.Vector3.Zero();
  6095. this._scaledVelocity = BABYLON.Vector3.Zero();
  6096. this._engine = engine;
  6097. engine.scenes.push(this);
  6098. this._renderingManager = new BABYLON.RenderingManager(this);
  6099. this.postProcessManager = new BABYLON.PostProcessManager(this);
  6100. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  6101. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  6102. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  6103. this.attachControl();
  6104. }
  6105. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  6106. get: function () {
  6107. return this._meshUnderPointer;
  6108. },
  6109. enumerable: true,
  6110. configurable: true
  6111. });
  6112. Object.defineProperty(Scene.prototype, "pointerX", {
  6113. get: function () {
  6114. return this._pointerX;
  6115. },
  6116. enumerable: true,
  6117. configurable: true
  6118. });
  6119. Object.defineProperty(Scene.prototype, "pointerY", {
  6120. get: function () {
  6121. return this._pointerY;
  6122. },
  6123. enumerable: true,
  6124. configurable: true
  6125. });
  6126. Scene.prototype.getBoundingBoxRenderer = function () {
  6127. return this._boundingBoxRenderer;
  6128. };
  6129. Scene.prototype.getOutlineRenderer = function () {
  6130. return this._outlineRenderer;
  6131. };
  6132. Scene.prototype.getEngine = function () {
  6133. return this._engine;
  6134. };
  6135. Scene.prototype.getTotalVertices = function () {
  6136. return this._totalVertices;
  6137. };
  6138. Scene.prototype.getActiveVertices = function () {
  6139. return this._activeVertices;
  6140. };
  6141. Scene.prototype.getActiveParticles = function () {
  6142. return this._activeParticles;
  6143. };
  6144. Scene.prototype.getLastFrameDuration = function () {
  6145. return this._lastFrameDuration;
  6146. };
  6147. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  6148. return this._evaluateActiveMeshesDuration;
  6149. };
  6150. Scene.prototype.getActiveMeshes = function () {
  6151. return this._activeMeshes;
  6152. };
  6153. Scene.prototype.getRenderTargetsDuration = function () {
  6154. return this._renderTargetsDuration;
  6155. };
  6156. Scene.prototype.getRenderDuration = function () {
  6157. return this._renderDuration;
  6158. };
  6159. Scene.prototype.getParticlesDuration = function () {
  6160. return this._particlesDuration;
  6161. };
  6162. Scene.prototype.getSpritesDuration = function () {
  6163. return this._spritesDuration;
  6164. };
  6165. Scene.prototype.getAnimationRatio = function () {
  6166. return this._animationRatio;
  6167. };
  6168. Scene.prototype.getRenderId = function () {
  6169. return this._renderId;
  6170. };
  6171. Scene.prototype._updatePointerPosition = function (evt) {
  6172. var canvasRect = this._engine.getRenderingCanvasClientRect();
  6173. this._pointerX = evt.clientX - canvasRect.left;
  6174. this._pointerY = evt.clientY - canvasRect.top;
  6175. if (this.cameraToUseForPointers) {
  6176. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  6177. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  6178. }
  6179. };
  6180. Scene.prototype.attachControl = function () {
  6181. var _this = this;
  6182. this._onPointerMove = function (evt) {
  6183. var canvas = _this._engine.getRenderingCanvas();
  6184. _this._updatePointerPosition(evt);
  6185. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  6186. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  6187. }, false, _this.cameraToUseForPointers);
  6188. if (pickResult.hit) {
  6189. _this._meshUnderPointer = pickResult.pickedMesh;
  6190. _this.setPointerOverMesh(pickResult.pickedMesh);
  6191. canvas.style.cursor = "pointer";
  6192. } else {
  6193. _this.setPointerOverMesh(null);
  6194. canvas.style.cursor = "";
  6195. _this._meshUnderPointer = null;
  6196. }
  6197. };
  6198. this._onPointerDown = function (evt) {
  6199. var predicate = null;
  6200. if (!_this.onPointerDown) {
  6201. predicate = function (mesh) {
  6202. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  6203. };
  6204. }
  6205. _this._updatePointerPosition(evt);
  6206. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  6207. if (pickResult.hit) {
  6208. if (pickResult.pickedMesh.actionManager) {
  6209. switch (evt.button) {
  6210. case 0:
  6211. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6212. break;
  6213. case 1:
  6214. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6215. break;
  6216. case 2:
  6217. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6218. break;
  6219. }
  6220. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6221. }
  6222. }
  6223. if (_this.onPointerDown) {
  6224. _this.onPointerDown(evt, pickResult);
  6225. }
  6226. };
  6227. this._onKeyDown = function (evt) {
  6228. if (_this.actionManager) {
  6229. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6230. }
  6231. };
  6232. this._onKeyUp = function (evt) {
  6233. if (_this.actionManager) {
  6234. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6235. }
  6236. };
  6237. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6238. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6239. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6240. window.addEventListener("keydown", this._onKeyDown, false);
  6241. window.addEventListener("keyup", this._onKeyUp, false);
  6242. };
  6243. Scene.prototype.detachControl = function () {
  6244. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6245. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  6246. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  6247. window.removeEventListener("keydown", this._onKeyDown);
  6248. window.removeEventListener("keyup", this._onKeyUp);
  6249. };
  6250. Scene.prototype.isReady = function () {
  6251. if (this._pendingData.length > 0) {
  6252. return false;
  6253. }
  6254. for (var index = 0; index < this._geometries.length; index++) {
  6255. var geometry = this._geometries[index];
  6256. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  6257. return false;
  6258. }
  6259. }
  6260. for (index = 0; index < this.meshes.length; index++) {
  6261. var mesh = this.meshes[index];
  6262. if (!mesh.isReady()) {
  6263. return false;
  6264. }
  6265. var mat = mesh.material;
  6266. if (mat) {
  6267. if (!mat.isReady(mesh)) {
  6268. return false;
  6269. }
  6270. }
  6271. }
  6272. return true;
  6273. };
  6274. Scene.prototype.registerBeforeRender = function (func) {
  6275. this._onBeforeRenderCallbacks.push(func);
  6276. };
  6277. Scene.prototype.unregisterBeforeRender = function (func) {
  6278. var index = this._onBeforeRenderCallbacks.indexOf(func);
  6279. if (index > -1) {
  6280. this._onBeforeRenderCallbacks.splice(index, 1);
  6281. }
  6282. };
  6283. Scene.prototype._addPendingData = function (data) {
  6284. this._pendingData.push(data);
  6285. };
  6286. Scene.prototype._removePendingData = function (data) {
  6287. var index = this._pendingData.indexOf(data);
  6288. if (index !== -1) {
  6289. this._pendingData.splice(index, 1);
  6290. }
  6291. };
  6292. Scene.prototype.getWaitingItemsCount = function () {
  6293. return this._pendingData.length;
  6294. };
  6295. Scene.prototype.executeWhenReady = function (func) {
  6296. var _this = this;
  6297. this._onReadyCallbacks.push(func);
  6298. if (this._executeWhenReadyTimeoutId !== -1) {
  6299. return;
  6300. }
  6301. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6302. _this._checkIsReady();
  6303. }, 150);
  6304. };
  6305. Scene.prototype._checkIsReady = function () {
  6306. var _this = this;
  6307. if (this.isReady()) {
  6308. this._onReadyCallbacks.forEach(function (func) {
  6309. func();
  6310. });
  6311. this._onReadyCallbacks = [];
  6312. this._executeWhenReadyTimeoutId = -1;
  6313. return;
  6314. }
  6315. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6316. _this._checkIsReady();
  6317. }, 150);
  6318. };
  6319. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  6320. if (speedRatio === undefined) {
  6321. speedRatio = 1.0;
  6322. }
  6323. this.stopAnimation(target);
  6324. if (!animatable) {
  6325. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  6326. }
  6327. if (target.animations) {
  6328. animatable.appendAnimations(target, target.animations);
  6329. }
  6330. if (target.getAnimatables) {
  6331. var animatables = target.getAnimatables();
  6332. for (var index = 0; index < animatables.length; index++) {
  6333. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  6334. }
  6335. }
  6336. return animatable;
  6337. };
  6338. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  6339. if (speedRatio === undefined) {
  6340. speedRatio = 1.0;
  6341. }
  6342. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  6343. return animatable;
  6344. };
  6345. Scene.prototype.getAnimatableByTarget = function (target) {
  6346. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6347. if (this._activeAnimatables[index].target === target) {
  6348. return this._activeAnimatables[index];
  6349. }
  6350. }
  6351. return null;
  6352. };
  6353. Scene.prototype.stopAnimation = function (target) {
  6354. var animatable = this.getAnimatableByTarget(target);
  6355. if (animatable) {
  6356. animatable.stop();
  6357. }
  6358. };
  6359. Scene.prototype._animate = function () {
  6360. if (!this._animationStartDate) {
  6361. this._animationStartDate = new Date().getTime();
  6362. }
  6363. var now = new Date().getTime();
  6364. var delay = now - this._animationStartDate;
  6365. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6366. if (!this._activeAnimatables[index]._animate(delay)) {
  6367. this._activeAnimatables.splice(index, 1);
  6368. index--;
  6369. }
  6370. }
  6371. };
  6372. Scene.prototype.getViewMatrix = function () {
  6373. return this._viewMatrix;
  6374. };
  6375. Scene.prototype.getProjectionMatrix = function () {
  6376. return this._projectionMatrix;
  6377. };
  6378. Scene.prototype.getTransformMatrix = function () {
  6379. return this._transformMatrix;
  6380. };
  6381. Scene.prototype.setTransformMatrix = function (view, projection) {
  6382. this._viewMatrix = view;
  6383. this._projectionMatrix = projection;
  6384. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6385. };
  6386. Scene.prototype.setActiveCameraByID = function (id) {
  6387. var camera = this.getCameraByID(id);
  6388. if (camera) {
  6389. this.activeCamera = camera;
  6390. return camera;
  6391. }
  6392. return null;
  6393. };
  6394. Scene.prototype.setActiveCameraByName = function (name) {
  6395. var camera = this.getCameraByName(name);
  6396. if (camera) {
  6397. this.activeCamera = camera;
  6398. return camera;
  6399. }
  6400. return null;
  6401. };
  6402. Scene.prototype.getMaterialByID = function (id) {
  6403. for (var index = 0; index < this.materials.length; index++) {
  6404. if (this.materials[index].id === id) {
  6405. return this.materials[index];
  6406. }
  6407. }
  6408. return null;
  6409. };
  6410. Scene.prototype.getMaterialByName = function (name) {
  6411. for (var index = 0; index < this.materials.length; index++) {
  6412. if (this.materials[index].name === name) {
  6413. return this.materials[index];
  6414. }
  6415. }
  6416. return null;
  6417. };
  6418. Scene.prototype.getCameraByID = function (id) {
  6419. for (var index = 0; index < this.cameras.length; index++) {
  6420. if (this.cameras[index].id === id) {
  6421. return this.cameras[index];
  6422. }
  6423. }
  6424. return null;
  6425. };
  6426. Scene.prototype.getCameraByName = function (name) {
  6427. for (var index = 0; index < this.cameras.length; index++) {
  6428. if (this.cameras[index].name === name) {
  6429. return this.cameras[index];
  6430. }
  6431. }
  6432. return null;
  6433. };
  6434. Scene.prototype.getLightByName = function (name) {
  6435. for (var index = 0; index < this.lights.length; index++) {
  6436. if (this.lights[index].name === name) {
  6437. return this.lights[index];
  6438. }
  6439. }
  6440. return null;
  6441. };
  6442. Scene.prototype.getLightByID = function (id) {
  6443. for (var index = 0; index < this.lights.length; index++) {
  6444. if (this.lights[index].id === id) {
  6445. return this.lights[index];
  6446. }
  6447. }
  6448. return null;
  6449. };
  6450. Scene.prototype.getGeometryByID = function (id) {
  6451. for (var index = 0; index < this._geometries.length; index++) {
  6452. if (this._geometries[index].id === id) {
  6453. return this._geometries[index];
  6454. }
  6455. }
  6456. return null;
  6457. };
  6458. Scene.prototype.pushGeometry = function (geometry, force) {
  6459. if (!force && this.getGeometryByID(geometry.id)) {
  6460. return false;
  6461. }
  6462. this._geometries.push(geometry);
  6463. return true;
  6464. };
  6465. Scene.prototype.getGeometries = function () {
  6466. return this._geometries;
  6467. };
  6468. Scene.prototype.getMeshByID = function (id) {
  6469. for (var index = 0; index < this.meshes.length; index++) {
  6470. if (this.meshes[index].id === id) {
  6471. return this.meshes[index];
  6472. }
  6473. }
  6474. return null;
  6475. };
  6476. Scene.prototype.getLastMeshByID = function (id) {
  6477. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6478. if (this.meshes[index].id === id) {
  6479. return this.meshes[index];
  6480. }
  6481. }
  6482. return null;
  6483. };
  6484. Scene.prototype.getLastEntryByID = function (id) {
  6485. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6486. if (this.meshes[index].id === id) {
  6487. return this.meshes[index];
  6488. }
  6489. }
  6490. for (index = this.cameras.length - 1; index >= 0; index--) {
  6491. if (this.cameras[index].id === id) {
  6492. return this.cameras[index];
  6493. }
  6494. }
  6495. for (index = this.lights.length - 1; index >= 0; index--) {
  6496. if (this.lights[index].id === id) {
  6497. return this.lights[index];
  6498. }
  6499. }
  6500. return null;
  6501. };
  6502. Scene.prototype.getMeshByName = function (name) {
  6503. for (var index = 0; index < this.meshes.length; index++) {
  6504. if (this.meshes[index].name === name) {
  6505. return this.meshes[index];
  6506. }
  6507. }
  6508. return null;
  6509. };
  6510. Scene.prototype.getLastSkeletonByID = function (id) {
  6511. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  6512. if (this.skeletons[index].id === id) {
  6513. return this.skeletons[index];
  6514. }
  6515. }
  6516. return null;
  6517. };
  6518. Scene.prototype.getSkeletonById = function (id) {
  6519. for (var index = 0; index < this.skeletons.length; index++) {
  6520. if (this.skeletons[index].id === id) {
  6521. return this.skeletons[index];
  6522. }
  6523. }
  6524. return null;
  6525. };
  6526. Scene.prototype.getSkeletonByName = function (name) {
  6527. for (var index = 0; index < this.skeletons.length; index++) {
  6528. if (this.skeletons[index].name === name) {
  6529. return this.skeletons[index];
  6530. }
  6531. }
  6532. return null;
  6533. };
  6534. Scene.prototype.isActiveMesh = function (mesh) {
  6535. return (this._activeMeshes.indexOf(mesh) !== -1);
  6536. };
  6537. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  6538. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  6539. var material = subMesh.getMaterial();
  6540. if (mesh.showSubMeshesBoundingBox) {
  6541. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  6542. }
  6543. if (material) {
  6544. if (material.getRenderTargetTextures) {
  6545. if (this._processedMaterials.indexOf(material) === -1) {
  6546. this._processedMaterials.push(material);
  6547. this._renderTargets.concat(material.getRenderTargetTextures());
  6548. }
  6549. }
  6550. this._activeVertices += subMesh.verticesCount;
  6551. this._renderingManager.dispatch(subMesh);
  6552. }
  6553. }
  6554. };
  6555. Scene.prototype._evaluateActiveMeshes = function () {
  6556. this._activeMeshes.reset();
  6557. this._renderingManager.reset();
  6558. this._processedMaterials.reset();
  6559. this._activeParticleSystems.reset();
  6560. this._activeSkeletons.reset();
  6561. this._boundingBoxRenderer.reset();
  6562. if (!this._frustumPlanes) {
  6563. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  6564. } else {
  6565. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  6566. }
  6567. var meshes;
  6568. var len;
  6569. if (this._selectionOctree) {
  6570. var selection = this._selectionOctree.select(this._frustumPlanes);
  6571. meshes = selection.data;
  6572. len = selection.length;
  6573. } else {
  6574. len = this.meshes.length;
  6575. meshes = this.meshes;
  6576. }
  6577. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  6578. var mesh = meshes[meshIndex];
  6579. this._totalVertices += mesh.getTotalVertices();
  6580. if (!mesh.isReady()) {
  6581. continue;
  6582. }
  6583. mesh.computeWorldMatrix();
  6584. mesh._preActivate();
  6585. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  6586. this._meshesForIntersections.pushNoDuplicate(mesh);
  6587. }
  6588. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) != 0) && mesh.isInFrustum(this._frustumPlanes)) {
  6589. this._activeMeshes.push(mesh);
  6590. mesh._activate(this._renderId);
  6591. this._activeMesh(mesh);
  6592. }
  6593. }
  6594. var beforeParticlesDate = new Date().getTime();
  6595. if (this.particlesEnabled) {
  6596. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  6597. var particleSystem = this.particleSystems[particleIndex];
  6598. if (!particleSystem.isStarted()) {
  6599. continue;
  6600. }
  6601. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  6602. this._activeParticleSystems.push(particleSystem);
  6603. particleSystem.animate();
  6604. }
  6605. }
  6606. }
  6607. this._particlesDuration += new Date().getTime() - beforeParticlesDate;
  6608. };
  6609. Scene.prototype._activeMesh = function (mesh) {
  6610. if (mesh.skeleton) {
  6611. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  6612. }
  6613. if (mesh.showBoundingBox) {
  6614. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  6615. }
  6616. if (mesh.subMeshes) {
  6617. var len;
  6618. var subMeshes;
  6619. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  6620. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  6621. len = intersections.length;
  6622. subMeshes = intersections.data;
  6623. } else {
  6624. subMeshes = mesh.subMeshes;
  6625. len = subMeshes.length;
  6626. }
  6627. for (var subIndex = 0; subIndex < len; subIndex++) {
  6628. var subMesh = subMeshes[subIndex];
  6629. this._evaluateSubMesh(subMesh, mesh);
  6630. }
  6631. }
  6632. };
  6633. Scene.prototype.updateTransformMatrix = function (force) {
  6634. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  6635. };
  6636. Scene.prototype._renderForCamera = function (camera) {
  6637. var engine = this._engine;
  6638. this.activeCamera = camera;
  6639. if (!this.activeCamera)
  6640. throw new Error("Active camera not set");
  6641. engine.setViewport(this.activeCamera.viewport);
  6642. this._renderId++;
  6643. this.updateTransformMatrix();
  6644. if (this.beforeCameraRender) {
  6645. this.beforeCameraRender(this.activeCamera);
  6646. }
  6647. var beforeEvaluateActiveMeshesDate = new Date().getTime();
  6648. this._evaluateActiveMeshes();
  6649. this._evaluateActiveMeshesDuration += new Date().getTime() - beforeEvaluateActiveMeshesDate;
  6650. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  6651. var skeleton = this._activeSkeletons.data[skeletonIndex];
  6652. skeleton.prepare();
  6653. }
  6654. var beforeRenderTargetDate = new Date().getTime();
  6655. if (this.renderTargetsEnabled) {
  6656. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  6657. var renderTarget = this._renderTargets.data[renderIndex];
  6658. if (renderTarget._shouldRender()) {
  6659. this._renderId++;
  6660. renderTarget.render();
  6661. }
  6662. }
  6663. this._renderId++;
  6664. }
  6665. if (this._renderTargets.length > 0) {
  6666. engine.restoreDefaultFramebuffer();
  6667. }
  6668. this._renderTargetsDuration += new Date().getTime() - beforeRenderTargetDate;
  6669. this.postProcessManager._prepareFrame();
  6670. var beforeRenderDate = new Date().getTime();
  6671. if (this.layers.length) {
  6672. engine.setDepthBuffer(false);
  6673. var layerIndex;
  6674. var layer;
  6675. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6676. layer = this.layers[layerIndex];
  6677. if (layer.isBackground) {
  6678. layer.render();
  6679. }
  6680. }
  6681. engine.setDepthBuffer(true);
  6682. }
  6683. this._renderingManager.render(null, null, true, true);
  6684. this._boundingBoxRenderer.render();
  6685. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  6686. this.lensFlareSystems[lensFlareSystemIndex].render();
  6687. }
  6688. if (this.layers.length) {
  6689. engine.setDepthBuffer(false);
  6690. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6691. layer = this.layers[layerIndex];
  6692. if (!layer.isBackground) {
  6693. layer.render();
  6694. }
  6695. }
  6696. engine.setDepthBuffer(true);
  6697. }
  6698. this._renderDuration += new Date().getTime() - beforeRenderDate;
  6699. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  6700. this.activeCamera._updateFromScene();
  6701. this._renderTargets.reset();
  6702. if (this.afterCameraRender) {
  6703. this.afterCameraRender(this.activeCamera);
  6704. }
  6705. };
  6706. Scene.prototype._processSubCameras = function (camera) {
  6707. if (camera.subCameras.length == 0) {
  6708. this._renderForCamera(camera);
  6709. return;
  6710. }
  6711. for (var index = 0; index < camera.subCameras.length; index++) {
  6712. this._renderForCamera(camera.subCameras[index]);
  6713. }
  6714. this.activeCamera = camera;
  6715. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  6716. this.activeCamera._updateFromScene();
  6717. };
  6718. Scene.prototype._checkIntersections = function () {
  6719. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  6720. var sourceMesh = this._meshesForIntersections.data[index];
  6721. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  6722. var action = sourceMesh.actionManager.actions[actionIndex];
  6723. if (action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6724. var otherMesh = action.getTriggerParameter();
  6725. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  6726. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6727. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  6728. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6729. sourceMesh._intersectionsInProgress.push(otherMesh);
  6730. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6731. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6732. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6733. if (indexOfOther > -1) {
  6734. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  6735. }
  6736. }
  6737. }
  6738. }
  6739. }
  6740. };
  6741. Scene.prototype.render = function () {
  6742. var startDate = new Date().getTime();
  6743. this._particlesDuration = 0;
  6744. this._spritesDuration = 0;
  6745. this._activeParticles = 0;
  6746. this._renderDuration = 0;
  6747. this._evaluateActiveMeshesDuration = 0;
  6748. this._totalVertices = 0;
  6749. this._activeVertices = 0;
  6750. this._meshesForIntersections.reset();
  6751. if (this.actionManager) {
  6752. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  6753. }
  6754. if (this.beforeRender) {
  6755. this.beforeRender();
  6756. }
  6757. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  6758. this._onBeforeRenderCallbacks[callbackIndex]();
  6759. }
  6760. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  6761. this._animationRatio = deltaTime * (60.0 / 1000.0);
  6762. this._animate();
  6763. if (this._physicsEngine) {
  6764. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  6765. }
  6766. var beforeRenderTargetDate = new Date().getTime();
  6767. var engine = this.getEngine();
  6768. if (this.renderTargetsEnabled) {
  6769. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  6770. var renderTarget = this.customRenderTargets[customIndex];
  6771. if (renderTarget._shouldRender()) {
  6772. this._renderId++;
  6773. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  6774. if (!this.activeCamera)
  6775. throw new Error("Active camera not set");
  6776. engine.setViewport(this.activeCamera.viewport);
  6777. this.updateTransformMatrix();
  6778. renderTarget.render();
  6779. }
  6780. }
  6781. this._renderId++;
  6782. }
  6783. if (this.customRenderTargets.length > 0) {
  6784. engine.restoreDefaultFramebuffer();
  6785. }
  6786. this._renderTargetsDuration += new Date().getTime() - beforeRenderTargetDate;
  6787. if (this.proceduralTexturesEnabled) {
  6788. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  6789. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  6790. if (proceduralTexture._shouldRender()) {
  6791. proceduralTexture.render();
  6792. }
  6793. }
  6794. }
  6795. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  6796. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  6797. var light = this.lights[lightIndex];
  6798. var shadowGenerator = light.getShadowGenerator();
  6799. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  6800. this._renderTargets.push(shadowGenerator.getShadowMap());
  6801. }
  6802. }
  6803. this.postProcessRenderPipelineManager.update();
  6804. if (this.activeCameras.length > 0) {
  6805. var currentRenderId = this._renderId;
  6806. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  6807. this._renderId = currentRenderId;
  6808. this._processSubCameras(this.activeCameras[cameraIndex]);
  6809. }
  6810. } else {
  6811. if (!this.activeCamera) {
  6812. throw new Error("No camera defined");
  6813. }
  6814. this._processSubCameras(this.activeCamera);
  6815. }
  6816. this._checkIntersections();
  6817. if (this.afterRender) {
  6818. this.afterRender();
  6819. }
  6820. for (var index = 0; index < this._toBeDisposed.length; index++) {
  6821. this._toBeDisposed.data[index].dispose();
  6822. this._toBeDisposed[index] = null;
  6823. }
  6824. this._toBeDisposed.reset();
  6825. this._lastFrameDuration = new Date().getTime() - startDate;
  6826. };
  6827. Scene.prototype.dispose = function () {
  6828. this.beforeRender = null;
  6829. this.afterRender = null;
  6830. this.skeletons = [];
  6831. this._boundingBoxRenderer.dispose();
  6832. if (this.onDispose) {
  6833. this.onDispose();
  6834. }
  6835. this.detachControl();
  6836. var canvas = this._engine.getRenderingCanvas();
  6837. var index;
  6838. for (index = 0; index < this.cameras.length; index++) {
  6839. this.cameras[index].detachControl(canvas);
  6840. }
  6841. while (this.lights.length) {
  6842. this.lights[0].dispose();
  6843. }
  6844. while (this.meshes.length) {
  6845. this.meshes[0].dispose(true);
  6846. }
  6847. while (this.cameras.length) {
  6848. this.cameras[0].dispose();
  6849. }
  6850. while (this.materials.length) {
  6851. this.materials[0].dispose();
  6852. }
  6853. while (this.particleSystems.length) {
  6854. this.particleSystems[0].dispose();
  6855. }
  6856. while (this.spriteManagers.length) {
  6857. this.spriteManagers[0].dispose();
  6858. }
  6859. while (this.layers.length) {
  6860. this.layers[0].dispose();
  6861. }
  6862. while (this.textures.length) {
  6863. this.textures[0].dispose();
  6864. }
  6865. this.postProcessManager.dispose();
  6866. if (this._physicsEngine) {
  6867. this.disablePhysicsEngine();
  6868. }
  6869. index = this._engine.scenes.indexOf(this);
  6870. if (index > -1) {
  6871. this._engine.scenes.splice(index, 1);
  6872. }
  6873. this._engine.wipeCaches();
  6874. };
  6875. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6876. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6877. position.divideToRef(collider.radius, this._scaledPosition);
  6878. velocity.divideToRef(collider.radius, this._scaledVelocity);
  6879. collider.retry = 0;
  6880. collider.initialVelocity = this._scaledVelocity;
  6881. collider.initialPosition = this._scaledPosition;
  6882. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  6883. finalPosition.multiplyInPlace(collider.radius);
  6884. };
  6885. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  6886. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  6887. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  6888. if (collider.retry >= maximumRetry) {
  6889. finalPosition.copyFrom(position);
  6890. return;
  6891. }
  6892. collider._initialize(position, velocity, closeDistance);
  6893. for (var index = 0; index < this.meshes.length; index++) {
  6894. var mesh = this.meshes[index];
  6895. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  6896. mesh._checkCollision(collider);
  6897. }
  6898. }
  6899. if (!collider.collisionFound) {
  6900. position.addToRef(velocity, finalPosition);
  6901. return;
  6902. }
  6903. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  6904. collider._getResponse(position, velocity);
  6905. }
  6906. if (velocity.length() <= closeDistance) {
  6907. finalPosition.copyFrom(position);
  6908. return;
  6909. }
  6910. collider.retry++;
  6911. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  6912. };
  6913. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  6914. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  6915. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  6916. if (!this._selectionOctree) {
  6917. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  6918. }
  6919. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6920. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6921. for (var index = 0; index < this.meshes.length; index++) {
  6922. var mesh = this.meshes[index];
  6923. mesh.computeWorldMatrix(true);
  6924. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  6925. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  6926. BABYLON.Tools.CheckExtends(minBox, min, max);
  6927. BABYLON.Tools.CheckExtends(maxBox, min, max);
  6928. }
  6929. this._selectionOctree.update(min, max, this.meshes);
  6930. return this._selectionOctree;
  6931. };
  6932. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  6933. var engine = this._engine;
  6934. if (!camera) {
  6935. if (!this.activeCamera)
  6936. throw new Error("Active camera not set");
  6937. camera = this.activeCamera;
  6938. }
  6939. var cameraViewport = camera.viewport;
  6940. var viewport = cameraViewport.toGlobal(engine);
  6941. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  6942. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  6943. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  6944. };
  6945. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  6946. var pickingInfo = null;
  6947. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  6948. var mesh = this.meshes[meshIndex];
  6949. if (predicate) {
  6950. if (!predicate(mesh)) {
  6951. continue;
  6952. }
  6953. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  6954. continue;
  6955. }
  6956. var world = mesh.getWorldMatrix();
  6957. var ray = rayFunction(world);
  6958. var result = mesh.intersects(ray, fastCheck);
  6959. if (!result || !result.hit)
  6960. continue;
  6961. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  6962. continue;
  6963. pickingInfo = result;
  6964. if (fastCheck) {
  6965. break;
  6966. }
  6967. }
  6968. return pickingInfo || new BABYLON.PickingInfo();
  6969. };
  6970. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  6971. var _this = this;
  6972. return this._internalPick(function (world) {
  6973. return _this.createPickingRay(x, y, world, camera);
  6974. }, predicate, fastCheck);
  6975. };
  6976. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  6977. var _this = this;
  6978. return this._internalPick(function (world) {
  6979. if (!_this._pickWithRayInverseMatrix) {
  6980. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  6981. }
  6982. world.invertToRef(_this._pickWithRayInverseMatrix);
  6983. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  6984. }, predicate, fastCheck);
  6985. };
  6986. Scene.prototype.setPointerOverMesh = function (mesh) {
  6987. if (this._pointerOverMesh === mesh) {
  6988. return;
  6989. }
  6990. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6991. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6992. }
  6993. this._pointerOverMesh = mesh;
  6994. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  6995. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  6996. }
  6997. };
  6998. Scene.prototype.getPointerOverMesh = function () {
  6999. return this._pointerOverMesh;
  7000. };
  7001. Scene.prototype.getPhysicsEngine = function () {
  7002. return this._physicsEngine;
  7003. };
  7004. Scene.prototype.enablePhysics = function (gravity, plugin) {
  7005. if (this._physicsEngine) {
  7006. return true;
  7007. }
  7008. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  7009. if (!this._physicsEngine.isSupported()) {
  7010. this._physicsEngine = null;
  7011. return false;
  7012. }
  7013. this._physicsEngine._initialize(gravity);
  7014. return true;
  7015. };
  7016. Scene.prototype.disablePhysicsEngine = function () {
  7017. if (!this._physicsEngine) {
  7018. return;
  7019. }
  7020. this._physicsEngine.dispose();
  7021. this._physicsEngine = undefined;
  7022. };
  7023. Scene.prototype.isPhysicsEnabled = function () {
  7024. return this._physicsEngine !== undefined;
  7025. };
  7026. Scene.prototype.setGravity = function (gravity) {
  7027. if (!this._physicsEngine) {
  7028. return;
  7029. }
  7030. this._physicsEngine._setGravity(gravity);
  7031. };
  7032. Scene.prototype.createCompoundImpostor = function (parts, options) {
  7033. if (parts.parts) {
  7034. options = parts;
  7035. parts = parts.parts;
  7036. }
  7037. if (!this._physicsEngine) {
  7038. return null;
  7039. }
  7040. for (var index = 0; index < parts.length; index++) {
  7041. var mesh = parts[index].mesh;
  7042. mesh._physicImpostor = parts[index].impostor;
  7043. mesh._physicsMass = options.mass / parts.length;
  7044. mesh._physicsFriction = options.friction;
  7045. mesh._physicRestitution = options.restitution;
  7046. }
  7047. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  7048. };
  7049. Scene.prototype.deleteCompoundImpostor = function (compound) {
  7050. for (var index = 0; index < compound.parts.length; index++) {
  7051. var mesh = compound.parts[index].mesh;
  7052. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7053. this._physicsEngine._unregisterMesh(mesh);
  7054. }
  7055. };
  7056. Scene.prototype._getByTags = function (list, tagsQuery) {
  7057. if (tagsQuery === undefined) {
  7058. return list;
  7059. }
  7060. var listByTags = [];
  7061. for (var i in list) {
  7062. var item = list[i];
  7063. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  7064. listByTags.push(item);
  7065. }
  7066. }
  7067. return listByTags;
  7068. };
  7069. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  7070. return this._getByTags(this.meshes, tagsQuery);
  7071. };
  7072. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  7073. return this._getByTags(this.cameras, tagsQuery);
  7074. };
  7075. Scene.prototype.getLightsByTags = function (tagsQuery) {
  7076. return this._getByTags(this.lights, tagsQuery);
  7077. };
  7078. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  7079. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  7080. };
  7081. Scene.FOGMODE_NONE = 0;
  7082. Scene.FOGMODE_EXP = 1;
  7083. Scene.FOGMODE_EXP2 = 2;
  7084. Scene.FOGMODE_LINEAR = 3;
  7085. Scene.MinDeltaTime = 1.0;
  7086. Scene.MaxDeltaTime = 1000.0;
  7087. return Scene;
  7088. })();
  7089. BABYLON.Scene = Scene;
  7090. })(BABYLON || (BABYLON = {}));
  7091. var BABYLON;
  7092. (function (BABYLON) {
  7093. var VertexBuffer = (function () {
  7094. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation) {
  7095. if (engine instanceof BABYLON.Mesh) {
  7096. this._engine = engine.getScene().getEngine();
  7097. } else {
  7098. this._engine = engine;
  7099. }
  7100. this._updatable = updatable;
  7101. this._data = data;
  7102. if (!postponeInternalCreation) {
  7103. this.create();
  7104. }
  7105. this._kind = kind;
  7106. switch (kind) {
  7107. case VertexBuffer.PositionKind:
  7108. this._strideSize = 3;
  7109. break;
  7110. case VertexBuffer.NormalKind:
  7111. this._strideSize = 3;
  7112. break;
  7113. case VertexBuffer.UVKind:
  7114. this._strideSize = 2;
  7115. break;
  7116. case VertexBuffer.UV2Kind:
  7117. this._strideSize = 2;
  7118. break;
  7119. case VertexBuffer.ColorKind:
  7120. this._strideSize = 3;
  7121. break;
  7122. case VertexBuffer.MatricesIndicesKind:
  7123. this._strideSize = 4;
  7124. break;
  7125. case VertexBuffer.MatricesWeightsKind:
  7126. this._strideSize = 4;
  7127. break;
  7128. }
  7129. }
  7130. VertexBuffer.prototype.isUpdatable = function () {
  7131. return this._updatable;
  7132. };
  7133. VertexBuffer.prototype.getData = function () {
  7134. return this._data;
  7135. };
  7136. VertexBuffer.prototype.getBuffer = function () {
  7137. return this._buffer;
  7138. };
  7139. VertexBuffer.prototype.getStrideSize = function () {
  7140. return this._strideSize;
  7141. };
  7142. VertexBuffer.prototype.create = function (data) {
  7143. if (!data && this._buffer) {
  7144. return;
  7145. }
  7146. data = data || this._data;
  7147. if (!this._buffer) {
  7148. if (this._updatable) {
  7149. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  7150. } else {
  7151. this._buffer = this._engine.createVertexBuffer(data);
  7152. }
  7153. }
  7154. if (this._updatable) {
  7155. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7156. this._data = data;
  7157. }
  7158. };
  7159. VertexBuffer.prototype.update = function (data) {
  7160. this.create(data);
  7161. };
  7162. VertexBuffer.prototype.updateDirectly = function (data) {
  7163. if (!this._buffer) {
  7164. return;
  7165. }
  7166. if (this._updatable) {
  7167. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7168. this._data = null;
  7169. }
  7170. };
  7171. VertexBuffer.prototype.dispose = function () {
  7172. if (!this._buffer) {
  7173. return;
  7174. }
  7175. if (this._engine._releaseBuffer(this._buffer)) {
  7176. this._buffer = null;
  7177. }
  7178. };
  7179. Object.defineProperty(VertexBuffer, "PositionKind", {
  7180. get: function () {
  7181. return VertexBuffer._PositionKind;
  7182. },
  7183. enumerable: true,
  7184. configurable: true
  7185. });
  7186. Object.defineProperty(VertexBuffer, "NormalKind", {
  7187. get: function () {
  7188. return VertexBuffer._NormalKind;
  7189. },
  7190. enumerable: true,
  7191. configurable: true
  7192. });
  7193. Object.defineProperty(VertexBuffer, "UVKind", {
  7194. get: function () {
  7195. return VertexBuffer._UVKind;
  7196. },
  7197. enumerable: true,
  7198. configurable: true
  7199. });
  7200. Object.defineProperty(VertexBuffer, "UV2Kind", {
  7201. get: function () {
  7202. return VertexBuffer._UV2Kind;
  7203. },
  7204. enumerable: true,
  7205. configurable: true
  7206. });
  7207. Object.defineProperty(VertexBuffer, "ColorKind", {
  7208. get: function () {
  7209. return VertexBuffer._ColorKind;
  7210. },
  7211. enumerable: true,
  7212. configurable: true
  7213. });
  7214. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  7215. get: function () {
  7216. return VertexBuffer._MatricesIndicesKind;
  7217. },
  7218. enumerable: true,
  7219. configurable: true
  7220. });
  7221. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  7222. get: function () {
  7223. return VertexBuffer._MatricesWeightsKind;
  7224. },
  7225. enumerable: true,
  7226. configurable: true
  7227. });
  7228. VertexBuffer._PositionKind = "position";
  7229. VertexBuffer._NormalKind = "normal";
  7230. VertexBuffer._UVKind = "uv";
  7231. VertexBuffer._UV2Kind = "uv2";
  7232. VertexBuffer._ColorKind = "color";
  7233. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  7234. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  7235. return VertexBuffer;
  7236. })();
  7237. BABYLON.VertexBuffer = VertexBuffer;
  7238. })(BABYLON || (BABYLON = {}));
  7239. var __extends = this.__extends || function (d, b) {
  7240. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7241. function __() { this.constructor = d; }
  7242. __.prototype = b.prototype;
  7243. d.prototype = new __();
  7244. };
  7245. var BABYLON;
  7246. (function (BABYLON) {
  7247. var AbstractMesh = (function (_super) {
  7248. __extends(AbstractMesh, _super);
  7249. function AbstractMesh(name, scene) {
  7250. _super.call(this, name, scene);
  7251. this.position = new BABYLON.Vector3(0, 0, 0);
  7252. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7253. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7254. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  7255. this.visibility = 1.0;
  7256. this.infiniteDistance = false;
  7257. this.isVisible = true;
  7258. this.isPickable = true;
  7259. this.showBoundingBox = false;
  7260. this.showSubMeshesBoundingBox = false;
  7261. this.onDispose = null;
  7262. this.checkCollisions = false;
  7263. this.isBlocker = false;
  7264. this.renderingGroupId = 0;
  7265. this.receiveShadows = false;
  7266. this.renderOutline = false;
  7267. this.outlineColor = BABYLON.Color3.Red();
  7268. this.outlineWidth = 0.02;
  7269. this.useOctreeForRenderingSelection = true;
  7270. this.useOctreeForPicking = true;
  7271. this.useOctreeForCollisions = true;
  7272. this.layerMask = 0xFFFFFFFF;
  7273. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7274. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7275. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7276. this._collider = new BABYLON.Collider();
  7277. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7278. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7279. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7280. this._localScaling = BABYLON.Matrix.Zero();
  7281. this._localRotation = BABYLON.Matrix.Zero();
  7282. this._localTranslation = BABYLON.Matrix.Zero();
  7283. this._localBillboard = BABYLON.Matrix.Zero();
  7284. this._localPivotScaling = BABYLON.Matrix.Zero();
  7285. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7286. this._localWorld = BABYLON.Matrix.Zero();
  7287. this._worldMatrix = BABYLON.Matrix.Zero();
  7288. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7289. this._absolutePosition = BABYLON.Vector3.Zero();
  7290. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7291. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7292. this._isDirty = false;
  7293. this._pivotMatrix = BABYLON.Matrix.Identity();
  7294. this._isDisposed = false;
  7295. this._renderId = 0;
  7296. this._intersectionsInProgress = new Array();
  7297. scene.meshes.push(this);
  7298. }
  7299. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7300. get: function () {
  7301. return AbstractMesh._BILLBOARDMODE_NONE;
  7302. },
  7303. enumerable: true,
  7304. configurable: true
  7305. });
  7306. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7307. get: function () {
  7308. return AbstractMesh._BILLBOARDMODE_X;
  7309. },
  7310. enumerable: true,
  7311. configurable: true
  7312. });
  7313. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7314. get: function () {
  7315. return AbstractMesh._BILLBOARDMODE_Y;
  7316. },
  7317. enumerable: true,
  7318. configurable: true
  7319. });
  7320. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7321. get: function () {
  7322. return AbstractMesh._BILLBOARDMODE_Z;
  7323. },
  7324. enumerable: true,
  7325. configurable: true
  7326. });
  7327. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7328. get: function () {
  7329. return AbstractMesh._BILLBOARDMODE_ALL;
  7330. },
  7331. enumerable: true,
  7332. configurable: true
  7333. });
  7334. AbstractMesh.prototype.getTotalVertices = function () {
  7335. return 0;
  7336. };
  7337. AbstractMesh.prototype.getIndices = function () {
  7338. return null;
  7339. };
  7340. AbstractMesh.prototype.getVerticesData = function (kind) {
  7341. return null;
  7342. };
  7343. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7344. return false;
  7345. };
  7346. AbstractMesh.prototype.getBoundingInfo = function () {
  7347. if (!this._boundingInfo) {
  7348. this._updateBoundingInfo();
  7349. }
  7350. return this._boundingInfo;
  7351. };
  7352. AbstractMesh.prototype._preActivate = function () {
  7353. };
  7354. AbstractMesh.prototype._activate = function (renderId) {
  7355. this._renderId = renderId;
  7356. };
  7357. AbstractMesh.prototype.getWorldMatrix = function () {
  7358. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7359. this.computeWorldMatrix();
  7360. }
  7361. return this._worldMatrix;
  7362. };
  7363. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7364. get: function () {
  7365. return this._worldMatrix;
  7366. },
  7367. enumerable: true,
  7368. configurable: true
  7369. });
  7370. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7371. get: function () {
  7372. return this._absolutePosition;
  7373. },
  7374. enumerable: true,
  7375. configurable: true
  7376. });
  7377. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7378. if (!this.rotationQuaternion) {
  7379. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7380. this.rotation = BABYLON.Vector3.Zero();
  7381. }
  7382. if (!space || space == 0 /* LOCAL */) {
  7383. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7384. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7385. } else {
  7386. if (this.parent) {
  7387. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7388. invertParentWorldMatrix.invert();
  7389. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7390. }
  7391. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7392. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7393. }
  7394. };
  7395. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7396. var displacementVector = axis.scale(distance);
  7397. if (!space || space == 0 /* LOCAL */) {
  7398. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7399. this.setPositionWithLocalVector(tempV3);
  7400. } else {
  7401. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7402. }
  7403. };
  7404. AbstractMesh.prototype.getAbsolutePosition = function () {
  7405. this.computeWorldMatrix();
  7406. return this._absolutePosition;
  7407. };
  7408. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7409. if (!absolutePosition) {
  7410. return;
  7411. }
  7412. var absolutePositionX;
  7413. var absolutePositionY;
  7414. var absolutePositionZ;
  7415. if (absolutePosition.x === undefined) {
  7416. if (arguments.length < 3) {
  7417. return;
  7418. }
  7419. absolutePositionX = arguments[0];
  7420. absolutePositionY = arguments[1];
  7421. absolutePositionZ = arguments[2];
  7422. } else {
  7423. absolutePositionX = absolutePosition.x;
  7424. absolutePositionY = absolutePosition.y;
  7425. absolutePositionZ = absolutePosition.z;
  7426. }
  7427. if (this.parent) {
  7428. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7429. invertParentWorldMatrix.invert();
  7430. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7431. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7432. } else {
  7433. this.position.x = absolutePositionX;
  7434. this.position.y = absolutePositionY;
  7435. this.position.z = absolutePositionZ;
  7436. }
  7437. };
  7438. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7439. this._pivotMatrix = matrix;
  7440. this._cache.pivotMatrixUpdated = true;
  7441. };
  7442. AbstractMesh.prototype.getPivotMatrix = function () {
  7443. return this._pivotMatrix;
  7444. };
  7445. AbstractMesh.prototype._isSynchronized = function () {
  7446. if (this._isDirty) {
  7447. return false;
  7448. }
  7449. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7450. return false;
  7451. if (this._cache.pivotMatrixUpdated) {
  7452. return false;
  7453. }
  7454. if (this.infiniteDistance) {
  7455. return false;
  7456. }
  7457. if (!this._cache.position.equals(this.position))
  7458. return false;
  7459. if (this.rotationQuaternion) {
  7460. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7461. return false;
  7462. } else {
  7463. if (!this._cache.rotation.equals(this.rotation))
  7464. return false;
  7465. }
  7466. if (!this._cache.scaling.equals(this.scaling))
  7467. return false;
  7468. return true;
  7469. };
  7470. AbstractMesh.prototype._initCache = function () {
  7471. _super.prototype._initCache.call(this);
  7472. this._cache.localMatrixUpdated = false;
  7473. this._cache.position = BABYLON.Vector3.Zero();
  7474. this._cache.scaling = BABYLON.Vector3.Zero();
  7475. this._cache.rotation = BABYLON.Vector3.Zero();
  7476. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7477. };
  7478. AbstractMesh.prototype.markAsDirty = function (property) {
  7479. if (property === "rotation") {
  7480. this.rotationQuaternion = null;
  7481. }
  7482. this._currentRenderId = Number.MAX_VALUE;
  7483. this._isDirty = true;
  7484. };
  7485. AbstractMesh.prototype._updateBoundingInfo = function () {
  7486. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7487. this._boundingInfo._update(this.worldMatrixFromCache);
  7488. if (!this.subMeshes) {
  7489. return;
  7490. }
  7491. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7492. var subMesh = this.subMeshes[subIndex];
  7493. subMesh.updateBoundingInfo(this.worldMatrixFromCache);
  7494. }
  7495. };
  7496. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7497. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  7498. return this._worldMatrix;
  7499. }
  7500. this._cache.position.copyFrom(this.position);
  7501. this._cache.scaling.copyFrom(this.scaling);
  7502. this._cache.pivotMatrixUpdated = false;
  7503. this._currentRenderId = this.getScene().getRenderId();
  7504. this._isDirty = false;
  7505. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7506. if (this.rotationQuaternion) {
  7507. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7508. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7509. } else {
  7510. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7511. this._cache.rotation.copyFrom(this.rotation);
  7512. }
  7513. if (this.infiniteDistance && !this.parent) {
  7514. var camera = this.getScene().activeCamera;
  7515. var cameraWorldMatrix = camera.getWorldMatrix();
  7516. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7517. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7518. } else {
  7519. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7520. }
  7521. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7522. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7523. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7524. var localPosition = this.position.clone();
  7525. var zero = this.getScene().activeCamera.position.clone();
  7526. if (this.parent && this.parent.position) {
  7527. localPosition.addInPlace(this.parent.position);
  7528. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7529. }
  7530. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  7531. zero = this.getScene().activeCamera.position;
  7532. } else {
  7533. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  7534. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7535. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  7536. zero.y = localPosition.y + 0.001;
  7537. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  7538. zero.z = localPosition.z + 0.001;
  7539. }
  7540. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7541. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7542. this._localBillboard.invert();
  7543. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7544. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7545. }
  7546. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7547. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  7548. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7549. } else {
  7550. this._worldMatrix.copyFrom(this._localWorld);
  7551. }
  7552. this._updateBoundingInfo();
  7553. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7554. return this._worldMatrix;
  7555. };
  7556. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7557. this.computeWorldMatrix();
  7558. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7559. };
  7560. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7561. this.computeWorldMatrix();
  7562. var invLocalWorldMatrix = this._localWorld.clone();
  7563. invLocalWorldMatrix.invert();
  7564. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7565. };
  7566. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7567. this.computeWorldMatrix();
  7568. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7569. };
  7570. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7571. yawCor = yawCor || 0;
  7572. pitchCor = pitchCor || 0;
  7573. rollCor = rollCor || 0;
  7574. var dv = targetPoint.subtract(this.position);
  7575. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7576. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7577. var pitch = Math.atan2(dv.y, len);
  7578. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7579. };
  7580. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7581. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  7582. return false;
  7583. }
  7584. return true;
  7585. };
  7586. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7587. if (!this._boundingInfo || !mesh._boundingInfo) {
  7588. return false;
  7589. }
  7590. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7591. };
  7592. AbstractMesh.prototype.intersectsPoint = function (point) {
  7593. if (!this._boundingInfo) {
  7594. return false;
  7595. }
  7596. return this._boundingInfo.intersectsPoint(point);
  7597. };
  7598. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  7599. var physicsEngine = this.getScene().getPhysicsEngine();
  7600. if (!physicsEngine) {
  7601. return;
  7602. }
  7603. if (impostor.impostor) {
  7604. options = impostor;
  7605. impostor = impostor.impostor;
  7606. }
  7607. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  7608. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  7609. physicsEngine._unregisterMesh(this);
  7610. return;
  7611. }
  7612. options.mass = options.mass || 0;
  7613. options.friction = options.friction || 0.2;
  7614. options.restitution = options.restitution || 0.2;
  7615. this._physicImpostor = impostor;
  7616. this._physicsMass = options.mass;
  7617. this._physicsFriction = options.friction;
  7618. this._physicRestitution = options.restitution;
  7619. physicsEngine._registerMesh(this, impostor, options);
  7620. };
  7621. AbstractMesh.prototype.getPhysicsImpostor = function () {
  7622. if (!this._physicImpostor) {
  7623. return BABYLON.PhysicsEngine.NoImpostor;
  7624. }
  7625. return this._physicImpostor;
  7626. };
  7627. AbstractMesh.prototype.getPhysicsMass = function () {
  7628. if (!this._physicsMass) {
  7629. return 0;
  7630. }
  7631. return this._physicsMass;
  7632. };
  7633. AbstractMesh.prototype.getPhysicsFriction = function () {
  7634. if (!this._physicsFriction) {
  7635. return 0;
  7636. }
  7637. return this._physicsFriction;
  7638. };
  7639. AbstractMesh.prototype.getPhysicsRestitution = function () {
  7640. if (!this._physicRestitution) {
  7641. return 0;
  7642. }
  7643. return this._physicRestitution;
  7644. };
  7645. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  7646. if (!this._physicImpostor) {
  7647. return;
  7648. }
  7649. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  7650. };
  7651. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  7652. if (!this._physicImpostor) {
  7653. return;
  7654. }
  7655. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  7656. };
  7657. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  7658. if (!this._physicImpostor) {
  7659. return;
  7660. }
  7661. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  7662. };
  7663. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  7664. var globalPosition = this.getAbsolutePosition();
  7665. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  7666. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  7667. this._collider.radius = this.ellipsoid;
  7668. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  7669. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  7670. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7671. this.position.addInPlace(this._diffPositionForCollisions);
  7672. }
  7673. };
  7674. /**
  7675. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  7676. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  7677. */
  7678. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  7679. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7680. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7681. if (!this._submeshesOctree) {
  7682. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  7683. }
  7684. this.computeWorldMatrix(true);
  7685. var bbox = this.getBoundingInfo().boundingBox;
  7686. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  7687. return this._submeshesOctree;
  7688. };
  7689. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  7690. this._generatePointsArray();
  7691. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  7692. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  7693. subMesh._lastColliderWorldVertices = [];
  7694. subMesh._trianglePlanes = [];
  7695. var start = subMesh.verticesStart;
  7696. var end = (subMesh.verticesStart + subMesh.verticesCount);
  7697. for (var i = start; i < end; i++) {
  7698. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  7699. }
  7700. }
  7701. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  7702. };
  7703. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  7704. var subMeshes;
  7705. var len;
  7706. if (this._submeshesOctree && this.useOctreeForCollisions) {
  7707. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  7708. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  7709. len = intersections.length;
  7710. subMeshes = intersections.data;
  7711. } else {
  7712. subMeshes = this.subMeshes;
  7713. len = subMeshes.length;
  7714. }
  7715. for (var index = 0; index < len; index++) {
  7716. var subMesh = subMeshes[index];
  7717. if (len > 1 && !subMesh._checkCollision(collider))
  7718. continue;
  7719. this._collideForSubMesh(subMesh, transformMatrix, collider);
  7720. }
  7721. };
  7722. AbstractMesh.prototype._checkCollision = function (collider) {
  7723. if (!this._boundingInfo._checkCollision(collider))
  7724. return;
  7725. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  7726. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  7727. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  7728. };
  7729. AbstractMesh.prototype._generatePointsArray = function () {
  7730. return false;
  7731. };
  7732. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  7733. var pickingInfo = new BABYLON.PickingInfo();
  7734. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  7735. return pickingInfo;
  7736. }
  7737. if (!this._generatePointsArray()) {
  7738. return pickingInfo;
  7739. }
  7740. var intersectInfo = null;
  7741. var subMeshes;
  7742. var len;
  7743. if (this._submeshesOctree && this.useOctreeForPicking) {
  7744. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  7745. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  7746. len = intersections.length;
  7747. subMeshes = intersections.data;
  7748. } else {
  7749. subMeshes = this.subMeshes;
  7750. len = subMeshes.length;
  7751. }
  7752. for (var index = 0; index < len; index++) {
  7753. var subMesh = subMeshes[index];
  7754. if (len > 1 && !subMesh.canIntersects(ray))
  7755. continue;
  7756. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  7757. if (currentIntersectInfo) {
  7758. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  7759. intersectInfo = currentIntersectInfo;
  7760. if (fastCheck) {
  7761. break;
  7762. }
  7763. }
  7764. }
  7765. }
  7766. if (intersectInfo) {
  7767. var world = this.getWorldMatrix();
  7768. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  7769. var direction = ray.direction.clone();
  7770. direction.normalize();
  7771. direction = direction.scale(intersectInfo.distance);
  7772. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  7773. var pickedPoint = worldOrigin.add(worldDirection);
  7774. pickingInfo.hit = true;
  7775. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  7776. pickingInfo.pickedPoint = pickedPoint;
  7777. pickingInfo.pickedMesh = this;
  7778. pickingInfo.bu = intersectInfo.bu;
  7779. pickingInfo.bv = intersectInfo.bv;
  7780. pickingInfo.faceId = intersectInfo.faceId;
  7781. return pickingInfo;
  7782. }
  7783. return pickingInfo;
  7784. };
  7785. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  7786. return null;
  7787. };
  7788. AbstractMesh.prototype.releaseSubMeshes = function () {
  7789. if (this.subMeshes) {
  7790. while (this.subMeshes.length) {
  7791. this.subMeshes[0].dispose();
  7792. }
  7793. } else {
  7794. this.subMeshes = new Array();
  7795. }
  7796. };
  7797. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  7798. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  7799. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  7800. }
  7801. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  7802. var other = this._intersectionsInProgress[index];
  7803. var pos = other._intersectionsInProgress.indexOf(this);
  7804. other._intersectionsInProgress.splice(pos, 1);
  7805. }
  7806. this._intersectionsInProgress = [];
  7807. this.releaseSubMeshes();
  7808. var index = this.getScene().meshes.indexOf(this);
  7809. if (index != -1) {
  7810. this.getScene().meshes.splice(index, 1);
  7811. }
  7812. if (!doNotRecurse) {
  7813. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  7814. if (this.getScene().particleSystems[index].emitter == this) {
  7815. this.getScene().particleSystems[index].dispose();
  7816. index--;
  7817. }
  7818. }
  7819. var objects = this.getScene().meshes.slice(0);
  7820. for (index = 0; index < objects.length; index++) {
  7821. if (objects[index].parent == this) {
  7822. objects[index].dispose();
  7823. }
  7824. }
  7825. } else {
  7826. for (index = 0; index < this.getScene().meshes.length; index++) {
  7827. var obj = this.getScene().meshes[index];
  7828. if (obj.parent === this) {
  7829. obj.parent = null;
  7830. obj.computeWorldMatrix(true);
  7831. }
  7832. }
  7833. }
  7834. this._isDisposed = true;
  7835. if (this.onDispose) {
  7836. this.onDispose();
  7837. }
  7838. };
  7839. AbstractMesh._BILLBOARDMODE_NONE = 0;
  7840. AbstractMesh._BILLBOARDMODE_X = 1;
  7841. AbstractMesh._BILLBOARDMODE_Y = 2;
  7842. AbstractMesh._BILLBOARDMODE_Z = 4;
  7843. AbstractMesh._BILLBOARDMODE_ALL = 7;
  7844. return AbstractMesh;
  7845. })(BABYLON.Node);
  7846. BABYLON.AbstractMesh = AbstractMesh;
  7847. })(BABYLON || (BABYLON = {}));
  7848. var __extends = this.__extends || function (d, b) {
  7849. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7850. function __() { this.constructor = d; }
  7851. __.prototype = b.prototype;
  7852. d.prototype = new __();
  7853. };
  7854. var BABYLON;
  7855. (function (BABYLON) {
  7856. var _InstancesBatch = (function () {
  7857. function _InstancesBatch() {
  7858. this.mustReturn = false;
  7859. this.visibleInstances = new Array();
  7860. this.renderSelf = new Array();
  7861. }
  7862. return _InstancesBatch;
  7863. })();
  7864. BABYLON._InstancesBatch = _InstancesBatch;
  7865. var Mesh = (function (_super) {
  7866. __extends(Mesh, _super);
  7867. function Mesh(name, scene) {
  7868. _super.call(this, name, scene);
  7869. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  7870. this.instances = new Array();
  7871. this._onBeforeRenderCallbacks = new Array();
  7872. this._onAfterRenderCallbacks = new Array();
  7873. this._visibleInstances = {};
  7874. this._renderIdForInstances = new Array();
  7875. this._batchCache = new _InstancesBatch();
  7876. this._instancesBufferSize = 32 * 16 * 4;
  7877. }
  7878. Mesh.prototype.getTotalVertices = function () {
  7879. if (!this._geometry) {
  7880. return 0;
  7881. }
  7882. return this._geometry.getTotalVertices();
  7883. };
  7884. Mesh.prototype.getVerticesData = function (kind) {
  7885. if (!this._geometry) {
  7886. return null;
  7887. }
  7888. return this._geometry.getVerticesData(kind);
  7889. };
  7890. Mesh.prototype.getVertexBuffer = function (kind) {
  7891. if (!this._geometry) {
  7892. return undefined;
  7893. }
  7894. return this._geometry.getVertexBuffer(kind);
  7895. };
  7896. Mesh.prototype.isVerticesDataPresent = function (kind) {
  7897. if (!this._geometry) {
  7898. if (this._delayInfo) {
  7899. return this._delayInfo.indexOf(kind) !== -1;
  7900. }
  7901. return false;
  7902. }
  7903. return this._geometry.isVerticesDataPresent(kind);
  7904. };
  7905. Mesh.prototype.getVerticesDataKinds = function () {
  7906. if (!this._geometry) {
  7907. var result = [];
  7908. if (this._delayInfo) {
  7909. for (var kind in this._delayInfo) {
  7910. result.push(kind);
  7911. }
  7912. }
  7913. return result;
  7914. }
  7915. return this._geometry.getVerticesDataKinds();
  7916. };
  7917. Mesh.prototype.getTotalIndices = function () {
  7918. if (!this._geometry) {
  7919. return 0;
  7920. }
  7921. return this._geometry.getTotalIndices();
  7922. };
  7923. Mesh.prototype.getIndices = function () {
  7924. if (!this._geometry) {
  7925. return [];
  7926. }
  7927. return this._geometry.getIndices();
  7928. };
  7929. Mesh.prototype.isReady = function () {
  7930. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7931. return false;
  7932. }
  7933. return _super.prototype.isReady.call(this);
  7934. };
  7935. Mesh.prototype.isDisposed = function () {
  7936. return this._isDisposed;
  7937. };
  7938. Mesh.prototype._preActivate = function () {
  7939. var sceneRenderId = this.getScene().getRenderId();
  7940. if (this._preActivateId == sceneRenderId) {
  7941. return;
  7942. }
  7943. this._preActivateId = sceneRenderId;
  7944. this._visibleInstances = null;
  7945. };
  7946. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  7947. if (!this._visibleInstances) {
  7948. this._visibleInstances = {};
  7949. this._visibleInstances.defaultRenderId = renderId;
  7950. this._visibleInstances.selfDefaultRenderId = this._renderId;
  7951. }
  7952. if (!this._visibleInstances[renderId]) {
  7953. this._visibleInstances[renderId] = new Array();
  7954. }
  7955. this._visibleInstances[renderId].push(instance);
  7956. };
  7957. Mesh.prototype.refreshBoundingInfo = function () {
  7958. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7959. if (data) {
  7960. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  7961. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  7962. }
  7963. if (this.subMeshes) {
  7964. for (var index = 0; index < this.subMeshes.length; index++) {
  7965. this.subMeshes[index].refreshBoundingInfo();
  7966. }
  7967. }
  7968. this._updateBoundingInfo();
  7969. };
  7970. Mesh.prototype._createGlobalSubMesh = function () {
  7971. var totalVertices = this.getTotalVertices();
  7972. if (!totalVertices || !this.getIndices()) {
  7973. return null;
  7974. }
  7975. this.releaseSubMeshes();
  7976. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  7977. };
  7978. Mesh.prototype.subdivide = function (count) {
  7979. if (count < 1) {
  7980. return;
  7981. }
  7982. var totalIndices = this.getTotalIndices();
  7983. var subdivisionSize = (totalIndices / count) | 0;
  7984. var offset = 0;
  7985. while (subdivisionSize % 3 != 0) {
  7986. subdivisionSize++;
  7987. }
  7988. this.releaseSubMeshes();
  7989. for (var index = 0; index < count; index++) {
  7990. if (offset >= totalIndices) {
  7991. break;
  7992. }
  7993. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  7994. offset += subdivisionSize;
  7995. }
  7996. this.synchronizeInstances();
  7997. };
  7998. Mesh.prototype.setVerticesData = function (kind, data, updatable) {
  7999. if (kind instanceof Array) {
  8000. var temp = data;
  8001. data = kind;
  8002. kind = temp;
  8003. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  8004. }
  8005. if (!this._geometry) {
  8006. var vertexData = new BABYLON.VertexData();
  8007. vertexData.set(data, kind);
  8008. var scene = this.getScene();
  8009. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  8010. } else {
  8011. this._geometry.setVerticesData(kind, data, updatable);
  8012. }
  8013. };
  8014. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  8015. if (!this._geometry) {
  8016. return;
  8017. }
  8018. if (!makeItUnique) {
  8019. this._geometry.updateVerticesData(kind, data, updateExtends);
  8020. } else {
  8021. this.makeGeometryUnique();
  8022. this.updateVerticesData(kind, data, updateExtends, false);
  8023. }
  8024. };
  8025. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, makeItUnique) {
  8026. if (!this._geometry) {
  8027. return;
  8028. }
  8029. if (!makeItUnique) {
  8030. this._geometry.updateVerticesDataDirectly(kind, data);
  8031. } else {
  8032. this.makeGeometryUnique();
  8033. this.updateVerticesDataDirectly(kind, data, false);
  8034. }
  8035. };
  8036. Mesh.prototype.makeGeometryUnique = function () {
  8037. if (!this._geometry) {
  8038. return;
  8039. }
  8040. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  8041. geometry.applyToMesh(this);
  8042. };
  8043. Mesh.prototype.setIndices = function (indices) {
  8044. if (!this._geometry) {
  8045. var vertexData = new BABYLON.VertexData();
  8046. vertexData.indices = indices;
  8047. var scene = this.getScene();
  8048. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  8049. } else {
  8050. this._geometry.setIndices(indices);
  8051. }
  8052. };
  8053. Mesh.prototype._bind = function (subMesh, effect, wireframe) {
  8054. var engine = this.getScene().getEngine();
  8055. var indexToBind = this._geometry.getIndexBuffer();
  8056. if (wireframe) {
  8057. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  8058. }
  8059. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  8060. };
  8061. Mesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  8062. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8063. return;
  8064. }
  8065. var engine = this.getScene().getEngine();
  8066. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  8067. };
  8068. Mesh.prototype._fullDraw = function (subMesh, useTriangles, instancesCount) {
  8069. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8070. return;
  8071. }
  8072. var engine = this.getScene().getEngine();
  8073. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  8074. };
  8075. Mesh.prototype.registerBeforeRender = function (func) {
  8076. this._onBeforeRenderCallbacks.push(func);
  8077. };
  8078. Mesh.prototype.unregisterBeforeRender = function (func) {
  8079. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8080. if (index > -1) {
  8081. this._onBeforeRenderCallbacks.splice(index, 1);
  8082. }
  8083. };
  8084. Mesh.prototype.registerAfterRender = function (func) {
  8085. this._onAfterRenderCallbacks.push(func);
  8086. };
  8087. Mesh.prototype.unregisterAfterRender = function (func) {
  8088. var index = this._onAfterRenderCallbacks.indexOf(func);
  8089. if (index > -1) {
  8090. this._onAfterRenderCallbacks.splice(index, 1);
  8091. }
  8092. };
  8093. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  8094. var scene = this.getScene();
  8095. this._batchCache.mustReturn = false;
  8096. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  8097. this._batchCache.visibleInstances[subMeshId] = null;
  8098. if (this._visibleInstances) {
  8099. var currentRenderId = scene.getRenderId();
  8100. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  8101. var selfRenderId = this._renderId;
  8102. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  8103. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  8104. currentRenderId = this._visibleInstances.defaultRenderId;
  8105. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  8106. }
  8107. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  8108. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  8109. this._batchCache.mustReturn = true;
  8110. return this._batchCache;
  8111. }
  8112. if (currentRenderId !== selfRenderId) {
  8113. this._batchCache.renderSelf[subMeshId] = false;
  8114. }
  8115. }
  8116. this._renderIdForInstances[subMeshId] = currentRenderId;
  8117. }
  8118. return this._batchCache;
  8119. };
  8120. Mesh.prototype._renderWithInstances = function (subMesh, wireFrame, batch, effect, engine) {
  8121. var matricesCount = this.instances.length + 1;
  8122. var bufferSize = matricesCount * 16 * 4;
  8123. while (this._instancesBufferSize < bufferSize) {
  8124. this._instancesBufferSize *= 2;
  8125. }
  8126. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  8127. if (this._worldMatricesInstancesBuffer) {
  8128. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8129. }
  8130. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  8131. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  8132. }
  8133. var offset = 0;
  8134. var instancesCount = 0;
  8135. var world = this.getWorldMatrix();
  8136. if (batch.renderSelf[subMesh._id]) {
  8137. world.copyToArray(this._worldMatricesInstancesArray, offset);
  8138. offset += 16;
  8139. instancesCount++;
  8140. }
  8141. var visibleInstances = batch.visibleInstances[subMesh._id];
  8142. if (visibleInstances) {
  8143. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  8144. var instance = visibleInstances[instanceIndex];
  8145. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  8146. offset += 16;
  8147. instancesCount++;
  8148. }
  8149. }
  8150. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  8151. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  8152. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  8153. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  8154. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  8155. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  8156. this._draw(subMesh, !wireFrame, instancesCount);
  8157. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  8158. };
  8159. Mesh.prototype.render = function (subMesh) {
  8160. var scene = this.getScene();
  8161. var batch = this._getInstancesRenderList(subMesh._id);
  8162. if (batch.mustReturn) {
  8163. return;
  8164. }
  8165. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8166. return;
  8167. }
  8168. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8169. this._onBeforeRenderCallbacks[callbackIndex]();
  8170. }
  8171. var engine = scene.getEngine();
  8172. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8173. var effectiveMaterial = subMesh.getMaterial();
  8174. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  8175. return;
  8176. }
  8177. var savedDepthWrite = engine.getDepthWrite();
  8178. if (this.renderOutline) {
  8179. engine.setDepthWrite(false);
  8180. scene.getOutlineRenderer().render(subMesh, batch);
  8181. }
  8182. effectiveMaterial._preBind();
  8183. var effect = effectiveMaterial.getEffect();
  8184. var wireFrame = engine.forceWireframe || effectiveMaterial.wireframe;
  8185. this._bind(subMesh, effect, wireFrame);
  8186. var world = this.getWorldMatrix();
  8187. effectiveMaterial.bind(world, this);
  8188. if (hardwareInstancedRendering) {
  8189. this._renderWithInstances(subMesh, wireFrame, batch, effect, engine);
  8190. } else {
  8191. if (batch.renderSelf[subMesh._id]) {
  8192. this._draw(subMesh, !wireFrame);
  8193. }
  8194. if (batch.visibleInstances[subMesh._id]) {
  8195. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  8196. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  8197. world = instance.getWorldMatrix();
  8198. effectiveMaterial.bindOnlyWorldMatrix(world);
  8199. this._draw(subMesh, !wireFrame);
  8200. }
  8201. }
  8202. }
  8203. effectiveMaterial.unbind();
  8204. if (this.renderOutline && savedDepthWrite) {
  8205. engine.setDepthWrite(true);
  8206. engine.setColorWrite(false);
  8207. scene.getOutlineRenderer().render(subMesh, batch);
  8208. engine.setColorWrite(true);
  8209. }
  8210. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8211. this._onAfterRenderCallbacks[callbackIndex]();
  8212. }
  8213. };
  8214. Mesh.prototype.getEmittedParticleSystems = function () {
  8215. var results = new Array();
  8216. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8217. var particleSystem = this.getScene().particleSystems[index];
  8218. if (particleSystem.emitter === this) {
  8219. results.push(particleSystem);
  8220. }
  8221. }
  8222. return results;
  8223. };
  8224. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  8225. var results = new Array();
  8226. var descendants = this.getDescendants();
  8227. descendants.push(this);
  8228. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8229. var particleSystem = this.getScene().particleSystems[index];
  8230. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  8231. results.push(particleSystem);
  8232. }
  8233. }
  8234. return results;
  8235. };
  8236. Mesh.prototype.getChildren = function () {
  8237. var results = [];
  8238. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8239. var mesh = this.getScene().meshes[index];
  8240. if (mesh.parent == this) {
  8241. results.push(mesh);
  8242. }
  8243. }
  8244. return results;
  8245. };
  8246. Mesh.prototype._checkDelayState = function () {
  8247. var _this = this;
  8248. var that = this;
  8249. var scene = this.getScene();
  8250. if (this._geometry) {
  8251. this._geometry.load(scene);
  8252. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8253. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  8254. scene._addPendingData(that);
  8255. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  8256. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  8257. if (data instanceof ArrayBuffer) {
  8258. _this._delayLoadingFunction(data, _this);
  8259. } else {
  8260. _this._delayLoadingFunction(JSON.parse(data), _this);
  8261. }
  8262. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  8263. scene._removePendingData(_this);
  8264. }, function () {
  8265. }, scene.database, getBinaryData);
  8266. }
  8267. };
  8268. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  8269. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8270. return false;
  8271. }
  8272. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  8273. return false;
  8274. }
  8275. this._checkDelayState();
  8276. return true;
  8277. };
  8278. Mesh.prototype.setMaterialByID = function (id) {
  8279. var materials = this.getScene().materials;
  8280. for (var index = 0; index < materials.length; index++) {
  8281. if (materials[index].id == id) {
  8282. this.material = materials[index];
  8283. return;
  8284. }
  8285. }
  8286. var multiMaterials = this.getScene().multiMaterials;
  8287. for (index = 0; index < multiMaterials.length; index++) {
  8288. if (multiMaterials[index].id == id) {
  8289. this.material = multiMaterials[index];
  8290. return;
  8291. }
  8292. }
  8293. };
  8294. Mesh.prototype.getAnimatables = function () {
  8295. var results = [];
  8296. if (this.material) {
  8297. results.push(this.material);
  8298. }
  8299. if (this.skeleton) {
  8300. results.push(this.skeleton);
  8301. }
  8302. return results;
  8303. };
  8304. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  8305. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  8306. return;
  8307. }
  8308. this._resetPointsArrayCache();
  8309. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8310. var temp = [];
  8311. for (var index = 0; index < data.length; index += 3) {
  8312. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8313. }
  8314. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  8315. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8316. return;
  8317. }
  8318. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8319. for (index = 0; index < data.length; index += 3) {
  8320. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8321. }
  8322. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  8323. };
  8324. Mesh.prototype._resetPointsArrayCache = function () {
  8325. this._positions = null;
  8326. };
  8327. Mesh.prototype._generatePointsArray = function () {
  8328. if (this._positions)
  8329. return true;
  8330. this._positions = [];
  8331. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8332. if (!data) {
  8333. return false;
  8334. }
  8335. for (var index = 0; index < data.length; index += 3) {
  8336. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  8337. }
  8338. return true;
  8339. };
  8340. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8341. var result = new BABYLON.Mesh(name, this.getScene());
  8342. this._geometry.applyToMesh(result);
  8343. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  8344. result.material = this.material;
  8345. if (newParent) {
  8346. result.parent = newParent;
  8347. }
  8348. if (!doNotCloneChildren) {
  8349. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8350. var mesh = this.getScene().meshes[index];
  8351. if (mesh.parent == this) {
  8352. mesh.clone(mesh.name, result);
  8353. }
  8354. }
  8355. }
  8356. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8357. var system = this.getScene().particleSystems[index];
  8358. if (system.emitter == this) {
  8359. system.clone(system.name, result);
  8360. }
  8361. }
  8362. result.computeWorldMatrix(true);
  8363. return result;
  8364. };
  8365. Mesh.prototype.dispose = function (doNotRecurse) {
  8366. if (this._geometry) {
  8367. this._geometry.releaseForMesh(this, true);
  8368. }
  8369. if (this._worldMatricesInstancesBuffer) {
  8370. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8371. this._worldMatricesInstancesBuffer = null;
  8372. }
  8373. while (this.instances.length) {
  8374. this.instances[0].dispose();
  8375. }
  8376. _super.prototype.dispose.call(this, doNotRecurse);
  8377. };
  8378. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  8379. var _this = this;
  8380. var scene = this.getScene();
  8381. var onload = function (img) {
  8382. var canvas = document.createElement("canvas");
  8383. var context = canvas.getContext("2d");
  8384. var heightMapWidth = img.width;
  8385. var heightMapHeight = img.height;
  8386. canvas.width = heightMapWidth;
  8387. canvas.height = heightMapHeight;
  8388. context.drawImage(img, 0, 0);
  8389. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8390. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  8391. };
  8392. BABYLON.Tools.LoadImage(url, onload, function () {
  8393. }, scene.database);
  8394. };
  8395. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  8396. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8397. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  8398. return;
  8399. }
  8400. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8401. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8402. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8403. var position = BABYLON.Vector3.Zero();
  8404. var normal = BABYLON.Vector3.Zero();
  8405. var uv = BABYLON.Vector2.Zero();
  8406. for (var index = 0; index < positions.length; index += 3) {
  8407. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  8408. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  8409. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  8410. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  8411. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  8412. var pos = (u + v * heightMapWidth) * 4;
  8413. var r = buffer[pos] / 255.0;
  8414. var g = buffer[pos + 1] / 255.0;
  8415. var b = buffer[pos + 2] / 255.0;
  8416. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  8417. normal.normalize();
  8418. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  8419. position = position.add(normal);
  8420. position.toArray(positions, index);
  8421. }
  8422. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  8423. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  8424. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  8425. };
  8426. Mesh.prototype.convertToFlatShadedMesh = function () {
  8427. var kinds = this.getVerticesDataKinds();
  8428. var vbs = [];
  8429. var data = [];
  8430. var newdata = [];
  8431. var updatableNormals = false;
  8432. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8433. var kind = kinds[kindIndex];
  8434. var vertexBuffer = this.getVertexBuffer(kind);
  8435. if (kind === BABYLON.VertexBuffer.NormalKind) {
  8436. updatableNormals = vertexBuffer.isUpdatable();
  8437. kinds.splice(kindIndex, 1);
  8438. kindIndex--;
  8439. continue;
  8440. }
  8441. vbs[kind] = vertexBuffer;
  8442. data[kind] = vbs[kind].getData();
  8443. newdata[kind] = [];
  8444. }
  8445. var previousSubmeshes = this.subMeshes.slice(0);
  8446. var indices = this.getIndices();
  8447. var totalIndices = this.getTotalIndices();
  8448. for (index = 0; index < totalIndices; index++) {
  8449. var vertexIndex = indices[index];
  8450. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8451. kind = kinds[kindIndex];
  8452. var stride = vbs[kind].getStrideSize();
  8453. for (var offset = 0; offset < stride; offset++) {
  8454. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  8455. }
  8456. }
  8457. }
  8458. var normals = [];
  8459. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  8460. for (var index = 0; index < totalIndices; index += 3) {
  8461. indices[index] = index;
  8462. indices[index + 1] = index + 1;
  8463. indices[index + 2] = index + 2;
  8464. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  8465. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  8466. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  8467. var p1p2 = p1.subtract(p2);
  8468. var p3p2 = p3.subtract(p2);
  8469. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  8470. for (var localIndex = 0; localIndex < 3; localIndex++) {
  8471. normals.push(normal.x);
  8472. normals.push(normal.y);
  8473. normals.push(normal.z);
  8474. }
  8475. }
  8476. this.setIndices(indices);
  8477. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  8478. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8479. kind = kinds[kindIndex];
  8480. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  8481. }
  8482. this.releaseSubMeshes();
  8483. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  8484. var previousOne = previousSubmeshes[submeshIndex];
  8485. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  8486. }
  8487. this.synchronizeInstances();
  8488. };
  8489. Mesh.prototype.createInstance = function (name) {
  8490. return new BABYLON.InstancedMesh(name, this);
  8491. };
  8492. Mesh.prototype.synchronizeInstances = function () {
  8493. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  8494. var instance = this.instances[instanceIndex];
  8495. instance._syncSubMeshes();
  8496. }
  8497. };
  8498. Mesh.CreateBox = function (name, size, scene, updatable) {
  8499. var box = new BABYLON.Mesh(name, scene);
  8500. var vertexData = BABYLON.VertexData.CreateBox(size);
  8501. vertexData.applyToMesh(box, updatable);
  8502. return box;
  8503. };
  8504. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  8505. var sphere = new BABYLON.Mesh(name, scene);
  8506. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  8507. vertexData.applyToMesh(sphere, updatable);
  8508. return sphere;
  8509. };
  8510. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  8511. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  8512. if (scene !== undefined) {
  8513. updatable = scene;
  8514. }
  8515. scene = subdivisions;
  8516. subdivisions = 1;
  8517. }
  8518. var cylinder = new BABYLON.Mesh(name, scene);
  8519. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  8520. vertexData.applyToMesh(cylinder, updatable);
  8521. return cylinder;
  8522. };
  8523. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  8524. var torus = new BABYLON.Mesh(name, scene);
  8525. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  8526. vertexData.applyToMesh(torus, updatable);
  8527. return torus;
  8528. };
  8529. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  8530. var torusKnot = new BABYLON.Mesh(name, scene);
  8531. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  8532. vertexData.applyToMesh(torusKnot, updatable);
  8533. return torusKnot;
  8534. };
  8535. Mesh.CreateLines = function (name, points, scene, updatable) {
  8536. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  8537. var vertexData = BABYLON.VertexData.CreateLines(points);
  8538. vertexData.applyToMesh(lines, updatable);
  8539. return lines;
  8540. };
  8541. Mesh.CreatePlane = function (name, size, scene, updatable) {
  8542. var plane = new BABYLON.Mesh(name, scene);
  8543. var vertexData = BABYLON.VertexData.CreatePlane(size);
  8544. vertexData.applyToMesh(plane, updatable);
  8545. return plane;
  8546. };
  8547. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  8548. var ground = new BABYLON.GroundMesh(name, scene);
  8549. ground._setReady(false);
  8550. ground._subdivisions = subdivisions;
  8551. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  8552. vertexData.applyToMesh(ground, updatable);
  8553. ground._setReady(true);
  8554. return ground;
  8555. };
  8556. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  8557. var tiledGround = new BABYLON.Mesh(name, scene);
  8558. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  8559. vertexData.applyToMesh(tiledGround, updatable);
  8560. return tiledGround;
  8561. };
  8562. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  8563. var ground = new BABYLON.GroundMesh(name, scene);
  8564. ground._subdivisions = subdivisions;
  8565. ground._setReady(false);
  8566. var onload = function (img) {
  8567. var canvas = document.createElement("canvas");
  8568. var context = canvas.getContext("2d");
  8569. var heightMapWidth = img.width;
  8570. var heightMapHeight = img.height;
  8571. canvas.width = heightMapWidth;
  8572. canvas.height = heightMapHeight;
  8573. context.drawImage(img, 0, 0);
  8574. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8575. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  8576. vertexData.applyToMesh(ground, updatable);
  8577. ground._setReady(true);
  8578. };
  8579. BABYLON.Tools.LoadImage(url, onload, function () {
  8580. }, scene.database);
  8581. return ground;
  8582. };
  8583. Mesh.MinMax = function (meshes) {
  8584. var minVector = null;
  8585. var maxVector = null;
  8586. for (var i in meshes) {
  8587. var mesh = meshes[i];
  8588. var boundingBox = mesh.getBoundingInfo().boundingBox;
  8589. if (!minVector) {
  8590. minVector = boundingBox.minimumWorld;
  8591. maxVector = boundingBox.maximumWorld;
  8592. continue;
  8593. }
  8594. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  8595. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  8596. }
  8597. return {
  8598. min: minVector,
  8599. max: maxVector
  8600. };
  8601. };
  8602. Mesh.Center = function (meshesOrMinMaxVector) {
  8603. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8604. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  8605. };
  8606. return Mesh;
  8607. })(BABYLON.AbstractMesh);
  8608. BABYLON.Mesh = Mesh;
  8609. })(BABYLON || (BABYLON = {}));
  8610. var __extends = this.__extends || function (d, b) {
  8611. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8612. function __() { this.constructor = d; }
  8613. __.prototype = b.prototype;
  8614. d.prototype = new __();
  8615. };
  8616. var BABYLON;
  8617. (function (BABYLON) {
  8618. var GroundMesh = (function (_super) {
  8619. __extends(GroundMesh, _super);
  8620. function GroundMesh(name, scene) {
  8621. _super.call(this, name, scene);
  8622. this.generateOctree = false;
  8623. this._worldInverse = new BABYLON.Matrix();
  8624. }
  8625. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  8626. get: function () {
  8627. return this._subdivisions;
  8628. },
  8629. enumerable: true,
  8630. configurable: true
  8631. });
  8632. GroundMesh.prototype.optimize = function (chunksCount) {
  8633. this.subdivide(this._subdivisions);
  8634. this.createOrUpdateSubmeshesOctree(32);
  8635. };
  8636. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  8637. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  8638. this.getWorldMatrix().invertToRef(this._worldInverse);
  8639. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  8640. var pickInfo = this.intersects(ray);
  8641. if (pickInfo.hit) {
  8642. return pickInfo.pickedPoint.y;
  8643. }
  8644. return 0;
  8645. };
  8646. return GroundMesh;
  8647. })(BABYLON.Mesh);
  8648. BABYLON.GroundMesh = GroundMesh;
  8649. })(BABYLON || (BABYLON = {}));
  8650. var __extends = this.__extends || function (d, b) {
  8651. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8652. function __() { this.constructor = d; }
  8653. __.prototype = b.prototype;
  8654. d.prototype = new __();
  8655. };
  8656. var BABYLON;
  8657. (function (BABYLON) {
  8658. var InstancedMesh = (function (_super) {
  8659. __extends(InstancedMesh, _super);
  8660. function InstancedMesh(name, source) {
  8661. _super.call(this, name, source.getScene());
  8662. source.instances.push(this);
  8663. this._sourceMesh = source;
  8664. this.position.copyFrom(source.position);
  8665. this.rotation.copyFrom(source.rotation);
  8666. this.scaling.copyFrom(source.scaling);
  8667. if (source.rotationQuaternion) {
  8668. this.rotationQuaternion = source.rotationQuaternion.clone();
  8669. }
  8670. this.infiniteDistance = source.infiniteDistance;
  8671. this.setPivotMatrix(source.getPivotMatrix());
  8672. this.refreshBoundingInfo();
  8673. this._syncSubMeshes();
  8674. }
  8675. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  8676. get: function () {
  8677. return this._sourceMesh.receiveShadows;
  8678. },
  8679. enumerable: true,
  8680. configurable: true
  8681. });
  8682. Object.defineProperty(InstancedMesh.prototype, "material", {
  8683. get: function () {
  8684. return this._sourceMesh.material;
  8685. },
  8686. enumerable: true,
  8687. configurable: true
  8688. });
  8689. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  8690. get: function () {
  8691. return this._sourceMesh.visibility;
  8692. },
  8693. enumerable: true,
  8694. configurable: true
  8695. });
  8696. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  8697. get: function () {
  8698. return this._sourceMesh.skeleton;
  8699. },
  8700. enumerable: true,
  8701. configurable: true
  8702. });
  8703. InstancedMesh.prototype.getTotalVertices = function () {
  8704. return this._sourceMesh.getTotalVertices();
  8705. };
  8706. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  8707. get: function () {
  8708. return this._sourceMesh;
  8709. },
  8710. enumerable: true,
  8711. configurable: true
  8712. });
  8713. InstancedMesh.prototype.getVerticesData = function (kind) {
  8714. return this._sourceMesh.getVerticesData(kind);
  8715. };
  8716. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  8717. return this._sourceMesh.isVerticesDataPresent(kind);
  8718. };
  8719. InstancedMesh.prototype.getIndices = function () {
  8720. return this._sourceMesh.getIndices();
  8721. };
  8722. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  8723. get: function () {
  8724. return this._sourceMesh._positions;
  8725. },
  8726. enumerable: true,
  8727. configurable: true
  8728. });
  8729. InstancedMesh.prototype.refreshBoundingInfo = function () {
  8730. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8731. if (data) {
  8732. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  8733. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8734. }
  8735. this._updateBoundingInfo();
  8736. };
  8737. InstancedMesh.prototype._preActivate = function () {
  8738. this.sourceMesh._preActivate();
  8739. };
  8740. InstancedMesh.prototype._activate = function (renderId) {
  8741. this.sourceMesh._registerInstanceForRenderId(this, renderId);
  8742. };
  8743. InstancedMesh.prototype._syncSubMeshes = function () {
  8744. this.releaseSubMeshes();
  8745. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  8746. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  8747. }
  8748. };
  8749. InstancedMesh.prototype._generatePointsArray = function () {
  8750. return this._sourceMesh._generatePointsArray();
  8751. };
  8752. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8753. var result = this._sourceMesh.createInstance(name);
  8754. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  8755. this.refreshBoundingInfo();
  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. result.computeWorldMatrix(true);
  8768. return result;
  8769. };
  8770. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  8771. var index = this._sourceMesh.instances.indexOf(this);
  8772. this._sourceMesh.instances.splice(index, 1);
  8773. _super.prototype.dispose.call(this, doNotRecurse);
  8774. };
  8775. return InstancedMesh;
  8776. })(BABYLON.AbstractMesh);
  8777. BABYLON.InstancedMesh = InstancedMesh;
  8778. })(BABYLON || (BABYLON = {}));
  8779. var BABYLON;
  8780. (function (BABYLON) {
  8781. var SubMesh = (function () {
  8782. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  8783. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  8784. this.materialIndex = materialIndex;
  8785. this.verticesStart = verticesStart;
  8786. this.verticesCount = verticesCount;
  8787. this.indexStart = indexStart;
  8788. this.indexCount = indexCount;
  8789. this._renderId = 0;
  8790. this._mesh = mesh;
  8791. this._renderingMesh = renderingMesh || mesh;
  8792. mesh.subMeshes.push(this);
  8793. this._id = mesh.subMeshes.length - 1;
  8794. if (createBoundingBox) {
  8795. this.refreshBoundingInfo();
  8796. }
  8797. }
  8798. SubMesh.prototype.getBoundingInfo = function () {
  8799. return this._boundingInfo;
  8800. };
  8801. SubMesh.prototype.getMesh = function () {
  8802. return this._mesh;
  8803. };
  8804. SubMesh.prototype.getRenderingMesh = function () {
  8805. return this._renderingMesh;
  8806. };
  8807. SubMesh.prototype.getMaterial = function () {
  8808. var rootMaterial = this._renderingMesh.material;
  8809. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  8810. var multiMaterial = rootMaterial;
  8811. return multiMaterial.getSubMaterial(this.materialIndex);
  8812. }
  8813. if (!rootMaterial) {
  8814. return this._mesh.getScene().defaultMaterial;
  8815. }
  8816. return rootMaterial;
  8817. };
  8818. SubMesh.prototype.refreshBoundingInfo = function () {
  8819. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8820. if (!data) {
  8821. this._boundingInfo = this._mesh._boundingInfo;
  8822. return;
  8823. }
  8824. var indices = this._renderingMesh.getIndices();
  8825. var extend;
  8826. if (this.indexStart === 0 && this.indexCount === indices.length) {
  8827. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  8828. } else {
  8829. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  8830. }
  8831. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8832. };
  8833. SubMesh.prototype._checkCollision = function (collider) {
  8834. return this._boundingInfo._checkCollision(collider);
  8835. };
  8836. SubMesh.prototype.updateBoundingInfo = function (world) {
  8837. if (!this._boundingInfo) {
  8838. this.refreshBoundingInfo();
  8839. }
  8840. this._boundingInfo._update(world);
  8841. };
  8842. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  8843. return this._boundingInfo.isInFrustum(frustumPlanes);
  8844. };
  8845. SubMesh.prototype.render = function () {
  8846. this._renderingMesh.render(this);
  8847. };
  8848. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  8849. if (!this._linesIndexBuffer) {
  8850. var linesIndices = [];
  8851. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8852. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  8853. }
  8854. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  8855. this.linesIndexCount = linesIndices.length;
  8856. }
  8857. return this._linesIndexBuffer;
  8858. };
  8859. SubMesh.prototype.canIntersects = function (ray) {
  8860. return ray.intersectsBox(this._boundingInfo.boundingBox);
  8861. };
  8862. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  8863. var intersectInfo = null;
  8864. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  8865. var p0 = positions[indices[index]];
  8866. var p1 = positions[indices[index + 1]];
  8867. var p2 = positions[indices[index + 2]];
  8868. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  8869. if (currentIntersectInfo) {
  8870. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8871. intersectInfo = currentIntersectInfo;
  8872. intersectInfo.faceId = index / 3;
  8873. if (fastCheck) {
  8874. break;
  8875. }
  8876. }
  8877. }
  8878. }
  8879. return intersectInfo;
  8880. };
  8881. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  8882. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  8883. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  8884. return result;
  8885. };
  8886. SubMesh.prototype.dispose = function () {
  8887. if (this._linesIndexBuffer) {
  8888. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  8889. this._linesIndexBuffer = null;
  8890. }
  8891. var index = this._mesh.subMeshes.indexOf(this);
  8892. this._mesh.subMeshes.splice(index, 1);
  8893. };
  8894. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  8895. var minVertexIndex = Number.MAX_VALUE;
  8896. var maxVertexIndex = -Number.MAX_VALUE;
  8897. renderingMesh = renderingMesh || mesh;
  8898. var indices = renderingMesh.getIndices();
  8899. for (var index = startIndex; index < startIndex + indexCount; index++) {
  8900. var vertexIndex = indices[index];
  8901. if (vertexIndex < minVertexIndex)
  8902. minVertexIndex = vertexIndex;
  8903. if (vertexIndex > maxVertexIndex)
  8904. maxVertexIndex = vertexIndex;
  8905. }
  8906. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  8907. };
  8908. return SubMesh;
  8909. })();
  8910. BABYLON.SubMesh = SubMesh;
  8911. })(BABYLON || (BABYLON = {}));
  8912. var BABYLON;
  8913. (function (BABYLON) {
  8914. var BaseTexture = (function () {
  8915. function BaseTexture(scene) {
  8916. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  8917. this.hasAlpha = false;
  8918. this.getAlphaFromRGB = false;
  8919. this.level = 1;
  8920. this.isCube = false;
  8921. this.isRenderTarget = false;
  8922. this.animations = new Array();
  8923. this.coordinatesIndex = 0;
  8924. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  8925. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  8926. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  8927. this.anisotropicFilteringLevel = 4;
  8928. this._scene = scene;
  8929. this._scene.textures.push(this);
  8930. }
  8931. BaseTexture.prototype.getScene = function () {
  8932. return this._scene;
  8933. };
  8934. BaseTexture.prototype.getTextureMatrix = function () {
  8935. return null;
  8936. };
  8937. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  8938. return null;
  8939. };
  8940. BaseTexture.prototype.getInternalTexture = function () {
  8941. return this._texture;
  8942. };
  8943. BaseTexture.prototype.isReady = function () {
  8944. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8945. return true;
  8946. }
  8947. if (this._texture) {
  8948. return this._texture.isReady;
  8949. }
  8950. return false;
  8951. };
  8952. BaseTexture.prototype.getSize = function () {
  8953. if (this._texture._width) {
  8954. return { width: this._texture._width, height: this._texture._height };
  8955. }
  8956. if (this._texture._size) {
  8957. return { width: this._texture._size, height: this._texture._size };
  8958. }
  8959. return { width: 0, height: 0 };
  8960. };
  8961. BaseTexture.prototype.getBaseSize = function () {
  8962. if (!this.isReady())
  8963. return { width: 0, height: 0 };
  8964. if (this._texture._size) {
  8965. return { width: this._texture._size, height: this._texture._size };
  8966. }
  8967. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  8968. };
  8969. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  8970. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8971. for (var index = 0; index < texturesCache.length; index++) {
  8972. var texturesCacheEntry = texturesCache[index];
  8973. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  8974. texturesCacheEntry.references++;
  8975. return texturesCacheEntry;
  8976. }
  8977. }
  8978. return null;
  8979. };
  8980. BaseTexture.prototype.delayLoad = function () {
  8981. };
  8982. BaseTexture.prototype.releaseInternalTexture = function () {
  8983. if (!this._texture) {
  8984. return;
  8985. }
  8986. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  8987. this._texture.references--;
  8988. if (this._texture.references == 0) {
  8989. var index = texturesCache.indexOf(this._texture);
  8990. texturesCache.splice(index, 1);
  8991. this._scene.getEngine()._releaseTexture(this._texture);
  8992. delete this._texture;
  8993. }
  8994. };
  8995. BaseTexture.prototype.clone = function () {
  8996. return null;
  8997. };
  8998. BaseTexture.prototype.dispose = function () {
  8999. var index = this._scene.textures.indexOf(this);
  9000. if (index >= 0) {
  9001. this._scene.textures.splice(index, 1);
  9002. }
  9003. if (this._texture === undefined) {
  9004. return;
  9005. }
  9006. this.releaseInternalTexture();
  9007. if (this.onDispose) {
  9008. this.onDispose();
  9009. }
  9010. };
  9011. return BaseTexture;
  9012. })();
  9013. BABYLON.BaseTexture = BaseTexture;
  9014. })(BABYLON || (BABYLON = {}));
  9015. var BABYLON;
  9016. (function (BABYLON) {
  9017. var RenderingGroup = (function () {
  9018. function RenderingGroup(index, scene) {
  9019. this.index = index;
  9020. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  9021. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  9022. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  9023. this._scene = scene;
  9024. }
  9025. RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
  9026. if (customRenderFunction) {
  9027. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
  9028. return true;
  9029. }
  9030. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  9031. return false;
  9032. }
  9033. var engine = this._scene.getEngine();
  9034. var subIndex;
  9035. var submesh;
  9036. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  9037. submesh = this._opaqueSubMeshes.data[subIndex];
  9038. this._activeVertices += submesh.verticesCount;
  9039. submesh.render();
  9040. }
  9041. engine.setAlphaTesting(true);
  9042. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  9043. submesh = this._alphaTestSubMeshes.data[subIndex];
  9044. this._activeVertices += submesh.verticesCount;
  9045. submesh.render();
  9046. }
  9047. engine.setAlphaTesting(false);
  9048. if (beforeTransparents) {
  9049. beforeTransparents();
  9050. }
  9051. if (this._transparentSubMeshes.length) {
  9052. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  9053. submesh = this._transparentSubMeshes.data[subIndex];
  9054. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  9055. }
  9056. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  9057. sortedArray.sort(function (a, b) {
  9058. if (a._distanceToCamera < b._distanceToCamera) {
  9059. return 1;
  9060. }
  9061. if (a._distanceToCamera > b._distanceToCamera) {
  9062. return -1;
  9063. }
  9064. return 0;
  9065. });
  9066. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9067. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  9068. submesh = sortedArray[subIndex];
  9069. this._activeVertices += submesh.verticesCount;
  9070. submesh.render();
  9071. }
  9072. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  9073. }
  9074. return true;
  9075. };
  9076. RenderingGroup.prototype.prepare = function () {
  9077. this._opaqueSubMeshes.reset();
  9078. this._transparentSubMeshes.reset();
  9079. this._alphaTestSubMeshes.reset();
  9080. };
  9081. RenderingGroup.prototype.dispatch = function (subMesh) {
  9082. var material = subMesh.getMaterial();
  9083. var mesh = subMesh.getMesh();
  9084. if (material.needAlphaBlending() || mesh.visibility < 1.0) {
  9085. if (material.alpha > 0 || mesh.visibility < 1.0) {
  9086. this._transparentSubMeshes.push(subMesh);
  9087. }
  9088. } else if (material.needAlphaTesting()) {
  9089. this._alphaTestSubMeshes.push(subMesh);
  9090. } else {
  9091. this._opaqueSubMeshes.push(subMesh);
  9092. }
  9093. };
  9094. return RenderingGroup;
  9095. })();
  9096. BABYLON.RenderingGroup = RenderingGroup;
  9097. })(BABYLON || (BABYLON = {}));
  9098. var BABYLON;
  9099. (function (BABYLON) {
  9100. var RenderingManager = (function () {
  9101. function RenderingManager(scene) {
  9102. this._renderingGroups = new Array();
  9103. this._scene = scene;
  9104. }
  9105. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  9106. if (this._scene._activeParticleSystems.length === 0) {
  9107. return;
  9108. }
  9109. var beforeParticlesDate = new Date().getTime();
  9110. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  9111. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  9112. if (particleSystem.renderingGroupId !== index) {
  9113. continue;
  9114. }
  9115. this._clearDepthBuffer();
  9116. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  9117. this._scene._activeParticles += particleSystem.render();
  9118. }
  9119. }
  9120. this._scene._particlesDuration += new Date().getTime() - beforeParticlesDate;
  9121. };
  9122. RenderingManager.prototype._renderSprites = function (index) {
  9123. if (this._scene.spriteManagers.length === 0) {
  9124. return;
  9125. }
  9126. var beforeSpritessDate = new Date().getTime();
  9127. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  9128. var spriteManager = this._scene.spriteManagers[id];
  9129. if (spriteManager.renderingGroupId === index) {
  9130. this._clearDepthBuffer();
  9131. spriteManager.render();
  9132. }
  9133. }
  9134. this._scene._spritesDuration += new Date().getTime() - beforeSpritessDate;
  9135. };
  9136. RenderingManager.prototype._clearDepthBuffer = function () {
  9137. if (this._depthBufferAlreadyCleaned) {
  9138. return;
  9139. }
  9140. this._scene.getEngine().clear(0, false, true);
  9141. this._depthBufferAlreadyCleaned = true;
  9142. };
  9143. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  9144. var _this = this;
  9145. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  9146. this._depthBufferAlreadyCleaned = false;
  9147. var renderingGroup = this._renderingGroups[index];
  9148. if (renderingGroup) {
  9149. this._clearDepthBuffer();
  9150. if (!renderingGroup.render(customRenderFunction, function () {
  9151. if (renderSprites) {
  9152. _this._renderSprites(index);
  9153. }
  9154. })) {
  9155. this._renderingGroups.splice(index, 1);
  9156. }
  9157. } else if (renderSprites) {
  9158. this._renderSprites(index);
  9159. }
  9160. if (renderParticles) {
  9161. this._renderParticles(index, activeMeshes);
  9162. }
  9163. }
  9164. };
  9165. RenderingManager.prototype.reset = function () {
  9166. for (var index in this._renderingGroups) {
  9167. var renderingGroup = this._renderingGroups[index];
  9168. renderingGroup.prepare();
  9169. }
  9170. };
  9171. RenderingManager.prototype.dispatch = function (subMesh) {
  9172. var mesh = subMesh.getMesh();
  9173. var renderingGroupId = mesh.renderingGroupId || 0;
  9174. if (!this._renderingGroups[renderingGroupId]) {
  9175. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  9176. }
  9177. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  9178. };
  9179. RenderingManager.MAX_RENDERINGGROUPS = 4;
  9180. return RenderingManager;
  9181. })();
  9182. BABYLON.RenderingManager = RenderingManager;
  9183. })(BABYLON || (BABYLON = {}));
  9184. var __extends = this.__extends || function (d, b) {
  9185. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9186. function __() { this.constructor = d; }
  9187. __.prototype = b.prototype;
  9188. d.prototype = new __();
  9189. };
  9190. var BABYLON;
  9191. (function (BABYLON) {
  9192. var Texture = (function (_super) {
  9193. __extends(Texture, _super);
  9194. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  9195. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  9196. if (typeof onLoad === "undefined") { onLoad = null; }
  9197. if (typeof onError === "undefined") { onError = null; }
  9198. if (typeof buffer === "undefined") { buffer = null; }
  9199. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  9200. _super.call(this, scene);
  9201. this.uOffset = 0;
  9202. this.vOffset = 0;
  9203. this.uScale = 1.0;
  9204. this.vScale = 1.0;
  9205. this.uAng = 0;
  9206. this.vAng = 0;
  9207. this.wAng = 0;
  9208. this.name = url;
  9209. this.url = url;
  9210. this._noMipmap = noMipmap;
  9211. this._invertY = invertY;
  9212. this._samplingMode = samplingMode;
  9213. this._buffer = buffer;
  9214. this._deleteBuffer = deleteBuffer;
  9215. if (!url) {
  9216. return;
  9217. }
  9218. this._texture = this._getFromCache(url, noMipmap);
  9219. if (!this._texture) {
  9220. if (!scene.useDelayedTextureLoading) {
  9221. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  9222. if (deleteBuffer) {
  9223. delete this._buffer;
  9224. }
  9225. } else {
  9226. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9227. }
  9228. }
  9229. }
  9230. Texture.prototype.delayLoad = function () {
  9231. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9232. return;
  9233. }
  9234. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9235. this._texture = this._getFromCache(this.url, this._noMipmap);
  9236. if (!this._texture) {
  9237. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  9238. if (this._deleteBuffer) {
  9239. delete this._buffer;
  9240. }
  9241. }
  9242. };
  9243. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  9244. x -= this.uOffset + 0.5;
  9245. y -= this.vOffset + 0.5;
  9246. z -= 0.5;
  9247. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  9248. t.x *= this.uScale;
  9249. t.y *= this.vScale;
  9250. t.x += 0.5;
  9251. t.y += 0.5;
  9252. t.z += 0.5;
  9253. };
  9254. Texture.prototype.getTextureMatrix = function () {
  9255. 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) {
  9256. return this._cachedTextureMatrix;
  9257. }
  9258. this._cachedUOffset = this.uOffset;
  9259. this._cachedVOffset = this.vOffset;
  9260. this._cachedUScale = this.uScale;
  9261. this._cachedVScale = this.vScale;
  9262. this._cachedUAng = this.uAng;
  9263. this._cachedVAng = this.vAng;
  9264. this._cachedWAng = this.wAng;
  9265. if (!this._cachedTextureMatrix) {
  9266. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9267. this._rowGenerationMatrix = new BABYLON.Matrix();
  9268. this._t0 = BABYLON.Vector3.Zero();
  9269. this._t1 = BABYLON.Vector3.Zero();
  9270. this._t2 = BABYLON.Vector3.Zero();
  9271. }
  9272. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  9273. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  9274. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  9275. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  9276. this._t1.subtractInPlace(this._t0);
  9277. this._t2.subtractInPlace(this._t0);
  9278. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9279. this._cachedTextureMatrix.m[0] = this._t1.x;
  9280. this._cachedTextureMatrix.m[1] = this._t1.y;
  9281. this._cachedTextureMatrix.m[2] = this._t1.z;
  9282. this._cachedTextureMatrix.m[4] = this._t2.x;
  9283. this._cachedTextureMatrix.m[5] = this._t2.y;
  9284. this._cachedTextureMatrix.m[6] = this._t2.z;
  9285. this._cachedTextureMatrix.m[8] = this._t0.x;
  9286. this._cachedTextureMatrix.m[9] = this._t0.y;
  9287. this._cachedTextureMatrix.m[10] = this._t0.z;
  9288. return this._cachedTextureMatrix;
  9289. };
  9290. Texture.prototype.getReflectionTextureMatrix = function () {
  9291. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  9292. return this._cachedTextureMatrix;
  9293. }
  9294. if (!this._cachedTextureMatrix) {
  9295. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9296. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  9297. }
  9298. switch (this.coordinatesMode) {
  9299. case BABYLON.Texture.SPHERICAL_MODE:
  9300. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9301. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  9302. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  9303. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  9304. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  9305. break;
  9306. case BABYLON.Texture.PLANAR_MODE:
  9307. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9308. this._cachedTextureMatrix[0] = this.uScale;
  9309. this._cachedTextureMatrix[5] = this.vScale;
  9310. this._cachedTextureMatrix[12] = this.uOffset;
  9311. this._cachedTextureMatrix[13] = this.vOffset;
  9312. break;
  9313. case BABYLON.Texture.PROJECTION_MODE:
  9314. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  9315. this._projectionModeMatrix.m[0] = 0.5;
  9316. this._projectionModeMatrix.m[5] = -0.5;
  9317. this._projectionModeMatrix.m[10] = 0.0;
  9318. this._projectionModeMatrix.m[12] = 0.5;
  9319. this._projectionModeMatrix.m[13] = 0.5;
  9320. this._projectionModeMatrix.m[14] = 1.0;
  9321. this._projectionModeMatrix.m[15] = 1.0;
  9322. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  9323. break;
  9324. default:
  9325. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9326. break;
  9327. }
  9328. return this._cachedTextureMatrix;
  9329. };
  9330. Texture.prototype.clone = function () {
  9331. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  9332. newTexture.hasAlpha = this.hasAlpha;
  9333. newTexture.level = this.level;
  9334. newTexture.wrapU = this.wrapU;
  9335. newTexture.wrapV = this.wrapV;
  9336. newTexture.coordinatesIndex = this.coordinatesIndex;
  9337. newTexture.coordinatesMode = this.coordinatesMode;
  9338. newTexture.uOffset = this.uOffset;
  9339. newTexture.vOffset = this.vOffset;
  9340. newTexture.uScale = this.uScale;
  9341. newTexture.vScale = this.vScale;
  9342. newTexture.uAng = this.uAng;
  9343. newTexture.vAng = this.vAng;
  9344. newTexture.wAng = this.wAng;
  9345. return newTexture;
  9346. };
  9347. Texture.NEAREST_SAMPLINGMODE = 1;
  9348. Texture.BILINEAR_SAMPLINGMODE = 2;
  9349. Texture.TRILINEAR_SAMPLINGMODE = 3;
  9350. Texture.EXPLICIT_MODE = 0;
  9351. Texture.SPHERICAL_MODE = 1;
  9352. Texture.PLANAR_MODE = 2;
  9353. Texture.CUBIC_MODE = 3;
  9354. Texture.PROJECTION_MODE = 4;
  9355. Texture.SKYBOX_MODE = 5;
  9356. Texture.CLAMP_ADDRESSMODE = 0;
  9357. Texture.WRAP_ADDRESSMODE = 1;
  9358. Texture.MIRROR_ADDRESSMODE = 2;
  9359. return Texture;
  9360. })(BABYLON.BaseTexture);
  9361. BABYLON.Texture = Texture;
  9362. })(BABYLON || (BABYLON = {}));
  9363. var __extends = this.__extends || function (d, b) {
  9364. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9365. function __() { this.constructor = d; }
  9366. __.prototype = b.prototype;
  9367. d.prototype = new __();
  9368. };
  9369. var BABYLON;
  9370. (function (BABYLON) {
  9371. var CubeTexture = (function (_super) {
  9372. __extends(CubeTexture, _super);
  9373. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  9374. _super.call(this, scene);
  9375. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  9376. this.name = rootUrl;
  9377. this.url = rootUrl;
  9378. this._noMipmap = noMipmap;
  9379. this.hasAlpha = false;
  9380. this._texture = this._getFromCache(rootUrl, noMipmap);
  9381. if (!extensions) {
  9382. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  9383. }
  9384. this._extensions = extensions;
  9385. if (!this._texture) {
  9386. if (!scene.useDelayedTextureLoading) {
  9387. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  9388. } else {
  9389. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9390. }
  9391. }
  9392. this.isCube = true;
  9393. this._textureMatrix = BABYLON.Matrix.Identity();
  9394. }
  9395. CubeTexture.prototype.clone = function () {
  9396. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  9397. newTexture.level = this.level;
  9398. newTexture.wrapU = this.wrapU;
  9399. newTexture.wrapV = this.wrapV;
  9400. newTexture.coordinatesIndex = this.coordinatesIndex;
  9401. newTexture.coordinatesMode = this.coordinatesMode;
  9402. return newTexture;
  9403. };
  9404. CubeTexture.prototype.delayLoad = function () {
  9405. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9406. return;
  9407. }
  9408. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9409. this._texture = this._getFromCache(this.url, this._noMipmap);
  9410. if (!this._texture) {
  9411. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  9412. }
  9413. };
  9414. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  9415. return this._textureMatrix;
  9416. };
  9417. return CubeTexture;
  9418. })(BABYLON.BaseTexture);
  9419. BABYLON.CubeTexture = CubeTexture;
  9420. })(BABYLON || (BABYLON = {}));
  9421. var __extends = this.__extends || function (d, b) {
  9422. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9423. function __() { this.constructor = d; }
  9424. __.prototype = b.prototype;
  9425. d.prototype = new __();
  9426. };
  9427. var BABYLON;
  9428. (function (BABYLON) {
  9429. var RenderTargetTexture = (function (_super) {
  9430. __extends(RenderTargetTexture, _super);
  9431. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  9432. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  9433. _super.call(this, null, scene, !generateMipMaps);
  9434. this.renderList = new Array();
  9435. this.renderParticles = true;
  9436. this.renderSprites = false;
  9437. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  9438. this._currentRefreshId = -1;
  9439. this._refreshRate = 1;
  9440. this.name = name;
  9441. this.isRenderTarget = true;
  9442. this._size = size;
  9443. this._generateMipMaps = generateMipMaps;
  9444. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  9445. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  9446. this._renderingManager = new BABYLON.RenderingManager(scene);
  9447. }
  9448. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  9449. this._currentRefreshId = -1;
  9450. };
  9451. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  9452. get: function () {
  9453. return this._refreshRate;
  9454. },
  9455. set: function (value) {
  9456. this._refreshRate = value;
  9457. this.resetRefreshCounter();
  9458. },
  9459. enumerable: true,
  9460. configurable: true
  9461. });
  9462. RenderTargetTexture.prototype._shouldRender = function () {
  9463. if (this._currentRefreshId === -1) {
  9464. this._currentRefreshId = 1;
  9465. return true;
  9466. }
  9467. if (this.refreshRate == this._currentRefreshId) {
  9468. this._currentRefreshId = 1;
  9469. return true;
  9470. }
  9471. this._currentRefreshId++;
  9472. return false;
  9473. };
  9474. RenderTargetTexture.prototype.getRenderSize = function () {
  9475. return this._size;
  9476. };
  9477. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  9478. this.releaseInternalTexture();
  9479. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  9480. };
  9481. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  9482. var scene = this.getScene();
  9483. var engine = scene.getEngine();
  9484. if (this._waitingRenderList) {
  9485. this.renderList = [];
  9486. for (var index = 0; index < this._waitingRenderList.length; index++) {
  9487. var id = this._waitingRenderList[index];
  9488. this.renderList.push(scene.getMeshByID(id));
  9489. }
  9490. delete this._waitingRenderList;
  9491. }
  9492. if (!this.renderList) {
  9493. return;
  9494. }
  9495. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  9496. engine.bindFramebuffer(this._texture);
  9497. }
  9498. engine.clear(scene.clearColor, true, true);
  9499. this._renderingManager.reset();
  9500. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  9501. var mesh = this.renderList[meshIndex];
  9502. if (mesh) {
  9503. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  9504. this.resetRefreshCounter();
  9505. continue;
  9506. }
  9507. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  9508. mesh._activate(scene.getRenderId());
  9509. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  9510. var subMesh = mesh.subMeshes[subIndex];
  9511. scene._activeVertices += subMesh.verticesCount;
  9512. this._renderingManager.dispatch(subMesh);
  9513. }
  9514. }
  9515. }
  9516. }
  9517. if (!this._doNotChangeAspectRatio) {
  9518. scene.updateTransformMatrix(true);
  9519. }
  9520. if (this.onBeforeRender) {
  9521. this.onBeforeRender();
  9522. }
  9523. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  9524. if (useCameraPostProcess) {
  9525. scene.postProcessManager._finalizeFrame(false, this._texture);
  9526. }
  9527. if (this.onAfterRender) {
  9528. this.onAfterRender();
  9529. }
  9530. engine.unBindFramebuffer(this._texture);
  9531. if (!this._doNotChangeAspectRatio) {
  9532. scene.updateTransformMatrix(true);
  9533. }
  9534. };
  9535. RenderTargetTexture.prototype.clone = function () {
  9536. var textureSize = this.getSize();
  9537. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9538. newTexture.hasAlpha = this.hasAlpha;
  9539. newTexture.level = this.level;
  9540. newTexture.coordinatesMode = this.coordinatesMode;
  9541. newTexture.renderList = this.renderList.slice(0);
  9542. return newTexture;
  9543. };
  9544. return RenderTargetTexture;
  9545. })(BABYLON.Texture);
  9546. BABYLON.RenderTargetTexture = RenderTargetTexture;
  9547. })(BABYLON || (BABYLON = {}));
  9548. var __extends = this.__extends || function (d, b) {
  9549. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9550. function __() { this.constructor = d; }
  9551. __.prototype = b.prototype;
  9552. d.prototype = new __();
  9553. };
  9554. var BABYLON;
  9555. (function (BABYLON) {
  9556. var ProceduralTexture = (function (_super) {
  9557. __extends(ProceduralTexture, _super);
  9558. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  9559. _super.call(this, null, scene, !generateMipMaps);
  9560. this._currentRefreshId = -1;
  9561. this._refreshRate = 1;
  9562. this._vertexDeclaration = [2];
  9563. this._vertexStrideSize = 2 * 4;
  9564. this._uniforms = new Array();
  9565. this._samplers = new Array();
  9566. this._textures = new Array();
  9567. this._floats = new Array();
  9568. this._floatsArrays = {};
  9569. this._colors3 = new Array();
  9570. this._colors4 = new Array();
  9571. this._vectors2 = new Array();
  9572. this._vectors3 = new Array();
  9573. this._matrices = new Array();
  9574. scene._proceduralTextures.push(this);
  9575. this.name = name;
  9576. this.isRenderTarget = true;
  9577. this._size = size;
  9578. this._generateMipMaps = generateMipMaps;
  9579. this._fragment = fragment;
  9580. this._fallbackTexture = fallbackTexture;
  9581. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  9582. var vertices = [];
  9583. vertices.push(1, 1);
  9584. vertices.push(-1, 1);
  9585. vertices.push(-1, -1);
  9586. vertices.push(1, -1);
  9587. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  9588. var indices = [];
  9589. indices.push(0);
  9590. indices.push(1);
  9591. indices.push(2);
  9592. indices.push(0);
  9593. indices.push(2);
  9594. indices.push(3);
  9595. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  9596. }
  9597. ProceduralTexture.prototype.isReady = function () {
  9598. var _this = this;
  9599. var engine = this.getScene().getEngine();
  9600. this._effect = engine.createEffect({ vertex: "procedural", fragment: this._fragment }, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  9601. _this.releaseInternalTexture();
  9602. _this._texture = _this._fallbackTexture._texture;
  9603. _this._texture.references++;
  9604. });
  9605. return this._effect.isReady();
  9606. };
  9607. ProceduralTexture.prototype.resetRefreshCounter = function () {
  9608. this._currentRefreshId = -1;
  9609. };
  9610. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  9611. get: function () {
  9612. return this._refreshRate;
  9613. },
  9614. set: function (value) {
  9615. this._refreshRate = value;
  9616. this.resetRefreshCounter();
  9617. },
  9618. enumerable: true,
  9619. configurable: true
  9620. });
  9621. ProceduralTexture.prototype._shouldRender = function () {
  9622. if (!this.isReady() || !this._texture) {
  9623. return false;
  9624. }
  9625. if (this._currentRefreshId === -1) {
  9626. this._currentRefreshId = 1;
  9627. return true;
  9628. }
  9629. if (this.refreshRate == this._currentRefreshId) {
  9630. this._currentRefreshId = 1;
  9631. return true;
  9632. }
  9633. this._currentRefreshId++;
  9634. return false;
  9635. };
  9636. ProceduralTexture.prototype.getRenderSize = function () {
  9637. return this._size;
  9638. };
  9639. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  9640. this.releaseInternalTexture();
  9641. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  9642. };
  9643. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  9644. if (this._uniforms.indexOf(uniformName) === -1) {
  9645. this._uniforms.push(uniformName);
  9646. }
  9647. };
  9648. ProceduralTexture.prototype.setTexture = function (name, texture) {
  9649. if (this._samplers.indexOf(name) === -1) {
  9650. this._samplers.push(name);
  9651. }
  9652. this._textures[name] = texture;
  9653. return this;
  9654. };
  9655. ProceduralTexture.prototype.setFloat = function (name, value) {
  9656. this._checkUniform(name);
  9657. this._floats[name] = value;
  9658. return this;
  9659. };
  9660. ProceduralTexture.prototype.setFloats = function (name, value) {
  9661. this._checkUniform(name);
  9662. this._floatsArrays[name] = value;
  9663. return this;
  9664. };
  9665. ProceduralTexture.prototype.setColor3 = function (name, value) {
  9666. this._checkUniform(name);
  9667. this._colors3[name] = value;
  9668. return this;
  9669. };
  9670. ProceduralTexture.prototype.setColor4 = function (name, value) {
  9671. this._checkUniform(name);
  9672. this._colors4[name] = value;
  9673. return this;
  9674. };
  9675. ProceduralTexture.prototype.setVector2 = function (name, value) {
  9676. this._checkUniform(name);
  9677. this._vectors2[name] = value;
  9678. return this;
  9679. };
  9680. ProceduralTexture.prototype.setVector3 = function (name, value) {
  9681. this._checkUniform(name);
  9682. this._vectors3[name] = value;
  9683. return this;
  9684. };
  9685. ProceduralTexture.prototype.setMatrix = function (name, value) {
  9686. this._checkUniform(name);
  9687. this._matrices[name] = value;
  9688. return this;
  9689. };
  9690. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  9691. var scene = this.getScene();
  9692. var engine = scene.getEngine();
  9693. engine.bindFramebuffer(this._texture);
  9694. engine.clear(scene.clearColor, true, true);
  9695. engine.enableEffect(this._effect);
  9696. engine.setState(false);
  9697. for (var name in this._textures) {
  9698. this._effect.setTexture(name, this._textures[name]);
  9699. }
  9700. for (name in this._floats) {
  9701. this._effect.setFloat(name, this._floats[name]);
  9702. }
  9703. for (name in this._floatsArrays) {
  9704. this._effect.setArray(name, this._floatsArrays[name]);
  9705. }
  9706. for (name in this._colors3) {
  9707. this._effect.setColor3(name, this._colors3[name]);
  9708. }
  9709. for (name in this._colors4) {
  9710. var color = this._colors4[name];
  9711. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  9712. }
  9713. for (name in this._vectors2) {
  9714. this._effect.setVector2(name, this._vectors2[name]);
  9715. }
  9716. for (name in this._vectors3) {
  9717. this._effect.setVector3(name, this._vectors3[name]);
  9718. }
  9719. for (name in this._matrices) {
  9720. this._effect.setMatrix(name, this._matrices[name]);
  9721. }
  9722. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  9723. engine.draw(true, 0, 6);
  9724. engine.unBindFramebuffer(this._texture);
  9725. };
  9726. ProceduralTexture.prototype.clone = function () {
  9727. var textureSize = this.getSize();
  9728. var newTexture = new BABYLON.ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  9729. newTexture.hasAlpha = this.hasAlpha;
  9730. newTexture.level = this.level;
  9731. newTexture.coordinatesMode = this.coordinatesMode;
  9732. return newTexture;
  9733. };
  9734. ProceduralTexture.prototype.dispose = function () {
  9735. var index = this.getScene()._proceduralTextures.indexOf(this);
  9736. if (index >= 0) {
  9737. this.getScene()._proceduralTextures.splice(index, 1);
  9738. }
  9739. _super.prototype.dispose.call(this);
  9740. };
  9741. return ProceduralTexture;
  9742. })(BABYLON.Texture);
  9743. BABYLON.ProceduralTexture = ProceduralTexture;
  9744. })(BABYLON || (BABYLON = {}));
  9745. var __extends = this.__extends || function (d, b) {
  9746. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9747. function __() { this.constructor = d; }
  9748. __.prototype = b.prototype;
  9749. d.prototype = new __();
  9750. };
  9751. var BABYLON;
  9752. (function (BABYLON) {
  9753. var WoodProceduralTexture = (function (_super) {
  9754. __extends(WoodProceduralTexture, _super);
  9755. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  9756. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  9757. this._ampScale = 0.03;
  9758. this._ringScale = 5;
  9759. this._woodColor1 = new BABYLON.Color3(0.80, 0.55, 0.01);
  9760. this._woodColor2 = new BABYLON.Color3(0.60, 0.41, 0.0);
  9761. this.updateShaderUniforms();
  9762. this.refreshRate = 0;
  9763. }
  9764. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  9765. this.setFloat("ampScale", this._ampScale);
  9766. this.setFloat("ringScale", this._ringScale);
  9767. this.setColor3("woodColor1", this._woodColor1);
  9768. this.setColor3("woodColor2", this._woodColor2);
  9769. };
  9770. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  9771. get: function () {
  9772. return this._ampScale;
  9773. },
  9774. set: function (value) {
  9775. this._ampScale = value;
  9776. this.updateShaderUniforms();
  9777. },
  9778. enumerable: true,
  9779. configurable: true
  9780. });
  9781. Object.defineProperty(WoodProceduralTexture.prototype, "ringScale", {
  9782. get: function () {
  9783. return this._ringScale;
  9784. },
  9785. set: function (value) {
  9786. this._ringScale = value;
  9787. this.updateShaderUniforms();
  9788. },
  9789. enumerable: true,
  9790. configurable: true
  9791. });
  9792. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor1", {
  9793. get: function () {
  9794. return this._woodColor1;
  9795. },
  9796. set: function (value) {
  9797. this._woodColor1 = value;
  9798. this.updateShaderUniforms();
  9799. },
  9800. enumerable: true,
  9801. configurable: true
  9802. });
  9803. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor2", {
  9804. get: function () {
  9805. return this._woodColor2;
  9806. },
  9807. set: function (value) {
  9808. this._woodColor2 = value;
  9809. this.updateShaderUniforms();
  9810. },
  9811. enumerable: true,
  9812. configurable: true
  9813. });
  9814. return WoodProceduralTexture;
  9815. })(BABYLON.ProceduralTexture);
  9816. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  9817. var FireProceduralTexture = (function (_super) {
  9818. __extends(FireProceduralTexture, _super);
  9819. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  9820. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  9821. this._time = 0.0;
  9822. this._speed = new BABYLON.Vector2(0.5, 0.3);
  9823. this._shift = 1.6;
  9824. this._alpha = 1.0;
  9825. this._autoGenerateTime = true;
  9826. this._fireColors = FireProceduralTexture.RedFireColors;
  9827. this.updateShaderUniforms();
  9828. this.refreshRate = 1;
  9829. }
  9830. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  9831. this.setFloat("iGlobalTime", this._time);
  9832. this.setVector2("speed", this._speed);
  9833. this.setFloat("shift", this._shift);
  9834. this.setFloat("alpha", this._alpha);
  9835. this.setColor3("c1", new BABYLON.Color3(this._fireColors[0][0], this._fireColors[0][1], this._fireColors[0][2]));
  9836. this.setColor3("c2", new BABYLON.Color3(this._fireColors[1][0], this._fireColors[1][1], this._fireColors[1][2]));
  9837. this.setColor3("c3", new BABYLON.Color3(this._fireColors[2][0], this._fireColors[2][1], this._fireColors[2][2]));
  9838. this.setColor3("c4", new BABYLON.Color3(this._fireColors[3][0], this._fireColors[3][1], this._fireColors[3][2]));
  9839. this.setColor3("c5", new BABYLON.Color3(this._fireColors[4][0], this._fireColors[4][1], this._fireColors[4][2]));
  9840. this.setColor3("c6", new BABYLON.Color3(this._fireColors[5][0], this._fireColors[5][1], this._fireColors[5][2]));
  9841. };
  9842. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  9843. if (this._autoGenerateTime) {
  9844. this._time += this.getScene().getAnimationRatio() * 0.03;
  9845. this.updateShaderUniforms();
  9846. }
  9847. _super.prototype.render.call(this, useCameraPostProcess);
  9848. };
  9849. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  9850. get: function () {
  9851. return [
  9852. [0.5, 0.0, 1.0],
  9853. [0.9, 0.0, 1.0],
  9854. [0.2, 0.0, 1.0],
  9855. [1.0, 0.9, 1.0],
  9856. [0.1, 0.1, 1.0],
  9857. [0.9, 0.9, 1.0]
  9858. ];
  9859. },
  9860. enumerable: true,
  9861. configurable: true
  9862. });
  9863. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  9864. get: function () {
  9865. return [
  9866. [0.5, 1.0, 0.0],
  9867. [0.5, 1.0, 0.0],
  9868. [0.3, 0.4, 0.0],
  9869. [0.5, 1.0, 0.0],
  9870. [0.2, 0.0, 0.0],
  9871. [0.5, 1.0, 0.0]
  9872. ];
  9873. },
  9874. enumerable: true,
  9875. configurable: true
  9876. });
  9877. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  9878. get: function () {
  9879. return [
  9880. [0.5, 0.0, 0.1],
  9881. [0.9, 0.0, 0.0],
  9882. [0.2, 0.0, 0.0],
  9883. [1.0, 0.9, 0.0],
  9884. [0.1, 0.1, 0.1],
  9885. [0.9, 0.9, 0.9]
  9886. ];
  9887. },
  9888. enumerable: true,
  9889. configurable: true
  9890. });
  9891. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  9892. get: function () {
  9893. return [
  9894. [0.1, 0.0, 0.5],
  9895. [0.0, 0.0, 0.5],
  9896. [0.1, 0.0, 0.2],
  9897. [0.0, 0.0, 1.0],
  9898. [0.1, 0.2, 0.3],
  9899. [0.0, 0.2, 0.9]
  9900. ];
  9901. },
  9902. enumerable: true,
  9903. configurable: true
  9904. });
  9905. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  9906. get: function () {
  9907. return this._fireColors;
  9908. },
  9909. set: function (value) {
  9910. this._fireColors = value;
  9911. this.updateShaderUniforms();
  9912. },
  9913. enumerable: true,
  9914. configurable: true
  9915. });
  9916. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  9917. get: function () {
  9918. return this._time;
  9919. },
  9920. set: function (value) {
  9921. this._time = value;
  9922. this.updateShaderUniforms();
  9923. },
  9924. enumerable: true,
  9925. configurable: true
  9926. });
  9927. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  9928. get: function () {
  9929. return this._speed;
  9930. },
  9931. set: function (value) {
  9932. this._speed = value;
  9933. this.updateShaderUniforms();
  9934. },
  9935. enumerable: true,
  9936. configurable: true
  9937. });
  9938. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  9939. get: function () {
  9940. return this._shift;
  9941. },
  9942. set: function (value) {
  9943. this._shift = value;
  9944. this.updateShaderUniforms();
  9945. },
  9946. enumerable: true,
  9947. configurable: true
  9948. });
  9949. Object.defineProperty(FireProceduralTexture.prototype, "alpha", {
  9950. get: function () {
  9951. return this._alpha;
  9952. },
  9953. set: function (value) {
  9954. this._alpha = value;
  9955. this.updateShaderUniforms();
  9956. },
  9957. enumerable: true,
  9958. configurable: true
  9959. });
  9960. return FireProceduralTexture;
  9961. })(BABYLON.ProceduralTexture);
  9962. BABYLON.FireProceduralTexture = FireProceduralTexture;
  9963. })(BABYLON || (BABYLON = {}));
  9964. var __extends = this.__extends || function (d, b) {
  9965. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9966. function __() { this.constructor = d; }
  9967. __.prototype = b.prototype;
  9968. d.prototype = new __();
  9969. };
  9970. var BABYLON;
  9971. (function (BABYLON) {
  9972. var MirrorTexture = (function (_super) {
  9973. __extends(MirrorTexture, _super);
  9974. function MirrorTexture(name, size, scene, generateMipMaps) {
  9975. var _this = this;
  9976. _super.call(this, name, size, scene, generateMipMaps, true);
  9977. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  9978. this._transformMatrix = BABYLON.Matrix.Zero();
  9979. this._mirrorMatrix = BABYLON.Matrix.Zero();
  9980. this.onBeforeRender = function () {
  9981. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  9982. _this._savedViewMatrix = scene.getViewMatrix();
  9983. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  9984. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  9985. scene.clipPlane = _this.mirrorPlane;
  9986. scene.getEngine().cullBackFaces = false;
  9987. };
  9988. this.onAfterRender = function () {
  9989. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  9990. scene.getEngine().cullBackFaces = true;
  9991. delete scene.clipPlane;
  9992. };
  9993. }
  9994. MirrorTexture.prototype.clone = function () {
  9995. var textureSize = this.getSize();
  9996. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9997. newTexture.hasAlpha = this.hasAlpha;
  9998. newTexture.level = this.level;
  9999. newTexture.mirrorPlane = this.mirrorPlane.clone();
  10000. newTexture.renderList = this.renderList.slice(0);
  10001. return newTexture;
  10002. };
  10003. return MirrorTexture;
  10004. })(BABYLON.RenderTargetTexture);
  10005. BABYLON.MirrorTexture = MirrorTexture;
  10006. })(BABYLON || (BABYLON = {}));
  10007. var __extends = this.__extends || function (d, b) {
  10008. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10009. function __() { this.constructor = d; }
  10010. __.prototype = b.prototype;
  10011. d.prototype = new __();
  10012. };
  10013. var BABYLON;
  10014. (function (BABYLON) {
  10015. var DynamicTexture = (function (_super) {
  10016. __extends(DynamicTexture, _super);
  10017. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  10018. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10019. _super.call(this, null, scene, !generateMipMaps);
  10020. this.name = name;
  10021. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10022. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10023. this._generateMipMaps = generateMipMaps;
  10024. if (options.getContext) {
  10025. this._canvas = options;
  10026. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  10027. } else {
  10028. this._canvas = document.createElement("canvas");
  10029. if (options.width) {
  10030. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  10031. } else {
  10032. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  10033. }
  10034. }
  10035. var textureSize = this.getSize();
  10036. this._canvas.width = textureSize.width;
  10037. this._canvas.height = textureSize.height;
  10038. this._context = this._canvas.getContext("2d");
  10039. }
  10040. DynamicTexture.prototype.getContext = function () {
  10041. return this._context;
  10042. };
  10043. DynamicTexture.prototype.update = function (invertY) {
  10044. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  10045. };
  10046. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  10047. var size = this.getSize();
  10048. if (clearColor) {
  10049. this._context.fillStyle = clearColor;
  10050. this._context.fillRect(0, 0, size.width, size.height);
  10051. }
  10052. this._context.font = font;
  10053. if (x === null) {
  10054. var textSize = this._context.measureText(text);
  10055. x = (size.width - textSize.width) / 2;
  10056. }
  10057. this._context.fillStyle = color;
  10058. this._context.fillText(text, x, y);
  10059. this.update(invertY);
  10060. };
  10061. DynamicTexture.prototype.clone = function () {
  10062. var textureSize = this.getSize();
  10063. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10064. newTexture.hasAlpha = this.hasAlpha;
  10065. newTexture.level = this.level;
  10066. newTexture.wrapU = this.wrapU;
  10067. newTexture.wrapV = this.wrapV;
  10068. return newTexture;
  10069. };
  10070. return DynamicTexture;
  10071. })(BABYLON.Texture);
  10072. BABYLON.DynamicTexture = DynamicTexture;
  10073. })(BABYLON || (BABYLON = {}));
  10074. var __extends = this.__extends || function (d, b) {
  10075. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10076. function __() { this.constructor = d; }
  10077. __.prototype = b.prototype;
  10078. d.prototype = new __();
  10079. };
  10080. var BABYLON;
  10081. (function (BABYLON) {
  10082. var VideoTexture = (function (_super) {
  10083. __extends(VideoTexture, _super);
  10084. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  10085. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10086. var _this = this;
  10087. _super.call(this, null, scene, !generateMipMaps, invertY);
  10088. this._autoLaunch = true;
  10089. this.name = name;
  10090. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  10091. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  10092. var requiredWidth = size.width || size;
  10093. var requiredHeight = size.height || size;
  10094. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  10095. var textureSize = this.getSize();
  10096. this.video = document.createElement("video");
  10097. this.video.width = textureSize.width;
  10098. this.video.height = textureSize.height;
  10099. this.video.autoplay = false;
  10100. this.video.loop = true;
  10101. this.video.addEventListener("canplaythrough", function () {
  10102. if (_this._texture) {
  10103. _this._texture.isReady = true;
  10104. }
  10105. });
  10106. urls.forEach(function (url) {
  10107. var source = document.createElement("source");
  10108. source.src = url;
  10109. _this.video.appendChild(source);
  10110. });
  10111. this._lastUpdate = new Date().getTime();
  10112. }
  10113. VideoTexture.prototype.update = function () {
  10114. if (this._autoLaunch) {
  10115. this._autoLaunch = false;
  10116. this.video.play();
  10117. }
  10118. var now = new Date().getTime();
  10119. if (now - this._lastUpdate < 15) {
  10120. return false;
  10121. }
  10122. this._lastUpdate = now;
  10123. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  10124. return true;
  10125. };
  10126. return VideoTexture;
  10127. })(BABYLON.Texture);
  10128. BABYLON.VideoTexture = VideoTexture;
  10129. })(BABYLON || (BABYLON = {}));
  10130. var BABYLON;
  10131. (function (BABYLON) {
  10132. var EffectFallbacks = (function () {
  10133. function EffectFallbacks() {
  10134. this._defines = {};
  10135. this._currentRank = 32;
  10136. this._maxRank = -1;
  10137. }
  10138. EffectFallbacks.prototype.addFallback = function (rank, define) {
  10139. if (!this._defines[rank]) {
  10140. if (rank < this._currentRank) {
  10141. this._currentRank = rank;
  10142. }
  10143. if (rank > this._maxRank) {
  10144. this._maxRank = rank;
  10145. }
  10146. this._defines[rank] = new Array();
  10147. }
  10148. this._defines[rank].push(define);
  10149. };
  10150. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  10151. get: function () {
  10152. return this._currentRank <= this._maxRank;
  10153. },
  10154. enumerable: true,
  10155. configurable: true
  10156. });
  10157. EffectFallbacks.prototype.reduce = function (currentDefines) {
  10158. var currentFallbacks = this._defines[this._currentRank];
  10159. for (var index = 0; index < currentFallbacks.length; index++) {
  10160. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  10161. }
  10162. this._currentRank++;
  10163. return currentDefines;
  10164. };
  10165. return EffectFallbacks;
  10166. })();
  10167. BABYLON.EffectFallbacks = EffectFallbacks;
  10168. var Effect = (function () {
  10169. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  10170. var _this = this;
  10171. this._isReady = false;
  10172. this._compilationError = "";
  10173. this._valueCache = [];
  10174. this._engine = engine;
  10175. this.name = baseName;
  10176. this.defines = defines;
  10177. this._uniformsNames = uniformsNames.concat(samplers);
  10178. this._samplers = samplers;
  10179. this._attributesNames = attributesNames;
  10180. this.onError = onError;
  10181. this.onCompiled = onCompiled;
  10182. var vertexSource;
  10183. var fragmentSource;
  10184. if (baseName.vertexElement) {
  10185. vertexSource = document.getElementById(baseName.vertexElement);
  10186. if (!vertexSource) {
  10187. vertexSource = baseName.vertexElement;
  10188. }
  10189. } else {
  10190. vertexSource = baseName.vertex || baseName;
  10191. }
  10192. if (baseName.fragmentElement) {
  10193. fragmentSource = document.getElementById(baseName.fragmentElement);
  10194. if (!fragmentSource) {
  10195. fragmentSource = baseName.fragmentElement;
  10196. }
  10197. } else {
  10198. fragmentSource = baseName.fragment || baseName;
  10199. }
  10200. this._loadVertexShader(vertexSource, function (vertexCode) {
  10201. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  10202. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  10203. });
  10204. });
  10205. }
  10206. Effect.prototype.isReady = function () {
  10207. return this._isReady;
  10208. };
  10209. Effect.prototype.getProgram = function () {
  10210. return this._program;
  10211. };
  10212. Effect.prototype.getAttributesNames = function () {
  10213. return this._attributesNames;
  10214. };
  10215. Effect.prototype.getAttributeLocation = function (index) {
  10216. return this._attributes[index];
  10217. };
  10218. Effect.prototype.getAttributeLocationByName = function (name) {
  10219. var index = this._attributesNames.indexOf(name);
  10220. return this._attributes[index];
  10221. };
  10222. Effect.prototype.getAttributesCount = function () {
  10223. return this._attributes.length;
  10224. };
  10225. Effect.prototype.getUniformIndex = function (uniformName) {
  10226. return this._uniformsNames.indexOf(uniformName);
  10227. };
  10228. Effect.prototype.getUniform = function (uniformName) {
  10229. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  10230. };
  10231. Effect.prototype.getSamplers = function () {
  10232. return this._samplers;
  10233. };
  10234. Effect.prototype.getCompilationError = function () {
  10235. return this._compilationError;
  10236. };
  10237. Effect.prototype._loadVertexShader = function (vertex, callback) {
  10238. if (vertex instanceof HTMLElement) {
  10239. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  10240. callback(vertexCode);
  10241. return;
  10242. }
  10243. if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
  10244. callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
  10245. return;
  10246. }
  10247. var vertexShaderUrl;
  10248. if (vertex[0] === ".") {
  10249. vertexShaderUrl = vertex;
  10250. } else {
  10251. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  10252. }
  10253. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  10254. };
  10255. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  10256. if (fragment instanceof HTMLElement) {
  10257. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  10258. callback(fragmentCode);
  10259. return;
  10260. }
  10261. if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
  10262. callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
  10263. return;
  10264. }
  10265. if (BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]) {
  10266. callback(BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]);
  10267. return;
  10268. }
  10269. var fragmentShaderUrl;
  10270. if (fragment[0] === ".") {
  10271. fragmentShaderUrl = fragment;
  10272. } else {
  10273. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  10274. }
  10275. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  10276. };
  10277. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  10278. try {
  10279. var engine = this._engine;
  10280. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  10281. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  10282. this._attributes = engine.getAttributes(this._program, attributesNames);
  10283. for (var index = 0; index < this._samplers.length; index++) {
  10284. var sampler = this.getUniform(this._samplers[index]);
  10285. if (sampler == null) {
  10286. this._samplers.splice(index, 1);
  10287. index--;
  10288. }
  10289. }
  10290. engine.bindSamplers(this);
  10291. this._isReady = true;
  10292. if (this.onCompiled) {
  10293. this.onCompiled(this);
  10294. }
  10295. } catch (e) {
  10296. if (fallbacks && fallbacks.isMoreFallbacks) {
  10297. defines = fallbacks.reduce(defines);
  10298. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  10299. } else {
  10300. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  10301. BABYLON.Tools.Error("Defines: " + defines);
  10302. BABYLON.Tools.Error("Error: " + e.message);
  10303. this._compilationError = e.message;
  10304. if (this.onError) {
  10305. this.onError(this, this._compilationError);
  10306. }
  10307. }
  10308. }
  10309. };
  10310. Effect.prototype._bindTexture = function (channel, texture) {
  10311. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  10312. };
  10313. Effect.prototype.setTexture = function (channel, texture) {
  10314. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  10315. };
  10316. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10317. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  10318. };
  10319. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  10320. if (!this._valueCache[uniformName]) {
  10321. this._valueCache[uniformName] = [x, y];
  10322. return;
  10323. }
  10324. this._valueCache[uniformName][0] = x;
  10325. this._valueCache[uniformName][1] = y;
  10326. };
  10327. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  10328. if (!this._valueCache[uniformName]) {
  10329. this._valueCache[uniformName] = [x, y, z];
  10330. return;
  10331. }
  10332. this._valueCache[uniformName][0] = x;
  10333. this._valueCache[uniformName][1] = y;
  10334. this._valueCache[uniformName][2] = z;
  10335. };
  10336. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  10337. if (!this._valueCache[uniformName]) {
  10338. this._valueCache[uniformName] = [x, y, z, w];
  10339. return;
  10340. }
  10341. this._valueCache[uniformName][0] = x;
  10342. this._valueCache[uniformName][1] = y;
  10343. this._valueCache[uniformName][2] = z;
  10344. this._valueCache[uniformName][3] = w;
  10345. };
  10346. Effect.prototype.setArray = function (uniformName, array) {
  10347. this._engine.setArray(this.getUniform(uniformName), array);
  10348. return this;
  10349. };
  10350. Effect.prototype.setMatrices = function (uniformName, matrices) {
  10351. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  10352. return this;
  10353. };
  10354. Effect.prototype.setMatrix = function (uniformName, matrix) {
  10355. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  10356. return this;
  10357. };
  10358. Effect.prototype.setFloat = function (uniformName, value) {
  10359. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  10360. return this;
  10361. this._valueCache[uniformName] = value;
  10362. this._engine.setFloat(this.getUniform(uniformName), value);
  10363. return this;
  10364. };
  10365. Effect.prototype.setBool = function (uniformName, bool) {
  10366. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  10367. return this;
  10368. this._valueCache[uniformName] = bool;
  10369. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  10370. return this;
  10371. };
  10372. Effect.prototype.setVector2 = function (uniformName, vector2) {
  10373. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector2.x && this._valueCache[uniformName][1] == vector2.y)
  10374. return this;
  10375. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  10376. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  10377. return this;
  10378. };
  10379. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  10380. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y)
  10381. return this;
  10382. this._cacheFloat2(uniformName, x, y);
  10383. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  10384. return this;
  10385. };
  10386. Effect.prototype.setVector3 = function (uniformName, vector3) {
  10387. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector3.x && this._valueCache[uniformName][1] == vector3.y && this._valueCache[uniformName][2] == vector3.z)
  10388. return this;
  10389. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  10390. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  10391. return this;
  10392. };
  10393. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  10394. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z)
  10395. return this;
  10396. this._cacheFloat3(uniformName, x, y, z);
  10397. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  10398. return this;
  10399. };
  10400. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  10401. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z && this._valueCache[uniformName][3] == w)
  10402. return this;
  10403. this._cacheFloat4(uniformName, x, y, z, w);
  10404. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  10405. return this;
  10406. };
  10407. Effect.prototype.setColor3 = function (uniformName, color3) {
  10408. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b)
  10409. return this;
  10410. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  10411. this._engine.setColor3(this.getUniform(uniformName), color3);
  10412. return this;
  10413. };
  10414. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  10415. 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)
  10416. return this;
  10417. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  10418. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  10419. return this;
  10420. };
  10421. 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}",
  10422. 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}",
  10423. 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}",
  10424. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  10425. 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}",
  10426. 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}",
  10427. 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 for (int i = 0; i<4; i++){\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[i] / 1500.0)) < depth.z){\n visibility -= 0.2;\n }\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}",
  10428. 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// 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}",
  10429. 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}",
  10430. 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}",
  10431. 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}",
  10432. 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}",
  10433. 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}",
  10434. 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}",
  10435. 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}",
  10436. 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}",
  10437. 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}",
  10438. 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}",
  10439. 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}",
  10440. 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}",
  10441. 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}",
  10442. 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}",
  10443. 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}",
  10444. 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}",
  10445. 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}",
  10446. 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}",
  10447. 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}",
  10448. 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}",
  10449. 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}",
  10450. 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}",
  10451. 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}",
  10452. 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}",
  10453. };
  10454. return Effect;
  10455. })();
  10456. BABYLON.Effect = Effect;
  10457. })(BABYLON || (BABYLON = {}));
  10458. var BABYLON;
  10459. (function (BABYLON) {
  10460. var Material = (function () {
  10461. function Material(name, scene, doNotAdd) {
  10462. this.name = name;
  10463. this.checkReadyOnEveryCall = true;
  10464. this.checkReadyOnlyOnce = false;
  10465. this.state = "";
  10466. this.alpha = 1.0;
  10467. this.wireframe = false;
  10468. this.backFaceCulling = true;
  10469. this._wasPreviouslyReady = false;
  10470. this.id = name;
  10471. this._scene = scene;
  10472. if (!doNotAdd) {
  10473. scene.materials.push(this);
  10474. }
  10475. }
  10476. Material.prototype.isReady = function (mesh, useInstances) {
  10477. return true;
  10478. };
  10479. Material.prototype.getEffect = function () {
  10480. return this._effect;
  10481. };
  10482. Material.prototype.getScene = function () {
  10483. return this._scene;
  10484. };
  10485. Material.prototype.needAlphaBlending = function () {
  10486. return (this.alpha < 1.0);
  10487. };
  10488. Material.prototype.needAlphaTesting = function () {
  10489. return false;
  10490. };
  10491. Material.prototype.getAlphaTestTexture = function () {
  10492. return null;
  10493. };
  10494. Material.prototype.trackCreation = function (onCompiled, onError) {
  10495. };
  10496. Material.prototype._preBind = function () {
  10497. var engine = this._scene.getEngine();
  10498. engine.enableEffect(this._effect);
  10499. engine.setState(this.backFaceCulling);
  10500. };
  10501. Material.prototype.bind = function (world, mesh) {
  10502. };
  10503. Material.prototype.bindOnlyWorldMatrix = function (world) {
  10504. };
  10505. Material.prototype.unbind = function () {
  10506. };
  10507. Material.prototype.dispose = function (forceDisposeEffect) {
  10508. var index = this._scene.materials.indexOf(this);
  10509. this._scene.materials.splice(index, 1);
  10510. if (forceDisposeEffect && this._effect) {
  10511. this._scene.getEngine()._releaseEffect(this._effect);
  10512. this._effect = null;
  10513. }
  10514. if (this.onDispose) {
  10515. this.onDispose();
  10516. }
  10517. };
  10518. return Material;
  10519. })();
  10520. BABYLON.Material = Material;
  10521. })(BABYLON || (BABYLON = {}));
  10522. var __extends = this.__extends || function (d, b) {
  10523. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10524. function __() { this.constructor = d; }
  10525. __.prototype = b.prototype;
  10526. d.prototype = new __();
  10527. };
  10528. var BABYLON;
  10529. (function (BABYLON) {
  10530. var maxSimultaneousLights = 4;
  10531. var FresnelParameters = (function () {
  10532. function FresnelParameters() {
  10533. this.isEnabled = true;
  10534. this.leftColor = BABYLON.Color3.White();
  10535. this.rightColor = BABYLON.Color3.Black();
  10536. this.bias = 0;
  10537. this.power = 1;
  10538. }
  10539. return FresnelParameters;
  10540. })();
  10541. BABYLON.FresnelParameters = FresnelParameters;
  10542. var StandardMaterial = (function (_super) {
  10543. __extends(StandardMaterial, _super);
  10544. function StandardMaterial(name, scene) {
  10545. var _this = this;
  10546. _super.call(this, name, scene);
  10547. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  10548. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  10549. this.specularColor = new BABYLON.Color3(1, 1, 1);
  10550. this.specularPower = 64;
  10551. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  10552. this.useAlphaFromDiffuseTexture = false;
  10553. this.useSpecularOverAlpha = true;
  10554. this._cachedDefines = null;
  10555. this._renderTargets = new BABYLON.SmartArray(16);
  10556. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  10557. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  10558. this._scaledDiffuse = new BABYLON.Color3();
  10559. this._scaledSpecular = new BABYLON.Color3();
  10560. this.getRenderTargetTextures = function () {
  10561. _this._renderTargets.reset();
  10562. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  10563. _this._renderTargets.push(_this.reflectionTexture);
  10564. }
  10565. return _this._renderTargets;
  10566. };
  10567. }
  10568. StandardMaterial.prototype.needAlphaBlending = function () {
  10569. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  10570. };
  10571. StandardMaterial.prototype.needAlphaTesting = function () {
  10572. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  10573. };
  10574. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  10575. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  10576. };
  10577. StandardMaterial.prototype.getAlphaTestTexture = function () {
  10578. return this.diffuseTexture;
  10579. };
  10580. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  10581. if (this.checkReadyOnlyOnce) {
  10582. if (this._wasPreviouslyReady) {
  10583. return true;
  10584. }
  10585. }
  10586. var scene = this.getScene();
  10587. if (!this.checkReadyOnEveryCall) {
  10588. if (this._renderId === scene.getRenderId()) {
  10589. return true;
  10590. }
  10591. }
  10592. var engine = scene.getEngine();
  10593. var defines = [];
  10594. var fallbacks = new BABYLON.EffectFallbacks();
  10595. if (scene.texturesEnabled) {
  10596. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  10597. if (!this.diffuseTexture.isReady()) {
  10598. return false;
  10599. } else {
  10600. defines.push("#define DIFFUSE");
  10601. }
  10602. }
  10603. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  10604. if (!this.ambientTexture.isReady()) {
  10605. return false;
  10606. } else {
  10607. defines.push("#define AMBIENT");
  10608. }
  10609. }
  10610. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  10611. if (!this.opacityTexture.isReady()) {
  10612. return false;
  10613. } else {
  10614. defines.push("#define OPACITY");
  10615. if (this.opacityTexture.getAlphaFromRGB) {
  10616. defines.push("#define OPACITYRGB");
  10617. }
  10618. }
  10619. }
  10620. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10621. if (!this.reflectionTexture.isReady()) {
  10622. return false;
  10623. } else {
  10624. defines.push("#define REFLECTION");
  10625. fallbacks.addFallback(0, "REFLECTION");
  10626. }
  10627. }
  10628. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10629. if (!this.emissiveTexture.isReady()) {
  10630. return false;
  10631. } else {
  10632. defines.push("#define EMISSIVE");
  10633. }
  10634. }
  10635. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10636. if (!this.specularTexture.isReady()) {
  10637. return false;
  10638. } else {
  10639. defines.push("#define SPECULAR");
  10640. fallbacks.addFallback(0, "SPECULAR");
  10641. }
  10642. }
  10643. }
  10644. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10645. if (!this.bumpTexture.isReady()) {
  10646. return false;
  10647. } else {
  10648. defines.push("#define BUMP");
  10649. fallbacks.addFallback(0, "BUMP");
  10650. }
  10651. }
  10652. if (this.useSpecularOverAlpha) {
  10653. defines.push("#define SPECULAROVERALPHA");
  10654. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  10655. }
  10656. if (scene.clipPlane) {
  10657. defines.push("#define CLIPPLANE");
  10658. }
  10659. if (engine.getAlphaTesting()) {
  10660. defines.push("#define ALPHATEST");
  10661. }
  10662. if (this._shouldUseAlphaFromDiffuseTexture()) {
  10663. defines.push("#define ALPHAFROMDIFFUSE");
  10664. }
  10665. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10666. defines.push("#define FOG");
  10667. fallbacks.addFallback(1, "FOG");
  10668. }
  10669. var shadowsActivated = false;
  10670. var lightIndex = 0;
  10671. if (scene.lightsEnabled) {
  10672. for (var index = 0; index < scene.lights.length; index++) {
  10673. var light = scene.lights[index];
  10674. if (!light.isEnabled()) {
  10675. continue;
  10676. }
  10677. if (light._excludedMeshesIds.length > 0) {
  10678. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  10679. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  10680. if (excludedMesh) {
  10681. light.excludedMeshes.push(excludedMesh);
  10682. }
  10683. }
  10684. light._excludedMeshesIds = [];
  10685. }
  10686. if (light._includedOnlyMeshesIds.length > 0) {
  10687. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  10688. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  10689. if (includedOnlyMesh) {
  10690. light.includedOnlyMeshes.push(includedOnlyMesh);
  10691. }
  10692. }
  10693. light._includedOnlyMeshesIds = [];
  10694. }
  10695. if (!light.canAffectMesh(mesh)) {
  10696. continue;
  10697. }
  10698. defines.push("#define LIGHT" + lightIndex);
  10699. if (lightIndex > 0) {
  10700. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  10701. }
  10702. var type;
  10703. if (light instanceof BABYLON.SpotLight) {
  10704. type = "#define SPOTLIGHT" + lightIndex;
  10705. } else if (light instanceof BABYLON.HemisphericLight) {
  10706. type = "#define HEMILIGHT" + lightIndex;
  10707. } else {
  10708. type = "#define POINTDIRLIGHT" + lightIndex;
  10709. }
  10710. defines.push(type);
  10711. if (lightIndex > 0) {
  10712. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  10713. }
  10714. var shadowGenerator = light.getShadowGenerator();
  10715. if (mesh && mesh.receiveShadows && shadowGenerator) {
  10716. defines.push("#define SHADOW" + lightIndex);
  10717. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  10718. if (!shadowsActivated) {
  10719. defines.push("#define SHADOWS");
  10720. shadowsActivated = true;
  10721. }
  10722. if (shadowGenerator.useVarianceShadowMap) {
  10723. defines.push("#define SHADOWVSM" + lightIndex);
  10724. if (lightIndex > 0) {
  10725. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  10726. }
  10727. }
  10728. if (shadowGenerator.usePoissonSampling) {
  10729. defines.push("#define SHADOWPCF" + lightIndex);
  10730. if (lightIndex > 0) {
  10731. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  10732. }
  10733. }
  10734. }
  10735. lightIndex++;
  10736. if (lightIndex == maxSimultaneousLights)
  10737. break;
  10738. }
  10739. }
  10740. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10741. var fresnelRank = 1;
  10742. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10743. defines.push("#define DIFFUSEFRESNEL");
  10744. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  10745. fresnelRank++;
  10746. }
  10747. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10748. defines.push("#define OPACITYFRESNEL");
  10749. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  10750. fresnelRank++;
  10751. }
  10752. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10753. defines.push("#define REFLECTIONFRESNEL");
  10754. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  10755. fresnelRank++;
  10756. }
  10757. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10758. defines.push("#define EMISSIVEFRESNEL");
  10759. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  10760. fresnelRank++;
  10761. }
  10762. defines.push("#define FRESNEL");
  10763. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  10764. }
  10765. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  10766. if (mesh) {
  10767. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10768. attribs.push(BABYLON.VertexBuffer.UVKind);
  10769. defines.push("#define UV1");
  10770. }
  10771. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10772. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10773. defines.push("#define UV2");
  10774. }
  10775. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  10776. attribs.push(BABYLON.VertexBuffer.ColorKind);
  10777. defines.push("#define VERTEXCOLOR");
  10778. }
  10779. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10780. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10781. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10782. defines.push("#define BONES");
  10783. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10784. defines.push("#define BONES4");
  10785. fallbacks.addFallback(0, "BONES4");
  10786. }
  10787. if (useInstances) {
  10788. defines.push("#define INSTANCES");
  10789. attribs.push("world0");
  10790. attribs.push("world1");
  10791. attribs.push("world2");
  10792. attribs.push("world3");
  10793. }
  10794. }
  10795. var join = defines.join("\n");
  10796. if (this._cachedDefines != join) {
  10797. this._cachedDefines = join;
  10798. var shaderName = "default";
  10799. if (!scene.getEngine().getCaps().standardDerivatives) {
  10800. shaderName = "legacydefault";
  10801. }
  10802. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  10803. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  10804. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  10805. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  10806. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  10807. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  10808. "vFogInfos", "vFogColor",
  10809. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  10810. "mBones",
  10811. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  10812. "darkness0", "darkness1", "darkness2", "darkness3",
  10813. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  10814. ], [
  10815. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  10816. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  10817. ], join, fallbacks, this.onCompiled, this.onError);
  10818. }
  10819. if (!this._effect.isReady()) {
  10820. return false;
  10821. }
  10822. this._renderId = scene.getRenderId();
  10823. this._wasPreviouslyReady = true;
  10824. return true;
  10825. };
  10826. StandardMaterial.prototype.unbind = function () {
  10827. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  10828. this._effect.setTexture("reflection2DSampler", null);
  10829. }
  10830. };
  10831. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  10832. this._effect.setMatrix("world", world);
  10833. };
  10834. StandardMaterial.prototype.bind = function (world, mesh) {
  10835. var scene = this.getScene();
  10836. this.bindOnlyWorldMatrix(world);
  10837. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  10838. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10839. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  10840. }
  10841. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10842. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  10843. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  10844. }
  10845. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10846. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  10847. }
  10848. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10849. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  10850. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  10851. }
  10852. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10853. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  10854. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  10855. }
  10856. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  10857. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  10858. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  10859. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  10860. }
  10861. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  10862. this._effect.setTexture("ambientSampler", this.ambientTexture);
  10863. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  10864. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  10865. }
  10866. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  10867. this._effect.setTexture("opacitySampler", this.opacityTexture);
  10868. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  10869. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  10870. }
  10871. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10872. if (this.reflectionTexture.isCube) {
  10873. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  10874. } else {
  10875. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  10876. }
  10877. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  10878. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  10879. }
  10880. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10881. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  10882. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  10883. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  10884. }
  10885. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10886. this._effect.setTexture("specularSampler", this.specularTexture);
  10887. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  10888. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  10889. }
  10890. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10891. this._effect.setTexture("bumpSampler", this.bumpTexture);
  10892. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
  10893. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  10894. }
  10895. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  10896. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  10897. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  10898. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  10899. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  10900. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  10901. if (scene.lightsEnabled) {
  10902. var lightIndex = 0;
  10903. for (var index = 0; index < scene.lights.length; index++) {
  10904. var light = scene.lights[index];
  10905. if (!light.isEnabled()) {
  10906. continue;
  10907. }
  10908. if (!light.canAffectMesh(mesh)) {
  10909. continue;
  10910. }
  10911. if (light instanceof BABYLON.PointLight) {
  10912. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10913. } else if (light instanceof BABYLON.DirectionalLight) {
  10914. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  10915. } else if (light instanceof BABYLON.SpotLight) {
  10916. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  10917. } else if (light instanceof BABYLON.HemisphericLight) {
  10918. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  10919. }
  10920. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  10921. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  10922. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  10923. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  10924. var shadowGenerator = light.getShadowGenerator();
  10925. if (mesh.receiveShadows && shadowGenerator) {
  10926. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  10927. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  10928. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  10929. }
  10930. lightIndex++;
  10931. if (lightIndex == maxSimultaneousLights)
  10932. break;
  10933. }
  10934. }
  10935. if (scene.clipPlane) {
  10936. var clipPlane = scene.clipPlane;
  10937. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  10938. }
  10939. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  10940. this._effect.setMatrix("view", scene.getViewMatrix());
  10941. }
  10942. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  10943. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  10944. this._effect.setColor3("vFogColor", scene.fogColor);
  10945. }
  10946. };
  10947. StandardMaterial.prototype.getAnimatables = function () {
  10948. var results = [];
  10949. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  10950. results.push(this.diffuseTexture);
  10951. }
  10952. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  10953. results.push(this.ambientTexture);
  10954. }
  10955. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  10956. results.push(this.opacityTexture);
  10957. }
  10958. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  10959. results.push(this.reflectionTexture);
  10960. }
  10961. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  10962. results.push(this.emissiveTexture);
  10963. }
  10964. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  10965. results.push(this.specularTexture);
  10966. }
  10967. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  10968. results.push(this.bumpTexture);
  10969. }
  10970. return results;
  10971. };
  10972. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  10973. if (this.diffuseTexture) {
  10974. this.diffuseTexture.dispose();
  10975. }
  10976. if (this.ambientTexture) {
  10977. this.ambientTexture.dispose();
  10978. }
  10979. if (this.opacityTexture) {
  10980. this.opacityTexture.dispose();
  10981. }
  10982. if (this.reflectionTexture) {
  10983. this.reflectionTexture.dispose();
  10984. }
  10985. if (this.emissiveTexture) {
  10986. this.emissiveTexture.dispose();
  10987. }
  10988. if (this.specularTexture) {
  10989. this.specularTexture.dispose();
  10990. }
  10991. if (this.bumpTexture) {
  10992. this.bumpTexture.dispose();
  10993. }
  10994. _super.prototype.dispose.call(this, forceDisposeEffect);
  10995. };
  10996. StandardMaterial.prototype.clone = function (name) {
  10997. var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
  10998. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  10999. newStandardMaterial.alpha = this.alpha;
  11000. newStandardMaterial.wireframe = this.wireframe;
  11001. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  11002. if (this.diffuseTexture && this.diffuseTexture.clone) {
  11003. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  11004. }
  11005. if (this.ambientTexture && this.ambientTexture.clone) {
  11006. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  11007. }
  11008. if (this.opacityTexture && this.opacityTexture.clone) {
  11009. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  11010. }
  11011. if (this.reflectionTexture && this.reflectionTexture.clone) {
  11012. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  11013. }
  11014. if (this.emissiveTexture && this.emissiveTexture.clone) {
  11015. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  11016. }
  11017. if (this.specularTexture && this.specularTexture.clone) {
  11018. newStandardMaterial.specularTexture = this.specularTexture.clone();
  11019. }
  11020. if (this.bumpTexture && this.bumpTexture.clone) {
  11021. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  11022. }
  11023. newStandardMaterial.ambientColor = this.ambientColor.clone();
  11024. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  11025. newStandardMaterial.specularColor = this.specularColor.clone();
  11026. newStandardMaterial.specularPower = this.specularPower;
  11027. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  11028. return newStandardMaterial;
  11029. };
  11030. StandardMaterial.DiffuseTextureEnabled = true;
  11031. StandardMaterial.AmbientTextureEnabled = true;
  11032. StandardMaterial.OpacityTextureEnabled = true;
  11033. StandardMaterial.ReflectionTextureEnabled = true;
  11034. StandardMaterial.EmissiveTextureEnabled = true;
  11035. StandardMaterial.SpecularTextureEnabled = true;
  11036. StandardMaterial.BumpTextureEnabled = true;
  11037. return StandardMaterial;
  11038. })(BABYLON.Material);
  11039. BABYLON.StandardMaterial = StandardMaterial;
  11040. })(BABYLON || (BABYLON = {}));
  11041. var __extends = this.__extends || function (d, b) {
  11042. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11043. function __() { this.constructor = d; }
  11044. __.prototype = b.prototype;
  11045. d.prototype = new __();
  11046. };
  11047. var BABYLON;
  11048. (function (BABYLON) {
  11049. var MultiMaterial = (function (_super) {
  11050. __extends(MultiMaterial, _super);
  11051. function MultiMaterial(name, scene) {
  11052. _super.call(this, name, scene, true);
  11053. this.subMaterials = new Array();
  11054. scene.multiMaterials.push(this);
  11055. }
  11056. MultiMaterial.prototype.getSubMaterial = function (index) {
  11057. if (index < 0 || index >= this.subMaterials.length) {
  11058. return this.getScene().defaultMaterial;
  11059. }
  11060. return this.subMaterials[index];
  11061. };
  11062. MultiMaterial.prototype.isReady = function (mesh) {
  11063. for (var index = 0; index < this.subMaterials.length; index++) {
  11064. var subMaterial = this.subMaterials[index];
  11065. if (subMaterial) {
  11066. if (!this.subMaterials[index].isReady(mesh)) {
  11067. return false;
  11068. }
  11069. }
  11070. }
  11071. return true;
  11072. };
  11073. return MultiMaterial;
  11074. })(BABYLON.Material);
  11075. BABYLON.MultiMaterial = MultiMaterial;
  11076. })(BABYLON || (BABYLON = {}));
  11077. var BABYLON;
  11078. (function (BABYLON) {
  11079. var Database = (function () {
  11080. function Database(urlToScene, callbackManifestChecked) {
  11081. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  11082. this.callbackManifestChecked = callbackManifestChecked;
  11083. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  11084. this.db = null;
  11085. this.enableSceneOffline = false;
  11086. this.enableTexturesOffline = false;
  11087. this.manifestVersionFound = 0;
  11088. this.mustUpdateRessources = false;
  11089. this.hasReachedQuota = false;
  11090. this.checkManifestFile();
  11091. }
  11092. Database.prototype.checkManifestFile = function () {
  11093. var _this = this;
  11094. function noManifestFile() {
  11095. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  11096. that.enableSceneOffline = false;
  11097. that.enableTexturesOffline = false;
  11098. that.callbackManifestChecked(false);
  11099. }
  11100. var that = this;
  11101. var manifestURL = this.currentSceneUrl + ".manifest";
  11102. var xhr = new XMLHttpRequest();
  11103. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  11104. xhr.open("GET", manifestURLTimeStamped, true);
  11105. xhr.addEventListener("load", function () {
  11106. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  11107. try {
  11108. var manifestFile = JSON.parse(xhr.response);
  11109. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  11110. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  11111. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  11112. _this.manifestVersionFound = manifestFile.version;
  11113. }
  11114. if (_this.callbackManifestChecked) {
  11115. _this.callbackManifestChecked(true);
  11116. }
  11117. } catch (ex) {
  11118. noManifestFile();
  11119. }
  11120. } else {
  11121. noManifestFile();
  11122. }
  11123. }, false);
  11124. xhr.addEventListener("error", function (event) {
  11125. noManifestFile();
  11126. }, false);
  11127. try {
  11128. xhr.send();
  11129. } catch (ex) {
  11130. BABYLON.Tools.Error("Error on XHR send request.");
  11131. that.callbackManifestChecked(false);
  11132. }
  11133. };
  11134. Database.prototype.openAsync = function (successCallback, errorCallback) {
  11135. var _this = this;
  11136. function handleError() {
  11137. that.isSupported = false;
  11138. if (errorCallback)
  11139. errorCallback();
  11140. }
  11141. var that = this;
  11142. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  11143. this.isSupported = false;
  11144. if (errorCallback)
  11145. errorCallback();
  11146. } else {
  11147. if (!this.db) {
  11148. this.hasReachedQuota = false;
  11149. this.isSupported = true;
  11150. var request = this.idbFactory.open("babylonjs", 1);
  11151. request.onerror = function (event) {
  11152. handleError();
  11153. };
  11154. request.onblocked = function (event) {
  11155. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  11156. handleError();
  11157. };
  11158. request.onsuccess = function (event) {
  11159. _this.db = request.result;
  11160. successCallback();
  11161. };
  11162. request.onupgradeneeded = function (event) {
  11163. _this.db = (event.target).result;
  11164. try {
  11165. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  11166. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  11167. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  11168. } catch (ex) {
  11169. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  11170. handleError();
  11171. }
  11172. };
  11173. } else {
  11174. if (successCallback)
  11175. successCallback();
  11176. }
  11177. }
  11178. };
  11179. Database.prototype.loadImageFromDB = function (url, image) {
  11180. var _this = this;
  11181. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  11182. var saveAndLoadImage = function () {
  11183. if (!_this.hasReachedQuota && _this.db !== null) {
  11184. _this._saveImageIntoDBAsync(completeURL, image);
  11185. } else {
  11186. image.src = url;
  11187. }
  11188. };
  11189. if (!this.mustUpdateRessources) {
  11190. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  11191. } else {
  11192. saveAndLoadImage();
  11193. }
  11194. };
  11195. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  11196. if (this.isSupported && this.db !== null) {
  11197. var texture;
  11198. var transaction = this.db.transaction(["textures"]);
  11199. transaction.onabort = function (event) {
  11200. image.src = url;
  11201. };
  11202. transaction.oncomplete = function (event) {
  11203. var blobTextureURL;
  11204. if (texture) {
  11205. var URL = window.URL || window.webkitURL;
  11206. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  11207. image.onerror = function () {
  11208. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  11209. image.src = url;
  11210. };
  11211. image.src = blobTextureURL;
  11212. } else {
  11213. notInDBCallback();
  11214. }
  11215. };
  11216. var getRequest = transaction.objectStore("textures").get(url);
  11217. getRequest.onsuccess = function (event) {
  11218. texture = (event.target).result;
  11219. };
  11220. getRequest.onerror = function (event) {
  11221. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  11222. image.src = url;
  11223. };
  11224. } else {
  11225. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11226. image.src = url;
  11227. }
  11228. };
  11229. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  11230. var _this = this;
  11231. if (this.isSupported) {
  11232. var generateBlobUrl = function () {
  11233. var blobTextureURL;
  11234. if (blob) {
  11235. var URL = window.URL || window.webkitURL;
  11236. try {
  11237. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  11238. } catch (ex) {
  11239. blobTextureURL = URL.createObjectURL(blob);
  11240. }
  11241. }
  11242. image.src = blobTextureURL;
  11243. };
  11244. if (BABYLON.Database.isUASupportingBlobStorage) {
  11245. var xhr = new XMLHttpRequest(), blob;
  11246. xhr.open("GET", url, true);
  11247. xhr.responseType = "blob";
  11248. xhr.addEventListener("load", function () {
  11249. if (xhr.status === 200) {
  11250. blob = xhr.response;
  11251. var transaction = _this.db.transaction(["textures"], "readwrite");
  11252. transaction.onabort = function (event) {
  11253. try {
  11254. if (event.srcElement.error.name === "QuotaExceededError") {
  11255. this.hasReachedQuota = true;
  11256. }
  11257. } catch (ex) {
  11258. }
  11259. generateBlobUrl();
  11260. };
  11261. transaction.oncomplete = function (event) {
  11262. generateBlobUrl();
  11263. };
  11264. var newTexture = { textureUrl: url, data: blob };
  11265. try {
  11266. var addRequest = transaction.objectStore("textures").put(newTexture);
  11267. addRequest.onsuccess = function (event) {
  11268. };
  11269. addRequest.onerror = function (event) {
  11270. generateBlobUrl();
  11271. };
  11272. } catch (ex) {
  11273. if (ex.code === 25) {
  11274. BABYLON.Database.isUASupportingBlobStorage = false;
  11275. }
  11276. image.src = url;
  11277. }
  11278. } else {
  11279. image.src = url;
  11280. }
  11281. }, false);
  11282. xhr.addEventListener("error", function (event) {
  11283. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  11284. image.src = url;
  11285. }, false);
  11286. xhr.send();
  11287. } else {
  11288. image.src = url;
  11289. }
  11290. } else {
  11291. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11292. image.src = url;
  11293. }
  11294. };
  11295. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  11296. var _this = this;
  11297. var updateVersion = function (event) {
  11298. _this._saveVersionIntoDBAsync(url, versionLoaded);
  11299. };
  11300. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  11301. };
  11302. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  11303. var _this = this;
  11304. if (this.isSupported) {
  11305. var version;
  11306. try {
  11307. var transaction = this.db.transaction(["versions"]);
  11308. transaction.oncomplete = function (event) {
  11309. if (version) {
  11310. if (_this.manifestVersionFound > version.data) {
  11311. _this.mustUpdateRessources = true;
  11312. updateInDBCallback();
  11313. } else {
  11314. callback(version.data);
  11315. }
  11316. } else {
  11317. _this.mustUpdateRessources = true;
  11318. updateInDBCallback();
  11319. }
  11320. };
  11321. transaction.onabort = function (event) {
  11322. callback(-1);
  11323. };
  11324. var getRequest = transaction.objectStore("versions").get(url);
  11325. getRequest.onsuccess = function (event) {
  11326. version = (event.target).result;
  11327. };
  11328. getRequest.onerror = function (event) {
  11329. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  11330. callback(-1);
  11331. };
  11332. } catch (ex) {
  11333. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  11334. callback(-1);
  11335. }
  11336. } else {
  11337. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11338. callback(-1);
  11339. }
  11340. };
  11341. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  11342. var _this = this;
  11343. if (this.isSupported && !this.hasReachedQuota) {
  11344. try {
  11345. var transaction = this.db.transaction(["versions"], "readwrite");
  11346. transaction.onabort = function (event) {
  11347. try {
  11348. if (event.srcElement.error.name === "QuotaExceededError") {
  11349. _this.hasReachedQuota = true;
  11350. }
  11351. } catch (ex) {
  11352. }
  11353. callback(-1);
  11354. };
  11355. transaction.oncomplete = function (event) {
  11356. callback(_this.manifestVersionFound);
  11357. };
  11358. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  11359. var addRequest = transaction.objectStore("versions").put(newVersion);
  11360. addRequest.onsuccess = function (event) {
  11361. };
  11362. addRequest.onerror = function (event) {
  11363. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  11364. };
  11365. } catch (ex) {
  11366. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  11367. callback(-1);
  11368. }
  11369. } else {
  11370. callback(-1);
  11371. }
  11372. };
  11373. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  11374. var _this = this;
  11375. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  11376. var saveAndLoadFile = function (event) {
  11377. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  11378. };
  11379. this._checkVersionFromDB(completeUrl, function (version) {
  11380. if (version !== -1) {
  11381. if (!_this.mustUpdateRessources) {
  11382. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  11383. } else {
  11384. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  11385. }
  11386. } else {
  11387. errorCallback();
  11388. }
  11389. });
  11390. };
  11391. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  11392. if (this.isSupported) {
  11393. var targetStore;
  11394. if (url.indexOf(".babylon") !== -1) {
  11395. targetStore = "scenes";
  11396. } else {
  11397. targetStore = "textures";
  11398. }
  11399. var file;
  11400. var transaction = this.db.transaction([targetStore]);
  11401. transaction.oncomplete = function (event) {
  11402. if (file) {
  11403. callback(file.data);
  11404. } else {
  11405. notInDBCallback();
  11406. }
  11407. };
  11408. transaction.onabort = function (event) {
  11409. notInDBCallback();
  11410. };
  11411. var getRequest = transaction.objectStore(targetStore).get(url);
  11412. getRequest.onsuccess = function (event) {
  11413. file = (event.target).result;
  11414. };
  11415. getRequest.onerror = function (event) {
  11416. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  11417. notInDBCallback();
  11418. };
  11419. } else {
  11420. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11421. callback();
  11422. }
  11423. };
  11424. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  11425. var _this = this;
  11426. if (this.isSupported) {
  11427. var targetStore;
  11428. if (url.indexOf(".babylon") !== -1) {
  11429. targetStore = "scenes";
  11430. } else {
  11431. targetStore = "textures";
  11432. }
  11433. var xhr = new XMLHttpRequest(), fileData;
  11434. xhr.open("GET", url, true);
  11435. if (useArrayBuffer) {
  11436. xhr.responseType = "arraybuffer";
  11437. }
  11438. xhr.onprogress = progressCallback;
  11439. xhr.addEventListener("load", function () {
  11440. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  11441. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  11442. if (!_this.hasReachedQuota) {
  11443. var transaction = _this.db.transaction([targetStore], "readwrite");
  11444. transaction.onabort = function (event) {
  11445. try {
  11446. if (event.srcElement.error.name === "QuotaExceededError") {
  11447. this.hasReachedQuota = true;
  11448. }
  11449. } catch (ex) {
  11450. }
  11451. callback(fileData);
  11452. };
  11453. transaction.oncomplete = function (event) {
  11454. callback(fileData);
  11455. };
  11456. var newFile;
  11457. if (targetStore === "scenes") {
  11458. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  11459. } else {
  11460. newFile = { textureUrl: url, data: fileData };
  11461. }
  11462. try {
  11463. var addRequest = transaction.objectStore(targetStore).put(newFile);
  11464. addRequest.onsuccess = function (event) {
  11465. };
  11466. addRequest.onerror = function (event) {
  11467. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  11468. };
  11469. } catch (ex) {
  11470. callback(fileData);
  11471. }
  11472. } else {
  11473. callback(fileData);
  11474. }
  11475. } else {
  11476. callback();
  11477. }
  11478. }, false);
  11479. xhr.addEventListener("error", function (event) {
  11480. BABYLON.Tools.Error("error on XHR request.");
  11481. callback();
  11482. }, false);
  11483. xhr.send();
  11484. } else {
  11485. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11486. callback();
  11487. }
  11488. };
  11489. Database.isUASupportingBlobStorage = true;
  11490. Database.parseURL = function (url) {
  11491. var a = document.createElement('a');
  11492. a.href = url;
  11493. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  11494. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  11495. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  11496. return absLocation;
  11497. };
  11498. Database.ReturnFullUrlLocation = function (url) {
  11499. if (url.indexOf("http:/") === -1) {
  11500. return (BABYLON.Database.parseURL(window.location.href) + url);
  11501. } else {
  11502. return url;
  11503. }
  11504. };
  11505. return Database;
  11506. })();
  11507. BABYLON.Database = Database;
  11508. })(BABYLON || (BABYLON = {}));
  11509. var BABYLON;
  11510. (function (BABYLON) {
  11511. var SpriteManager = (function () {
  11512. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  11513. this.name = name;
  11514. this.cellSize = cellSize;
  11515. this.sprites = new Array();
  11516. this.renderingGroupId = 0;
  11517. this._vertexDeclaration = [3, 4, 4, 4];
  11518. this._vertexStrideSize = 15 * 4;
  11519. this._capacity = capacity;
  11520. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  11521. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11522. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11523. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  11524. this._scene = scene;
  11525. this._scene.spriteManagers.push(this);
  11526. this._vertexDeclaration = [3, 4, 4, 4];
  11527. this._vertexStrideSize = 15 * 4;
  11528. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  11529. var indices = [];
  11530. var index = 0;
  11531. for (var count = 0; count < capacity; count++) {
  11532. indices.push(index);
  11533. indices.push(index + 1);
  11534. indices.push(index + 2);
  11535. indices.push(index);
  11536. indices.push(index + 2);
  11537. indices.push(index + 3);
  11538. index += 4;
  11539. }
  11540. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11541. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  11542. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  11543. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  11544. }
  11545. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  11546. var arrayOffset = index * 15;
  11547. if (offsetX == 0)
  11548. offsetX = this._epsilon;
  11549. else if (offsetX == 1)
  11550. offsetX = 1 - this._epsilon;
  11551. if (offsetY == 0)
  11552. offsetY = this._epsilon;
  11553. else if (offsetY == 1)
  11554. offsetY = 1 - this._epsilon;
  11555. this._vertices[arrayOffset] = sprite.position.x;
  11556. this._vertices[arrayOffset + 1] = sprite.position.y;
  11557. this._vertices[arrayOffset + 2] = sprite.position.z;
  11558. this._vertices[arrayOffset + 3] = sprite.angle;
  11559. this._vertices[arrayOffset + 4] = sprite.size;
  11560. this._vertices[arrayOffset + 5] = offsetX;
  11561. this._vertices[arrayOffset + 6] = offsetY;
  11562. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  11563. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  11564. var offset = (sprite.cellIndex / rowSize) >> 0;
  11565. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  11566. this._vertices[arrayOffset + 10] = offset;
  11567. this._vertices[arrayOffset + 11] = sprite.color.r;
  11568. this._vertices[arrayOffset + 12] = sprite.color.g;
  11569. this._vertices[arrayOffset + 13] = sprite.color.b;
  11570. this._vertices[arrayOffset + 14] = sprite.color.a;
  11571. };
  11572. SpriteManager.prototype.render = function () {
  11573. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  11574. return;
  11575. var engine = this._scene.getEngine();
  11576. var baseSize = this._spriteTexture.getBaseSize();
  11577. var deltaTime = BABYLON.Tools.GetDeltaTime();
  11578. var max = Math.min(this._capacity, this.sprites.length);
  11579. var rowSize = baseSize.width / this.cellSize;
  11580. var offset = 0;
  11581. for (var index = 0; index < max; index++) {
  11582. var sprite = this.sprites[index];
  11583. if (!sprite) {
  11584. continue;
  11585. }
  11586. sprite._animate(deltaTime);
  11587. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  11588. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  11589. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  11590. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  11591. }
  11592. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
  11593. var effect = this._effectBase;
  11594. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11595. effect = this._effectFog;
  11596. }
  11597. engine.enableEffect(effect);
  11598. var viewMatrix = this._scene.getViewMatrix();
  11599. effect.setTexture("diffuseSampler", this._spriteTexture);
  11600. effect.setMatrix("view", viewMatrix);
  11601. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  11602. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  11603. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11604. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  11605. effect.setColor3("vFogColor", this._scene.fogColor);
  11606. }
  11607. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  11608. effect.setBool("alphaTest", true);
  11609. engine.setColorWrite(false);
  11610. engine.draw(true, 0, max * 6);
  11611. engine.setColorWrite(true);
  11612. effect.setBool("alphaTest", false);
  11613. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11614. engine.draw(true, 0, max * 6);
  11615. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11616. };
  11617. SpriteManager.prototype.dispose = function () {
  11618. if (this._vertexBuffer) {
  11619. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11620. this._vertexBuffer = null;
  11621. }
  11622. if (this._indexBuffer) {
  11623. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11624. this._indexBuffer = null;
  11625. }
  11626. if (this._spriteTexture) {
  11627. this._spriteTexture.dispose();
  11628. this._spriteTexture = null;
  11629. }
  11630. var index = this._scene.spriteManagers.indexOf(this);
  11631. this._scene.spriteManagers.splice(index, 1);
  11632. if (this.onDispose) {
  11633. this.onDispose();
  11634. }
  11635. };
  11636. return SpriteManager;
  11637. })();
  11638. BABYLON.SpriteManager = SpriteManager;
  11639. })(BABYLON || (BABYLON = {}));
  11640. var BABYLON;
  11641. (function (BABYLON) {
  11642. var Sprite = (function () {
  11643. function Sprite(name, manager) {
  11644. this.name = name;
  11645. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11646. this.size = 1.0;
  11647. this.angle = 0;
  11648. this.cellIndex = 0;
  11649. this.invertU = 0;
  11650. this.invertV = 0;
  11651. this.animations = new Array();
  11652. this._animationStarted = false;
  11653. this._loopAnimation = false;
  11654. this._fromIndex = 0;
  11655. this._toIndex = 0;
  11656. this._delay = 0;
  11657. this._direction = 1;
  11658. this._frameCount = 0;
  11659. this._time = 0;
  11660. this._manager = manager;
  11661. this._manager.sprites.push(this);
  11662. this.position = BABYLON.Vector3.Zero();
  11663. }
  11664. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  11665. this._fromIndex = from;
  11666. this._toIndex = to;
  11667. this._loopAnimation = loop;
  11668. this._delay = delay;
  11669. this._animationStarted = true;
  11670. this._direction = from < to ? 1 : -1;
  11671. this.cellIndex = from;
  11672. this._time = 0;
  11673. };
  11674. Sprite.prototype.stopAnimation = function () {
  11675. this._animationStarted = false;
  11676. };
  11677. Sprite.prototype._animate = function (deltaTime) {
  11678. if (!this._animationStarted)
  11679. return;
  11680. this._time += deltaTime;
  11681. if (this._time > this._delay) {
  11682. this._time = this._time % this._delay;
  11683. this.cellIndex += this._direction;
  11684. if (this.cellIndex == this._toIndex) {
  11685. if (this._loopAnimation) {
  11686. this.cellIndex = this._fromIndex;
  11687. } else {
  11688. this._animationStarted = false;
  11689. if (this.disposeWhenFinishedAnimating) {
  11690. this.dispose();
  11691. }
  11692. }
  11693. }
  11694. }
  11695. };
  11696. Sprite.prototype.dispose = function () {
  11697. for (var i = 0; i < this._manager.sprites.length; i++) {
  11698. if (this._manager.sprites[i] == this) {
  11699. this._manager.sprites.splice(i, 1);
  11700. }
  11701. }
  11702. };
  11703. return Sprite;
  11704. })();
  11705. BABYLON.Sprite = Sprite;
  11706. })(BABYLON || (BABYLON = {}));
  11707. var BABYLON;
  11708. (function (BABYLON) {
  11709. var Layer = (function () {
  11710. function Layer(name, imgUrl, scene, isBackground, color) {
  11711. this.name = name;
  11712. this._vertexDeclaration = [2];
  11713. this._vertexStrideSize = 2 * 4;
  11714. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  11715. this.isBackground = isBackground === undefined ? true : isBackground;
  11716. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  11717. this._scene = scene;
  11718. this._scene.layers.push(this);
  11719. var vertices = [];
  11720. vertices.push(1, 1);
  11721. vertices.push(-1, 1);
  11722. vertices.push(-1, -1);
  11723. vertices.push(1, -1);
  11724. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11725. var indices = [];
  11726. indices.push(0);
  11727. indices.push(1);
  11728. indices.push(2);
  11729. indices.push(0);
  11730. indices.push(2);
  11731. indices.push(3);
  11732. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11733. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  11734. }
  11735. Layer.prototype.render = function () {
  11736. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  11737. return;
  11738. var engine = this._scene.getEngine();
  11739. engine.enableEffect(this._effect);
  11740. engine.setState(false);
  11741. this._effect.setTexture("textureSampler", this.texture);
  11742. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  11743. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  11744. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11745. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11746. engine.draw(true, 0, 6);
  11747. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11748. };
  11749. Layer.prototype.dispose = function () {
  11750. if (this._vertexBuffer) {
  11751. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11752. this._vertexBuffer = null;
  11753. }
  11754. if (this._indexBuffer) {
  11755. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11756. this._indexBuffer = null;
  11757. }
  11758. if (this.texture) {
  11759. this.texture.dispose();
  11760. this.texture = null;
  11761. }
  11762. var index = this._scene.layers.indexOf(this);
  11763. this._scene.layers.splice(index, 1);
  11764. if (this.onDispose) {
  11765. this.onDispose();
  11766. }
  11767. };
  11768. return Layer;
  11769. })();
  11770. BABYLON.Layer = Layer;
  11771. })(BABYLON || (BABYLON = {}));
  11772. var BABYLON;
  11773. (function (BABYLON) {
  11774. var Particle = (function () {
  11775. function Particle() {
  11776. this.position = BABYLON.Vector3.Zero();
  11777. this.direction = BABYLON.Vector3.Zero();
  11778. this.color = new BABYLON.Color4(0, 0, 0, 0);
  11779. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  11780. this.lifeTime = 1.0;
  11781. this.age = 0;
  11782. this.size = 0;
  11783. this.angle = 0;
  11784. this.angularSpeed = 0;
  11785. }
  11786. return Particle;
  11787. })();
  11788. BABYLON.Particle = Particle;
  11789. })(BABYLON || (BABYLON = {}));
  11790. var BABYLON;
  11791. (function (BABYLON) {
  11792. var randomNumber = function (min, max) {
  11793. if (min == max) {
  11794. return (min);
  11795. }
  11796. var random = Math.random();
  11797. return ((random * (max - min)) + min);
  11798. };
  11799. var ParticleSystem = (function () {
  11800. function ParticleSystem(name, capacity, scene, customEffect) {
  11801. var _this = this;
  11802. this.name = name;
  11803. this.renderingGroupId = 0;
  11804. this.emitter = null;
  11805. this.emitRate = 10;
  11806. this.manualEmitCount = -1;
  11807. this.updateSpeed = 0.01;
  11808. this.targetStopDuration = 0;
  11809. this.disposeOnStop = false;
  11810. this.minEmitPower = 1;
  11811. this.maxEmitPower = 1;
  11812. this.minLifeTime = 1;
  11813. this.maxLifeTime = 1;
  11814. this.minSize = 1;
  11815. this.maxSize = 1;
  11816. this.minAngularSpeed = 0;
  11817. this.maxAngularSpeed = 0;
  11818. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  11819. this.forceDepthWrite = false;
  11820. this.gravity = BABYLON.Vector3.Zero();
  11821. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  11822. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  11823. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  11824. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11825. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11826. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11827. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  11828. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11829. this.particles = new Array();
  11830. this._vertexDeclaration = [3, 4, 4];
  11831. this._vertexStrideSize = 11 * 4;
  11832. this._stockParticles = new Array();
  11833. this._newPartsExcess = 0;
  11834. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  11835. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  11836. this._scaledDirection = BABYLON.Vector3.Zero();
  11837. this._scaledGravity = BABYLON.Vector3.Zero();
  11838. this._currentRenderId = -1;
  11839. this._started = false;
  11840. this._stopped = false;
  11841. this._actualFrame = 0;
  11842. this.id = name;
  11843. this._capacity = capacity;
  11844. this._scene = scene;
  11845. this._customEffect = customEffect;
  11846. scene.particleSystems.push(this);
  11847. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  11848. var indices = [];
  11849. var index = 0;
  11850. for (var count = 0; count < capacity; count++) {
  11851. indices.push(index);
  11852. indices.push(index + 1);
  11853. indices.push(index + 2);
  11854. indices.push(index);
  11855. indices.push(index + 2);
  11856. indices.push(index + 3);
  11857. index += 4;
  11858. }
  11859. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11860. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  11861. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  11862. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  11863. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  11864. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  11865. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  11866. };
  11867. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  11868. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  11869. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  11870. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  11871. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  11872. };
  11873. }
  11874. ParticleSystem.prototype.getCapacity = function () {
  11875. return this._capacity;
  11876. };
  11877. ParticleSystem.prototype.isAlive = function () {
  11878. return this._alive;
  11879. };
  11880. ParticleSystem.prototype.isStarted = function () {
  11881. return this._started;
  11882. };
  11883. ParticleSystem.prototype.start = function () {
  11884. this._started = true;
  11885. this._stopped = false;
  11886. this._actualFrame = 0;
  11887. };
  11888. ParticleSystem.prototype.stop = function () {
  11889. this._stopped = true;
  11890. };
  11891. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  11892. var offset = index * 11;
  11893. this._vertices[offset] = particle.position.x;
  11894. this._vertices[offset + 1] = particle.position.y;
  11895. this._vertices[offset + 2] = particle.position.z;
  11896. this._vertices[offset + 3] = particle.color.r;
  11897. this._vertices[offset + 4] = particle.color.g;
  11898. this._vertices[offset + 5] = particle.color.b;
  11899. this._vertices[offset + 6] = particle.color.a;
  11900. this._vertices[offset + 7] = particle.angle;
  11901. this._vertices[offset + 8] = particle.size;
  11902. this._vertices[offset + 9] = offsetX;
  11903. this._vertices[offset + 10] = offsetY;
  11904. };
  11905. ParticleSystem.prototype._update = function (newParticles) {
  11906. this._alive = this.particles.length > 0;
  11907. for (var index = 0; index < this.particles.length; index++) {
  11908. var particle = this.particles[index];
  11909. particle.age += this._scaledUpdateSpeed;
  11910. if (particle.age >= particle.lifeTime) {
  11911. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  11912. index--;
  11913. continue;
  11914. } else {
  11915. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  11916. particle.color.addInPlace(this._scaledColorStep);
  11917. if (particle.color.a < 0)
  11918. particle.color.a = 0;
  11919. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  11920. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  11921. particle.position.addInPlace(this._scaledDirection);
  11922. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  11923. particle.direction.addInPlace(this._scaledGravity);
  11924. }
  11925. }
  11926. var worldMatrix;
  11927. if (this.emitter.position) {
  11928. worldMatrix = this.emitter.getWorldMatrix();
  11929. } else {
  11930. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  11931. }
  11932. for (index = 0; index < newParticles; index++) {
  11933. if (this.particles.length == this._capacity) {
  11934. break;
  11935. }
  11936. if (this._stockParticles.length !== 0) {
  11937. particle = this._stockParticles.pop();
  11938. particle.age = 0;
  11939. } else {
  11940. particle = new BABYLON.Particle();
  11941. }
  11942. this.particles.push(particle);
  11943. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  11944. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  11945. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  11946. particle.size = randomNumber(this.minSize, this.maxSize);
  11947. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  11948. this.startPositionFunction(worldMatrix, particle.position);
  11949. var step = randomNumber(0, 1.0);
  11950. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  11951. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  11952. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  11953. }
  11954. };
  11955. ParticleSystem.prototype._getEffect = function () {
  11956. if (this._customEffect) {
  11957. return this._customEffect;
  11958. }
  11959. ;
  11960. var defines = [];
  11961. if (this._scene.clipPlane) {
  11962. defines.push("#define CLIPPLANE");
  11963. }
  11964. var join = defines.join("\n");
  11965. if (this._cachedDefines != join) {
  11966. this._cachedDefines = join;
  11967. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  11968. }
  11969. return this._effect;
  11970. };
  11971. ParticleSystem.prototype.animate = function () {
  11972. if (!this._started)
  11973. return;
  11974. var effect = this._getEffect();
  11975. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  11976. return;
  11977. if (this._currentRenderId === this._scene.getRenderId()) {
  11978. return;
  11979. }
  11980. this._currentRenderId = this._scene.getRenderId();
  11981. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  11982. var emitCout;
  11983. if (this.manualEmitCount > -1) {
  11984. emitCout = this.manualEmitCount;
  11985. this.manualEmitCount = 0;
  11986. } else {
  11987. emitCout = this.emitRate;
  11988. }
  11989. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  11990. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  11991. if (this._newPartsExcess > 1.0) {
  11992. newParticles += this._newPartsExcess >> 0;
  11993. this._newPartsExcess -= this._newPartsExcess >> 0;
  11994. }
  11995. this._alive = false;
  11996. if (!this._stopped) {
  11997. this._actualFrame += this._scaledUpdateSpeed;
  11998. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  11999. this.stop();
  12000. } else {
  12001. newParticles = 0;
  12002. }
  12003. this._update(newParticles);
  12004. if (this._stopped) {
  12005. if (!this._alive) {
  12006. this._started = false;
  12007. if (this.disposeOnStop) {
  12008. this._scene._toBeDisposed.push(this);
  12009. }
  12010. }
  12011. }
  12012. var offset = 0;
  12013. for (var index = 0; index < this.particles.length; index++) {
  12014. var particle = this.particles[index];
  12015. this._appendParticleVertex(offset++, particle, 0, 0);
  12016. this._appendParticleVertex(offset++, particle, 1, 0);
  12017. this._appendParticleVertex(offset++, particle, 1, 1);
  12018. this._appendParticleVertex(offset++, particle, 0, 1);
  12019. }
  12020. var engine = this._scene.getEngine();
  12021. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  12022. };
  12023. ParticleSystem.prototype.render = function () {
  12024. var effect = this._getEffect();
  12025. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  12026. return 0;
  12027. var engine = this._scene.getEngine();
  12028. engine.enableEffect(effect);
  12029. var viewMatrix = this._scene.getViewMatrix();
  12030. effect.setTexture("diffuseSampler", this.particleTexture);
  12031. effect.setMatrix("view", viewMatrix);
  12032. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  12033. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  12034. if (this._scene.clipPlane) {
  12035. var clipPlane = this._scene.clipPlane;
  12036. var invView = viewMatrix.clone();
  12037. invView.invert();
  12038. effect.setMatrix("invView", invView);
  12039. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  12040. }
  12041. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12042. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  12043. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  12044. } else {
  12045. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12046. }
  12047. if (this.forceDepthWrite) {
  12048. engine.setDepthWrite(true);
  12049. }
  12050. engine.draw(true, 0, this.particles.length * 6);
  12051. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12052. return this.particles.length;
  12053. };
  12054. ParticleSystem.prototype.dispose = function () {
  12055. if (this._vertexBuffer) {
  12056. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12057. this._vertexBuffer = null;
  12058. }
  12059. if (this._indexBuffer) {
  12060. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12061. this._indexBuffer = null;
  12062. }
  12063. if (this.particleTexture) {
  12064. this.particleTexture.dispose();
  12065. this.particleTexture = null;
  12066. }
  12067. var index = this._scene.particleSystems.indexOf(this);
  12068. this._scene.particleSystems.splice(index, 1);
  12069. if (this.onDispose) {
  12070. this.onDispose();
  12071. }
  12072. };
  12073. ParticleSystem.prototype.clone = function (name, newEmitter) {
  12074. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  12075. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  12076. if (newEmitter === undefined) {
  12077. newEmitter = this.emitter;
  12078. }
  12079. result.emitter = newEmitter;
  12080. if (this.particleTexture) {
  12081. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  12082. }
  12083. result.start();
  12084. return result;
  12085. };
  12086. ParticleSystem.BLENDMODE_ONEONE = 0;
  12087. ParticleSystem.BLENDMODE_STANDARD = 1;
  12088. return ParticleSystem;
  12089. })();
  12090. BABYLON.ParticleSystem = ParticleSystem;
  12091. })(BABYLON || (BABYLON = {}));
  12092. var BABYLON;
  12093. (function (BABYLON) {
  12094. var Animation = (function () {
  12095. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  12096. this.name = name;
  12097. this.targetProperty = targetProperty;
  12098. this.framePerSecond = framePerSecond;
  12099. this.dataType = dataType;
  12100. this.loopMode = loopMode;
  12101. this._offsetsCache = {};
  12102. this._highLimitsCache = {};
  12103. this._stopped = false;
  12104. this.targetPropertyPath = targetProperty.split(".");
  12105. this.dataType = dataType;
  12106. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  12107. }
  12108. Animation.prototype.isStopped = function () {
  12109. return this._stopped;
  12110. };
  12111. Animation.prototype.getKeys = function () {
  12112. return this._keys;
  12113. };
  12114. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  12115. return startValue + (endValue - startValue) * gradient;
  12116. };
  12117. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  12118. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  12119. };
  12120. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  12121. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  12122. };
  12123. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  12124. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  12125. };
  12126. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  12127. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  12128. };
  12129. Animation.prototype.clone = function () {
  12130. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  12131. clone.setKeys(this._keys);
  12132. return clone;
  12133. };
  12134. Animation.prototype.setKeys = function (values) {
  12135. this._keys = values.slice(0);
  12136. this._offsetsCache = {};
  12137. this._highLimitsCache = {};
  12138. };
  12139. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  12140. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  12141. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  12142. }
  12143. this.currentFrame = currentFrame;
  12144. for (var key = 0; key < this._keys.length; key++) {
  12145. if (this._keys[key + 1].frame >= currentFrame) {
  12146. var startValue = this._keys[key].value;
  12147. var endValue = this._keys[key + 1].value;
  12148. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  12149. switch (this.dataType) {
  12150. case Animation.ANIMATIONTYPE_FLOAT:
  12151. switch (loopMode) {
  12152. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12153. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12154. return this.floatInterpolateFunction(startValue, endValue, gradient);
  12155. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12156. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  12157. }
  12158. break;
  12159. case Animation.ANIMATIONTYPE_QUATERNION:
  12160. var quaternion = null;
  12161. switch (loopMode) {
  12162. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12163. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12164. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  12165. break;
  12166. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12167. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12168. break;
  12169. }
  12170. return quaternion;
  12171. case Animation.ANIMATIONTYPE_VECTOR3:
  12172. switch (loopMode) {
  12173. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12174. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12175. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  12176. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12177. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12178. }
  12179. case Animation.ANIMATIONTYPE_VECTOR2:
  12180. switch (loopMode) {
  12181. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12182. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12183. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  12184. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12185. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12186. }
  12187. case Animation.ANIMATIONTYPE_COLOR3:
  12188. switch (loopMode) {
  12189. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12190. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12191. return this.color3InterpolateFunction(startValue, endValue, gradient);
  12192. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12193. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12194. }
  12195. case Animation.ANIMATIONTYPE_MATRIX:
  12196. switch (loopMode) {
  12197. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12198. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12199. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12200. return startValue;
  12201. }
  12202. default:
  12203. break;
  12204. }
  12205. break;
  12206. }
  12207. }
  12208. return this._keys[this._keys.length - 1].value;
  12209. };
  12210. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  12211. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  12212. this._stopped = true;
  12213. return false;
  12214. }
  12215. var returnValue = true;
  12216. if (this._keys[0].frame != 0) {
  12217. var newKey = {
  12218. frame: 0,
  12219. value: this._keys[0].value
  12220. };
  12221. this._keys.splice(0, 0, newKey);
  12222. }
  12223. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  12224. from = this._keys[0].frame;
  12225. }
  12226. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  12227. to = this._keys[this._keys.length - 1].frame;
  12228. }
  12229. var range = to - from;
  12230. var offsetValue;
  12231. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  12232. if (ratio > range && !loop) {
  12233. returnValue = false;
  12234. highLimitValue = this._keys[this._keys.length - 1].value;
  12235. } else {
  12236. var highLimitValue = 0;
  12237. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  12238. var keyOffset = to.toString() + from.toString();
  12239. if (!this._offsetsCache[keyOffset]) {
  12240. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  12241. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  12242. switch (this.dataType) {
  12243. case Animation.ANIMATIONTYPE_FLOAT:
  12244. this._offsetsCache[keyOffset] = toValue - fromValue;
  12245. break;
  12246. case Animation.ANIMATIONTYPE_QUATERNION:
  12247. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12248. break;
  12249. case Animation.ANIMATIONTYPE_VECTOR3:
  12250. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12251. case Animation.ANIMATIONTYPE_VECTOR2:
  12252. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12253. case Animation.ANIMATIONTYPE_COLOR3:
  12254. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12255. default:
  12256. break;
  12257. }
  12258. this._highLimitsCache[keyOffset] = toValue;
  12259. }
  12260. highLimitValue = this._highLimitsCache[keyOffset];
  12261. offsetValue = this._offsetsCache[keyOffset];
  12262. }
  12263. }
  12264. if (offsetValue === undefined) {
  12265. switch (this.dataType) {
  12266. case Animation.ANIMATIONTYPE_FLOAT:
  12267. offsetValue = 0;
  12268. break;
  12269. case Animation.ANIMATIONTYPE_QUATERNION:
  12270. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  12271. break;
  12272. case Animation.ANIMATIONTYPE_VECTOR3:
  12273. offsetValue = BABYLON.Vector3.Zero();
  12274. break;
  12275. case Animation.ANIMATIONTYPE_VECTOR2:
  12276. offsetValue = BABYLON.Vector2.Zero();
  12277. break;
  12278. case Animation.ANIMATIONTYPE_COLOR3:
  12279. offsetValue = BABYLON.Color3.Black();
  12280. }
  12281. }
  12282. var repeatCount = (ratio / range) >> 0;
  12283. var currentFrame = returnValue ? from + ratio % range : to;
  12284. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  12285. if (this.targetPropertyPath.length > 1) {
  12286. var property = this._target[this.targetPropertyPath[0]];
  12287. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  12288. property = property[this.targetPropertyPath[index]];
  12289. }
  12290. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  12291. } else {
  12292. this._target[this.targetPropertyPath[0]] = currentValue;
  12293. }
  12294. if (this._target.markAsDirty) {
  12295. this._target.markAsDirty(this.targetProperty);
  12296. }
  12297. if (!returnValue) {
  12298. this._stopped = true;
  12299. }
  12300. return returnValue;
  12301. };
  12302. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  12303. get: function () {
  12304. return Animation._ANIMATIONTYPE_FLOAT;
  12305. },
  12306. enumerable: true,
  12307. configurable: true
  12308. });
  12309. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  12310. get: function () {
  12311. return Animation._ANIMATIONTYPE_VECTOR3;
  12312. },
  12313. enumerable: true,
  12314. configurable: true
  12315. });
  12316. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  12317. get: function () {
  12318. return Animation._ANIMATIONTYPE_VECTOR2;
  12319. },
  12320. enumerable: true,
  12321. configurable: true
  12322. });
  12323. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  12324. get: function () {
  12325. return Animation._ANIMATIONTYPE_QUATERNION;
  12326. },
  12327. enumerable: true,
  12328. configurable: true
  12329. });
  12330. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  12331. get: function () {
  12332. return Animation._ANIMATIONTYPE_MATRIX;
  12333. },
  12334. enumerable: true,
  12335. configurable: true
  12336. });
  12337. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  12338. get: function () {
  12339. return Animation._ANIMATIONTYPE_COLOR3;
  12340. },
  12341. enumerable: true,
  12342. configurable: true
  12343. });
  12344. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  12345. get: function () {
  12346. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  12347. },
  12348. enumerable: true,
  12349. configurable: true
  12350. });
  12351. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  12352. get: function () {
  12353. return Animation._ANIMATIONLOOPMODE_CYCLE;
  12354. },
  12355. enumerable: true,
  12356. configurable: true
  12357. });
  12358. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  12359. get: function () {
  12360. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  12361. },
  12362. enumerable: true,
  12363. configurable: true
  12364. });
  12365. Animation._ANIMATIONTYPE_FLOAT = 0;
  12366. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  12367. Animation._ANIMATIONTYPE_QUATERNION = 2;
  12368. Animation._ANIMATIONTYPE_MATRIX = 3;
  12369. Animation._ANIMATIONTYPE_COLOR3 = 4;
  12370. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  12371. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  12372. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  12373. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  12374. return Animation;
  12375. })();
  12376. BABYLON.Animation = Animation;
  12377. })(BABYLON || (BABYLON = {}));
  12378. var BABYLON;
  12379. (function (BABYLON) {
  12380. var Animatable = (function () {
  12381. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  12382. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  12383. if (typeof toFrame === "undefined") { toFrame = 100; }
  12384. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  12385. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  12386. this.target = target;
  12387. this.fromFrame = fromFrame;
  12388. this.toFrame = toFrame;
  12389. this.loopAnimation = loopAnimation;
  12390. this.speedRatio = speedRatio;
  12391. this.onAnimationEnd = onAnimationEnd;
  12392. this._animations = new Array();
  12393. this._paused = false;
  12394. this.animationStarted = false;
  12395. if (animations) {
  12396. this.appendAnimations(target, animations);
  12397. }
  12398. this._scene = scene;
  12399. scene._activeAnimatables.push(this);
  12400. }
  12401. Animatable.prototype.appendAnimations = function (target, animations) {
  12402. for (var index = 0; index < animations.length; index++) {
  12403. var animation = animations[index];
  12404. animation._target = target;
  12405. this._animations.push(animation);
  12406. }
  12407. };
  12408. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  12409. var animations = this._animations;
  12410. for (var index = 0; index < animations.length; index++) {
  12411. if (animations[index].targetProperty === property) {
  12412. return animations[index];
  12413. }
  12414. }
  12415. return null;
  12416. };
  12417. Animatable.prototype.pause = function () {
  12418. this._paused = true;
  12419. };
  12420. Animatable.prototype.restart = function () {
  12421. this._paused = false;
  12422. };
  12423. Animatable.prototype.stop = function () {
  12424. var index = this._scene._activeAnimatables.indexOf(this);
  12425. if (index > -1) {
  12426. this._scene._activeAnimatables.splice(index, 1);
  12427. }
  12428. if (this.onAnimationEnd) {
  12429. this.onAnimationEnd();
  12430. }
  12431. };
  12432. Animatable.prototype._animate = function (delay) {
  12433. if (this._paused) {
  12434. return true;
  12435. }
  12436. if (!this._localDelayOffset) {
  12437. this._localDelayOffset = delay;
  12438. }
  12439. var running = false;
  12440. var animations = this._animations;
  12441. for (var index = 0; index < animations.length; index++) {
  12442. var animation = animations[index];
  12443. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  12444. running = running || isRunning;
  12445. }
  12446. if (!running && this.onAnimationEnd) {
  12447. this.onAnimationEnd();
  12448. }
  12449. return running;
  12450. };
  12451. return Animatable;
  12452. })();
  12453. BABYLON.Animatable = Animatable;
  12454. })(BABYLON || (BABYLON = {}));
  12455. var BABYLON;
  12456. (function (BABYLON) {
  12457. var Octree = (function () {
  12458. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  12459. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  12460. this.maxDepth = maxDepth;
  12461. this.dynamicContent = new Array();
  12462. this._maxBlockCapacity = maxBlockCapacity || 64;
  12463. this._selectionContent = new BABYLON.SmartArray(1024);
  12464. this._creationFunc = creationFunc;
  12465. }
  12466. Octree.prototype.update = function (worldMin, worldMax, entries) {
  12467. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  12468. };
  12469. Octree.prototype.addMesh = function (entry) {
  12470. for (var index = 0; index < this.blocks.length; index++) {
  12471. var block = this.blocks[index];
  12472. block.addEntry(entry);
  12473. }
  12474. };
  12475. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  12476. this._selectionContent.reset();
  12477. for (var index = 0; index < this.blocks.length; index++) {
  12478. var block = this.blocks[index];
  12479. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  12480. }
  12481. if (allowDuplicate) {
  12482. this._selectionContent.concat(this.dynamicContent);
  12483. } else {
  12484. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  12485. }
  12486. return this._selectionContent;
  12487. };
  12488. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  12489. this._selectionContent.reset();
  12490. for (var index = 0; index < this.blocks.length; index++) {
  12491. var block = this.blocks[index];
  12492. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  12493. }
  12494. if (allowDuplicate) {
  12495. this._selectionContent.concat(this.dynamicContent);
  12496. } else {
  12497. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  12498. }
  12499. return this._selectionContent;
  12500. };
  12501. Octree.prototype.intersectsRay = function (ray) {
  12502. this._selectionContent.reset();
  12503. for (var index = 0; index < this.blocks.length; index++) {
  12504. var block = this.blocks[index];
  12505. block.intersectsRay(ray, this._selectionContent);
  12506. }
  12507. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  12508. return this._selectionContent;
  12509. };
  12510. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  12511. target.blocks = new Array();
  12512. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  12513. for (var x = 0; x < 2; x++) {
  12514. for (var y = 0; y < 2; y++) {
  12515. for (var z = 0; z < 2; z++) {
  12516. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  12517. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  12518. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  12519. block.addEntries(entries);
  12520. target.blocks.push(block);
  12521. }
  12522. }
  12523. }
  12524. };
  12525. Octree.CreationFuncForMeshes = function (entry, block) {
  12526. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  12527. block.entries.push(entry);
  12528. }
  12529. };
  12530. Octree.CreationFuncForSubMeshes = function (entry, block) {
  12531. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  12532. block.entries.push(entry);
  12533. }
  12534. };
  12535. return Octree;
  12536. })();
  12537. BABYLON.Octree = Octree;
  12538. })(BABYLON || (BABYLON = {}));
  12539. var BABYLON;
  12540. (function (BABYLON) {
  12541. var OctreeBlock = (function () {
  12542. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  12543. this.entries = new Array();
  12544. this._boundingVectors = new Array();
  12545. this._capacity = capacity;
  12546. this._depth = depth;
  12547. this._maxDepth = maxDepth;
  12548. this._creationFunc = creationFunc;
  12549. this._minPoint = minPoint;
  12550. this._maxPoint = maxPoint;
  12551. this._boundingVectors.push(minPoint.clone());
  12552. this._boundingVectors.push(maxPoint.clone());
  12553. this._boundingVectors.push(minPoint.clone());
  12554. this._boundingVectors[2].x = maxPoint.x;
  12555. this._boundingVectors.push(minPoint.clone());
  12556. this._boundingVectors[3].y = maxPoint.y;
  12557. this._boundingVectors.push(minPoint.clone());
  12558. this._boundingVectors[4].z = maxPoint.z;
  12559. this._boundingVectors.push(maxPoint.clone());
  12560. this._boundingVectors[5].z = minPoint.z;
  12561. this._boundingVectors.push(maxPoint.clone());
  12562. this._boundingVectors[6].x = minPoint.x;
  12563. this._boundingVectors.push(maxPoint.clone());
  12564. this._boundingVectors[7].y = minPoint.y;
  12565. }
  12566. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  12567. get: function () {
  12568. return this._capacity;
  12569. },
  12570. enumerable: true,
  12571. configurable: true
  12572. });
  12573. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  12574. get: function () {
  12575. return this._minPoint;
  12576. },
  12577. enumerable: true,
  12578. configurable: true
  12579. });
  12580. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  12581. get: function () {
  12582. return this._maxPoint;
  12583. },
  12584. enumerable: true,
  12585. configurable: true
  12586. });
  12587. OctreeBlock.prototype.addEntry = function (entry) {
  12588. if (this.blocks) {
  12589. for (var index = 0; index < this.blocks.length; index++) {
  12590. var block = this.blocks[index];
  12591. block.addEntry(entry);
  12592. }
  12593. return;
  12594. }
  12595. this._creationFunc(entry, this);
  12596. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  12597. this.createInnerBlocks();
  12598. }
  12599. };
  12600. OctreeBlock.prototype.addEntries = function (entries) {
  12601. for (var index = 0; index < entries.length; index++) {
  12602. var mesh = entries[index];
  12603. this.addEntry(mesh);
  12604. }
  12605. };
  12606. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  12607. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  12608. if (this.blocks) {
  12609. for (var index = 0; index < this.blocks.length; index++) {
  12610. var block = this.blocks[index];
  12611. block.select(frustumPlanes, selection, allowDuplicate);
  12612. }
  12613. return;
  12614. }
  12615. if (allowDuplicate) {
  12616. selection.concat(this.entries);
  12617. } else {
  12618. selection.concatWithNoDuplicate(this.entries);
  12619. }
  12620. }
  12621. };
  12622. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  12623. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  12624. if (this.blocks) {
  12625. for (var index = 0; index < this.blocks.length; index++) {
  12626. var block = this.blocks[index];
  12627. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  12628. }
  12629. return;
  12630. }
  12631. if (allowDuplicate) {
  12632. selection.concat(this.entries);
  12633. } else {
  12634. selection.concatWithNoDuplicate(this.entries);
  12635. }
  12636. }
  12637. };
  12638. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  12639. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  12640. if (this.blocks) {
  12641. for (var index = 0; index < this.blocks.length; index++) {
  12642. var block = this.blocks[index];
  12643. block.intersectsRay(ray, selection);
  12644. }
  12645. return;
  12646. }
  12647. selection.concatWithNoDuplicate(this.entries);
  12648. }
  12649. };
  12650. OctreeBlock.prototype.createInnerBlocks = function () {
  12651. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  12652. };
  12653. return OctreeBlock;
  12654. })();
  12655. BABYLON.OctreeBlock = OctreeBlock;
  12656. })(BABYLON || (BABYLON = {}));
  12657. var BABYLON;
  12658. (function (BABYLON) {
  12659. var Bone = (function () {
  12660. function Bone(name, skeleton, parentBone, matrix) {
  12661. this.name = name;
  12662. this.children = new Array();
  12663. this.animations = new Array();
  12664. this._worldTransform = new BABYLON.Matrix();
  12665. this._absoluteTransform = new BABYLON.Matrix();
  12666. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  12667. this._skeleton = skeleton;
  12668. this._matrix = matrix;
  12669. this._baseMatrix = matrix;
  12670. skeleton.bones.push(this);
  12671. if (parentBone) {
  12672. this._parent = parentBone;
  12673. parentBone.children.push(this);
  12674. } else {
  12675. this._parent = null;
  12676. }
  12677. this._updateDifferenceMatrix();
  12678. }
  12679. Bone.prototype.getParent = function () {
  12680. return this._parent;
  12681. };
  12682. Bone.prototype.getLocalMatrix = function () {
  12683. return this._matrix;
  12684. };
  12685. Bone.prototype.getBaseMatrix = function () {
  12686. return this._baseMatrix;
  12687. };
  12688. Bone.prototype.getWorldMatrix = function () {
  12689. return this._worldTransform;
  12690. };
  12691. Bone.prototype.getInvertedAbsoluteTransform = function () {
  12692. return this._invertedAbsoluteTransform;
  12693. };
  12694. Bone.prototype.getAbsoluteMatrix = function () {
  12695. var matrix = this._matrix.clone();
  12696. var parent = this._parent;
  12697. while (parent) {
  12698. matrix = matrix.multiply(parent.getLocalMatrix());
  12699. parent = parent.getParent();
  12700. }
  12701. return matrix;
  12702. };
  12703. Bone.prototype.updateMatrix = function (matrix) {
  12704. this._matrix = matrix;
  12705. this._skeleton._markAsDirty();
  12706. this._updateDifferenceMatrix();
  12707. };
  12708. Bone.prototype._updateDifferenceMatrix = function () {
  12709. if (this._parent) {
  12710. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  12711. } else {
  12712. this._absoluteTransform.copyFrom(this._matrix);
  12713. }
  12714. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  12715. for (var index = 0; index < this.children.length; index++) {
  12716. this.children[index]._updateDifferenceMatrix();
  12717. }
  12718. };
  12719. Bone.prototype.markAsDirty = function () {
  12720. this._skeleton._markAsDirty();
  12721. };
  12722. return Bone;
  12723. })();
  12724. BABYLON.Bone = Bone;
  12725. })(BABYLON || (BABYLON = {}));
  12726. var BABYLON;
  12727. (function (BABYLON) {
  12728. var Skeleton = (function () {
  12729. function Skeleton(name, id, scene) {
  12730. this.name = name;
  12731. this.id = id;
  12732. this.bones = new Array();
  12733. this._isDirty = true;
  12734. this._identity = BABYLON.Matrix.Identity();
  12735. this.bones = [];
  12736. this._scene = scene;
  12737. scene.skeletons.push(this);
  12738. }
  12739. Skeleton.prototype.getTransformMatrices = function () {
  12740. return this._transformMatrices;
  12741. };
  12742. Skeleton.prototype._markAsDirty = function () {
  12743. this._isDirty = true;
  12744. };
  12745. Skeleton.prototype.prepare = function () {
  12746. if (!this._isDirty) {
  12747. return;
  12748. }
  12749. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  12750. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  12751. }
  12752. for (var index = 0; index < this.bones.length; index++) {
  12753. var bone = this.bones[index];
  12754. var parentBone = bone.getParent();
  12755. if (parentBone) {
  12756. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  12757. } else {
  12758. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  12759. }
  12760. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  12761. }
  12762. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  12763. this._isDirty = false;
  12764. };
  12765. Skeleton.prototype.getAnimatables = function () {
  12766. if (!this._animatables || this._animatables.length != this.bones.length) {
  12767. this._animatables = [];
  12768. for (var index = 0; index < this.bones.length; index++) {
  12769. this._animatables.push(this.bones[index]);
  12770. }
  12771. }
  12772. return this._animatables;
  12773. };
  12774. Skeleton.prototype.clone = function (name, id) {
  12775. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  12776. for (var index = 0; index < this.bones.length; index++) {
  12777. var source = this.bones[index];
  12778. var parentBone = null;
  12779. if (source.getParent()) {
  12780. var parentIndex = this.bones.indexOf(source.getParent());
  12781. parentBone = result.bones[parentIndex];
  12782. }
  12783. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  12784. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  12785. }
  12786. return result;
  12787. };
  12788. return Skeleton;
  12789. })();
  12790. BABYLON.Skeleton = Skeleton;
  12791. })(BABYLON || (BABYLON = {}));
  12792. var BABYLON;
  12793. (function (BABYLON) {
  12794. var PostProcess = (function () {
  12795. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  12796. this.name = name;
  12797. this.width = -1;
  12798. this.height = -1;
  12799. this._reusable = false;
  12800. this._textures = new BABYLON.SmartArray(2);
  12801. this._currentRenderTextureInd = 0;
  12802. if (camera != null) {
  12803. this._camera = camera;
  12804. this._scene = camera.getScene();
  12805. camera.attachPostProcess(this);
  12806. this._engine = this._scene.getEngine();
  12807. } else {
  12808. this._engine = engine;
  12809. }
  12810. this._renderRatio = ratio;
  12811. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12812. this._reusable = reusable || false;
  12813. samplers = samplers || [];
  12814. samplers.push("textureSampler");
  12815. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  12816. }
  12817. PostProcess.prototype.isReusable = function () {
  12818. return this._reusable;
  12819. };
  12820. PostProcess.prototype.activate = function (camera, sourceTexture) {
  12821. camera = camera || this._camera;
  12822. var scene = camera.getScene();
  12823. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  12824. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  12825. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  12826. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  12827. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  12828. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  12829. if (this._textures.length > 0) {
  12830. for (var i = 0; i < this._textures.length; i++) {
  12831. this._engine._releaseTexture(this._textures.data[i]);
  12832. }
  12833. this._textures.reset();
  12834. }
  12835. this.width = desiredWidth;
  12836. this.height = desiredHeight;
  12837. 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 }));
  12838. if (this._reusable) {
  12839. 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 }));
  12840. }
  12841. if (this.onSizeChanged) {
  12842. this.onSizeChanged();
  12843. }
  12844. }
  12845. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  12846. if (this.onActivate) {
  12847. this.onActivate(camera);
  12848. }
  12849. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  12850. if (this._reusable) {
  12851. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  12852. }
  12853. };
  12854. PostProcess.prototype.apply = function () {
  12855. if (!this._effect.isReady())
  12856. return null;
  12857. this._engine.enableEffect(this._effect);
  12858. this._engine.setState(false);
  12859. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12860. this._engine.setDepthBuffer(false);
  12861. this._engine.setDepthWrite(false);
  12862. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  12863. if (this.onApply) {
  12864. this.onApply(this._effect);
  12865. }
  12866. return this._effect;
  12867. };
  12868. PostProcess.prototype.dispose = function (camera) {
  12869. camera = camera || this._camera;
  12870. if (this._textures.length > 0) {
  12871. for (var i = 0; i < this._textures.length; i++) {
  12872. this._engine._releaseTexture(this._textures.data[i]);
  12873. }
  12874. this._textures.reset();
  12875. }
  12876. camera.detachPostProcess(this);
  12877. var index = camera._postProcesses.indexOf(this);
  12878. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  12879. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  12880. }
  12881. };
  12882. return PostProcess;
  12883. })();
  12884. BABYLON.PostProcess = PostProcess;
  12885. })(BABYLON || (BABYLON = {}));
  12886. var BABYLON;
  12887. (function (BABYLON) {
  12888. var PostProcessManager = (function () {
  12889. function PostProcessManager(scene) {
  12890. this._vertexDeclaration = [2];
  12891. this._vertexStrideSize = 2 * 4;
  12892. this._scene = scene;
  12893. var vertices = [];
  12894. vertices.push(1, 1);
  12895. vertices.push(-1, 1);
  12896. vertices.push(-1, -1);
  12897. vertices.push(1, -1);
  12898. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12899. var indices = [];
  12900. indices.push(0);
  12901. indices.push(1);
  12902. indices.push(2);
  12903. indices.push(0);
  12904. indices.push(2);
  12905. indices.push(3);
  12906. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12907. }
  12908. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  12909. var postProcesses = this._scene.activeCamera._postProcesses;
  12910. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12911. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12912. return false;
  12913. }
  12914. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  12915. return true;
  12916. };
  12917. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  12918. var postProcesses = this._scene.activeCamera._postProcesses;
  12919. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  12920. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  12921. return;
  12922. }
  12923. var engine = this._scene.getEngine();
  12924. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  12925. if (index < postProcessesTakenIndices.length - 1) {
  12926. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  12927. } else {
  12928. if (targetTexture) {
  12929. engine.bindFramebuffer(targetTexture);
  12930. } else {
  12931. engine.restoreDefaultFramebuffer();
  12932. }
  12933. }
  12934. if (doNotPresent) {
  12935. break;
  12936. }
  12937. var pp = postProcesses[postProcessesTakenIndices[index]];
  12938. var effect = pp.apply();
  12939. if (effect) {
  12940. if (pp.onBeforeRender) {
  12941. pp.onBeforeRender(effect);
  12942. }
  12943. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12944. engine.draw(true, 0, 6);
  12945. }
  12946. }
  12947. engine.setDepthBuffer(true);
  12948. engine.setDepthWrite(true);
  12949. };
  12950. PostProcessManager.prototype.dispose = function () {
  12951. if (this._vertexBuffer) {
  12952. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12953. this._vertexBuffer = null;
  12954. }
  12955. if (this._indexBuffer) {
  12956. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12957. this._indexBuffer = null;
  12958. }
  12959. };
  12960. return PostProcessManager;
  12961. })();
  12962. BABYLON.PostProcessManager = PostProcessManager;
  12963. })(BABYLON || (BABYLON = {}));
  12964. var __extends = this.__extends || function (d, b) {
  12965. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12966. function __() { this.constructor = d; }
  12967. __.prototype = b.prototype;
  12968. d.prototype = new __();
  12969. };
  12970. var BABYLON;
  12971. (function (BABYLON) {
  12972. var PassPostProcess = (function (_super) {
  12973. __extends(PassPostProcess, _super);
  12974. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  12975. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  12976. }
  12977. return PassPostProcess;
  12978. })(BABYLON.PostProcess);
  12979. BABYLON.PassPostProcess = PassPostProcess;
  12980. })(BABYLON || (BABYLON = {}));
  12981. var __extends = this.__extends || function (d, b) {
  12982. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12983. function __() { this.constructor = d; }
  12984. __.prototype = b.prototype;
  12985. d.prototype = new __();
  12986. };
  12987. var BABYLON;
  12988. (function (BABYLON) {
  12989. var BlurPostProcess = (function (_super) {
  12990. __extends(BlurPostProcess, _super);
  12991. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  12992. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  12993. var _this = this;
  12994. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  12995. this.direction = direction;
  12996. this.blurWidth = blurWidth;
  12997. this.onApply = function (effect) {
  12998. effect.setFloat2("screenSize", _this.width, _this.height);
  12999. effect.setVector2("direction", _this.direction);
  13000. effect.setFloat("blurWidth", _this.blurWidth);
  13001. };
  13002. }
  13003. return BlurPostProcess;
  13004. })(BABYLON.PostProcess);
  13005. BABYLON.BlurPostProcess = BlurPostProcess;
  13006. })(BABYLON || (BABYLON = {}));
  13007. var __extends = this.__extends || function (d, b) {
  13008. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13009. function __() { this.constructor = d; }
  13010. __.prototype = b.prototype;
  13011. d.prototype = new __();
  13012. };
  13013. var BABYLON;
  13014. (function (BABYLON) {
  13015. var FilterPostProcess = (function (_super) {
  13016. __extends(FilterPostProcess, _super);
  13017. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  13018. var _this = this;
  13019. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  13020. this.kernelMatrix = kernelMatrix;
  13021. this.onApply = function (effect) {
  13022. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  13023. };
  13024. }
  13025. return FilterPostProcess;
  13026. })(BABYLON.PostProcess);
  13027. BABYLON.FilterPostProcess = FilterPostProcess;
  13028. })(BABYLON || (BABYLON = {}));
  13029. var __extends = this.__extends || function (d, b) {
  13030. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13031. function __() { this.constructor = d; }
  13032. __.prototype = b.prototype;
  13033. d.prototype = new __();
  13034. };
  13035. var BABYLON;
  13036. (function (BABYLON) {
  13037. var RefractionPostProcess = (function (_super) {
  13038. __extends(RefractionPostProcess, _super);
  13039. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  13040. var _this = this;
  13041. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  13042. this.color = color;
  13043. this.depth = depth;
  13044. this.colorLevel = colorLevel;
  13045. this.onActivate = function (cam) {
  13046. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  13047. };
  13048. this.onApply = function (effect) {
  13049. effect.setColor3("baseColor", _this.color);
  13050. effect.setFloat("depth", _this.depth);
  13051. effect.setFloat("colorLevel", _this.colorLevel);
  13052. effect.setTexture("refractionSampler", _this._refRexture);
  13053. };
  13054. }
  13055. RefractionPostProcess.prototype.dispose = function (camera) {
  13056. if (this._refRexture) {
  13057. this._refRexture.dispose();
  13058. }
  13059. _super.prototype.dispose.call(this, camera);
  13060. };
  13061. return RefractionPostProcess;
  13062. })(BABYLON.PostProcess);
  13063. BABYLON.RefractionPostProcess = RefractionPostProcess;
  13064. })(BABYLON || (BABYLON = {}));
  13065. var __extends = this.__extends || function (d, b) {
  13066. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13067. function __() { this.constructor = d; }
  13068. __.prototype = b.prototype;
  13069. d.prototype = new __();
  13070. };
  13071. var BABYLON;
  13072. (function (BABYLON) {
  13073. var BlackAndWhitePostProcess = (function (_super) {
  13074. __extends(BlackAndWhitePostProcess, _super);
  13075. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  13076. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  13077. }
  13078. return BlackAndWhitePostProcess;
  13079. })(BABYLON.PostProcess);
  13080. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  13081. })(BABYLON || (BABYLON = {}));
  13082. var __extends = this.__extends || function (d, b) {
  13083. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13084. function __() { this.constructor = d; }
  13085. __.prototype = b.prototype;
  13086. d.prototype = new __();
  13087. };
  13088. var BABYLON;
  13089. (function (BABYLON) {
  13090. var ConvolutionPostProcess = (function (_super) {
  13091. __extends(ConvolutionPostProcess, _super);
  13092. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  13093. var _this = this;
  13094. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  13095. this.kernel = kernel;
  13096. this.onApply = function (effect) {
  13097. effect.setFloat2("screenSize", _this.width, _this.height);
  13098. effect.setArray("kernel", _this.kernel);
  13099. };
  13100. }
  13101. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  13102. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  13103. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  13104. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  13105. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  13106. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  13107. return ConvolutionPostProcess;
  13108. })(BABYLON.PostProcess);
  13109. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  13110. })(BABYLON || (BABYLON = {}));
  13111. var __extends = this.__extends || function (d, b) {
  13112. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13113. function __() { this.constructor = d; }
  13114. __.prototype = b.prototype;
  13115. d.prototype = new __();
  13116. };
  13117. var BABYLON;
  13118. (function (BABYLON) {
  13119. var FxaaPostProcess = (function (_super) {
  13120. __extends(FxaaPostProcess, _super);
  13121. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  13122. var _this = this;
  13123. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  13124. this.onSizeChanged = function () {
  13125. _this.texelWidth = 1.0 / _this.width;
  13126. _this.texelHeight = 1.0 / _this.height;
  13127. };
  13128. this.onApply = function (effect) {
  13129. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  13130. };
  13131. }
  13132. return FxaaPostProcess;
  13133. })(BABYLON.PostProcess);
  13134. BABYLON.FxaaPostProcess = FxaaPostProcess;
  13135. })(BABYLON || (BABYLON = {}));
  13136. var BABYLON;
  13137. (function (BABYLON) {
  13138. var LensFlare = (function () {
  13139. function LensFlare(size, position, color, imgUrl, system) {
  13140. this.size = size;
  13141. this.position = position;
  13142. this.dispose = function () {
  13143. if (this.texture) {
  13144. this.texture.dispose();
  13145. }
  13146. var index = this._system.lensFlares.indexOf(this);
  13147. this._system.lensFlares.splice(index, 1);
  13148. };
  13149. this.color = color || new BABYLON.Color3(1, 1, 1);
  13150. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  13151. this._system = system;
  13152. system.lensFlares.push(this);
  13153. }
  13154. return LensFlare;
  13155. })();
  13156. BABYLON.LensFlare = LensFlare;
  13157. })(BABYLON || (BABYLON = {}));
  13158. var BABYLON;
  13159. (function (BABYLON) {
  13160. var LensFlareSystem = (function () {
  13161. function LensFlareSystem(name, emitter, scene) {
  13162. this.name = name;
  13163. this.lensFlares = new Array();
  13164. this.borderLimit = 300;
  13165. this._vertexDeclaration = [2];
  13166. this._vertexStrideSize = 2 * 4;
  13167. this._isEnabled = true;
  13168. this._scene = scene;
  13169. this._emitter = emitter;
  13170. scene.lensFlareSystems.push(this);
  13171. this.meshesSelectionPredicate = function (m) {
  13172. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  13173. };
  13174. var vertices = [];
  13175. vertices.push(1, 1);
  13176. vertices.push(-1, 1);
  13177. vertices.push(-1, -1);
  13178. vertices.push(1, -1);
  13179. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13180. var indices = [];
  13181. indices.push(0);
  13182. indices.push(1);
  13183. indices.push(2);
  13184. indices.push(0);
  13185. indices.push(2);
  13186. indices.push(3);
  13187. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13188. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  13189. }
  13190. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  13191. get: function () {
  13192. return this._isEnabled;
  13193. },
  13194. set: function (value) {
  13195. this._isEnabled = value;
  13196. },
  13197. enumerable: true,
  13198. configurable: true
  13199. });
  13200. LensFlareSystem.prototype.getScene = function () {
  13201. return this._scene;
  13202. };
  13203. LensFlareSystem.prototype.getEmitter = function () {
  13204. return this._emitter;
  13205. };
  13206. LensFlareSystem.prototype.getEmitterPosition = function () {
  13207. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  13208. };
  13209. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  13210. var position = this.getEmitterPosition();
  13211. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  13212. this._positionX = position.x;
  13213. this._positionY = position.y;
  13214. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  13215. if (position.z > 0) {
  13216. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  13217. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  13218. return true;
  13219. }
  13220. }
  13221. return false;
  13222. };
  13223. LensFlareSystem.prototype._isVisible = function () {
  13224. if (!this._isEnabled) {
  13225. return false;
  13226. }
  13227. var emitterPosition = this.getEmitterPosition();
  13228. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  13229. var distance = direction.length();
  13230. direction.normalize();
  13231. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  13232. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  13233. return !pickInfo.hit || pickInfo.distance > distance;
  13234. };
  13235. LensFlareSystem.prototype.render = function () {
  13236. if (!this._effect.isReady())
  13237. return false;
  13238. var engine = this._scene.getEngine();
  13239. var viewport = this._scene.activeCamera.viewport;
  13240. var globalViewport = viewport.toGlobal(engine);
  13241. if (!this.computeEffectivePosition(globalViewport)) {
  13242. return false;
  13243. }
  13244. if (!this._isVisible()) {
  13245. return false;
  13246. }
  13247. var awayX;
  13248. var awayY;
  13249. if (this._positionX < this.borderLimit + globalViewport.x) {
  13250. awayX = this.borderLimit + globalViewport.x - this._positionX;
  13251. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  13252. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  13253. } else {
  13254. awayX = 0;
  13255. }
  13256. if (this._positionY < this.borderLimit + globalViewport.y) {
  13257. awayY = this.borderLimit + globalViewport.y - this._positionY;
  13258. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  13259. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  13260. } else {
  13261. awayY = 0;
  13262. }
  13263. var away = (awayX > awayY) ? awayX : awayY;
  13264. if (away > this.borderLimit) {
  13265. away = this.borderLimit;
  13266. }
  13267. var intensity = 1.0 - (away / this.borderLimit);
  13268. if (intensity < 0) {
  13269. return false;
  13270. }
  13271. if (intensity > 1.0) {
  13272. intensity = 1.0;
  13273. }
  13274. var centerX = globalViewport.x + globalViewport.width / 2;
  13275. var centerY = globalViewport.y + globalViewport.height / 2;
  13276. var distX = centerX - this._positionX;
  13277. var distY = centerY - this._positionY;
  13278. engine.enableEffect(this._effect);
  13279. engine.setState(false);
  13280. engine.setDepthBuffer(false);
  13281. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  13282. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13283. for (var index = 0; index < this.lensFlares.length; index++) {
  13284. var flare = this.lensFlares[index];
  13285. var x = centerX - (distX * flare.position);
  13286. var y = centerY - (distY * flare.position);
  13287. var cw = flare.size;
  13288. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  13289. var cx = 2 * (x / globalViewport.width) - 1.0;
  13290. var cy = 1.0 - 2 * (y / globalViewport.height);
  13291. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  13292. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  13293. this._effect.setTexture("textureSampler", flare.texture);
  13294. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  13295. engine.draw(true, 0, 6);
  13296. }
  13297. engine.setDepthBuffer(true);
  13298. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13299. return true;
  13300. };
  13301. LensFlareSystem.prototype.dispose = function () {
  13302. if (this._vertexBuffer) {
  13303. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13304. this._vertexBuffer = null;
  13305. }
  13306. if (this._indexBuffer) {
  13307. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13308. this._indexBuffer = null;
  13309. }
  13310. while (this.lensFlares.length) {
  13311. this.lensFlares[0].dispose();
  13312. }
  13313. var index = this._scene.lensFlareSystems.indexOf(this);
  13314. this._scene.lensFlareSystems.splice(index, 1);
  13315. };
  13316. return LensFlareSystem;
  13317. })();
  13318. BABYLON.LensFlareSystem = LensFlareSystem;
  13319. })(BABYLON || (BABYLON = {}));
  13320. var BABYLON;
  13321. (function (BABYLON) {
  13322. var IntersectionInfo = (function () {
  13323. function IntersectionInfo(bu, bv, distance) {
  13324. this.bu = bu;
  13325. this.bv = bv;
  13326. this.distance = distance;
  13327. this.faceId = 0;
  13328. }
  13329. return IntersectionInfo;
  13330. })();
  13331. BABYLON.IntersectionInfo = IntersectionInfo;
  13332. var PickingInfo = (function () {
  13333. function PickingInfo() {
  13334. this.hit = false;
  13335. this.distance = 0;
  13336. this.pickedPoint = null;
  13337. this.pickedMesh = null;
  13338. this.bu = 0;
  13339. this.bv = 0;
  13340. this.faceId = -1;
  13341. }
  13342. PickingInfo.prototype.getNormal = function () {
  13343. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13344. return null;
  13345. }
  13346. var indices = this.pickedMesh.getIndices();
  13347. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13348. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  13349. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  13350. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  13351. normal0 = normal0.scale(this.bu);
  13352. normal1 = normal1.scale(this.bv);
  13353. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  13354. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  13355. };
  13356. PickingInfo.prototype.getTextureCoordinates = function () {
  13357. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13358. return null;
  13359. }
  13360. var indices = this.pickedMesh.getIndices();
  13361. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  13362. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  13363. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  13364. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  13365. uv0 = uv0.scale(this.bu);
  13366. uv1 = uv1.scale(this.bv);
  13367. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  13368. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  13369. };
  13370. return PickingInfo;
  13371. })();
  13372. BABYLON.PickingInfo = PickingInfo;
  13373. })(BABYLON || (BABYLON = {}));
  13374. var BABYLON;
  13375. (function (BABYLON) {
  13376. var FilesInput = (function () {
  13377. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  13378. this.engine = p_engine;
  13379. this.canvas = p_canvas;
  13380. this.currentScene = p_scene;
  13381. this.sceneLoadedCallback = p_sceneLoadedCallback;
  13382. this.progressCallback = p_progressCallback;
  13383. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  13384. this.textureLoadingCallback = p_textureLoadingCallback;
  13385. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  13386. }
  13387. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  13388. var _this = this;
  13389. if (p_elementToMonitor) {
  13390. this.elementToMonitor = p_elementToMonitor;
  13391. this.elementToMonitor.addEventListener("dragenter", function (e) {
  13392. _this.drag(e);
  13393. }, false);
  13394. this.elementToMonitor.addEventListener("dragover", function (e) {
  13395. _this.drag(e);
  13396. }, false);
  13397. this.elementToMonitor.addEventListener("drop", function (e) {
  13398. _this.drop(e);
  13399. }, false);
  13400. }
  13401. };
  13402. FilesInput.prototype.renderFunction = function () {
  13403. if (this.additionnalRenderLoopLogicCallback) {
  13404. this.additionnalRenderLoopLogicCallback();
  13405. }
  13406. if (this.currentScene) {
  13407. if (this.textureLoadingCallback) {
  13408. var remaining = this.currentScene.getWaitingItemsCount();
  13409. if (remaining > 0) {
  13410. this.textureLoadingCallback(remaining);
  13411. }
  13412. }
  13413. this.currentScene.render();
  13414. }
  13415. };
  13416. FilesInput.prototype.drag = function (e) {
  13417. e.stopPropagation();
  13418. e.preventDefault();
  13419. };
  13420. FilesInput.prototype.drop = function (eventDrop) {
  13421. eventDrop.stopPropagation();
  13422. eventDrop.preventDefault();
  13423. this.loadFiles(eventDrop);
  13424. };
  13425. FilesInput.prototype.loadFiles = function (event) {
  13426. var _this = this;
  13427. var that = this;
  13428. if (this.startingProcessingFilesCallback)
  13429. this.startingProcessingFilesCallback();
  13430. var sceneFileToLoad;
  13431. var filesToLoad;
  13432. if (event && event.dataTransfer && event.dataTransfer.files) {
  13433. filesToLoad = event.dataTransfer.files;
  13434. }
  13435. if (event && event.target && event.target.files) {
  13436. filesToLoad = event.target.files;
  13437. }
  13438. if (filesToLoad && filesToLoad.length > 0) {
  13439. for (var i = 0; i < filesToLoad.length; i++) {
  13440. switch (filesToLoad[i].type) {
  13441. case "image/jpeg":
  13442. case "image/png":
  13443. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  13444. break;
  13445. case "image/targa":
  13446. case "image/vnd.ms-dds":
  13447. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  13448. break;
  13449. default:
  13450. 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) {
  13451. sceneFileToLoad = filesToLoad[i];
  13452. }
  13453. break;
  13454. }
  13455. }
  13456. if (sceneFileToLoad) {
  13457. if (this.currentScene) {
  13458. this.engine.stopRenderLoop();
  13459. this.currentScene.dispose();
  13460. }
  13461. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  13462. that.currentScene = newScene;
  13463. that.currentScene.executeWhenReady(function () {
  13464. if (that.currentScene.activeCamera) {
  13465. that.currentScene.activeCamera.attachControl(that.canvas);
  13466. }
  13467. if (that.sceneLoadedCallback) {
  13468. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  13469. }
  13470. that.engine.runRenderLoop(function () {
  13471. that.renderFunction();
  13472. });
  13473. });
  13474. }, function (progress) {
  13475. if (_this.progressCallback) {
  13476. _this.progressCallback(progress);
  13477. }
  13478. });
  13479. } else {
  13480. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  13481. }
  13482. }
  13483. };
  13484. FilesInput.FilesTextures = new Array();
  13485. FilesInput.FilesToLoad = new Array();
  13486. return FilesInput;
  13487. })();
  13488. BABYLON.FilesInput = FilesInput;
  13489. })(BABYLON || (BABYLON = {}));
  13490. var BABYLON;
  13491. (function (BABYLON) {
  13492. var OimoJSPlugin = (function () {
  13493. function OimoJSPlugin() {
  13494. this._registeredMeshes = [];
  13495. /**
  13496. * Update the body position according to the mesh position
  13497. * @param mesh
  13498. */
  13499. this.updateBodyPosition = function (mesh) {
  13500. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13501. var registeredMesh = this._registeredMeshes[index];
  13502. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13503. var body = registeredMesh.body.body;
  13504. mesh.computeWorldMatrix(true);
  13505. var center = mesh.getBoundingInfo().boundingBox.center;
  13506. body.setPosition(center.x, center.y, center.z);
  13507. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  13508. return;
  13509. }
  13510. if (registeredMesh.mesh.parent === mesh) {
  13511. mesh.computeWorldMatrix(true);
  13512. registeredMesh.mesh.computeWorldMatrix(true);
  13513. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  13514. var absoluteRotation = mesh.rotation;
  13515. body = registeredMesh.body.body;
  13516. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  13517. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  13518. return;
  13519. }
  13520. }
  13521. };
  13522. }
  13523. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  13524. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  13525. };
  13526. OimoJSPlugin.prototype.initialize = function (iterations) {
  13527. this._world = new OIMO.World();
  13528. this._world.clear();
  13529. };
  13530. OimoJSPlugin.prototype.setGravity = function (gravity) {
  13531. this._world.gravity = gravity;
  13532. };
  13533. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  13534. var body = null;
  13535. this.unregisterMesh(mesh);
  13536. mesh.computeWorldMatrix(true);
  13537. switch (impostor) {
  13538. case BABYLON.PhysicsEngine.SphereImpostor:
  13539. var bbox = mesh.getBoundingInfo().boundingBox;
  13540. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  13541. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  13542. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  13543. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  13544. var deltaPosition = mesh.position.subtract(bbox.center);
  13545. body = new OIMO.Body({
  13546. type: 'sphere',
  13547. size: [size],
  13548. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  13549. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  13550. move: options.mass != 0,
  13551. config: [options.mass, options.friction, options.restitution],
  13552. world: this._world
  13553. });
  13554. this._registeredMeshes.push({
  13555. mesh: mesh,
  13556. body: body,
  13557. delta: deltaPosition
  13558. });
  13559. break;
  13560. case BABYLON.PhysicsEngine.PlaneImpostor:
  13561. case BABYLON.PhysicsEngine.BoxImpostor:
  13562. bbox = mesh.getBoundingInfo().boundingBox;
  13563. var min = bbox.minimumWorld;
  13564. var max = bbox.maximumWorld;
  13565. var box = max.subtract(min);
  13566. var sizeX = this._checkWithEpsilon(box.x);
  13567. var sizeY = this._checkWithEpsilon(box.y);
  13568. var sizeZ = this._checkWithEpsilon(box.z);
  13569. var deltaPosition = mesh.position.subtract(bbox.center);
  13570. body = new OIMO.Body({
  13571. type: 'box',
  13572. size: [sizeX, sizeY, sizeZ],
  13573. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  13574. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  13575. move: options.mass != 0,
  13576. config: [options.mass, options.friction, options.restitution],
  13577. world: this._world
  13578. });
  13579. this._registeredMeshes.push({
  13580. mesh: mesh,
  13581. body: body,
  13582. delta: deltaPosition
  13583. });
  13584. break;
  13585. }
  13586. return body;
  13587. };
  13588. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  13589. var types = [], sizes = [], positions = [], rotations = [];
  13590. var initialMesh = parts[0].mesh;
  13591. for (var index = 0; index < parts.length; index++) {
  13592. var part = parts[index];
  13593. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  13594. types.push(bodyParameters.type);
  13595. sizes.push.apply(sizes, bodyParameters.size);
  13596. positions.push.apply(positions, bodyParameters.pos);
  13597. rotations.push.apply(rotations, bodyParameters.rot);
  13598. }
  13599. var body = new OIMO.Body({
  13600. type: types,
  13601. size: sizes,
  13602. pos: positions,
  13603. rot: rotations,
  13604. move: options.mass != 0,
  13605. config: [options.mass, options.friction, options.restitution],
  13606. world: this._world
  13607. });
  13608. this._registeredMeshes.push({
  13609. mesh: initialMesh,
  13610. body: body
  13611. });
  13612. return body;
  13613. };
  13614. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  13615. var bodyParameters = null;
  13616. var mesh = part.mesh;
  13617. switch (part.impostor) {
  13618. case BABYLON.PhysicsEngine.SphereImpostor:
  13619. var bbox = mesh.getBoundingInfo().boundingBox;
  13620. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  13621. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  13622. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  13623. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  13624. bodyParameters = {
  13625. type: 'sphere',
  13626. /* bug with oimo : sphere needs 3 sizes in this case */
  13627. size: [size, -1, -1],
  13628. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  13629. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  13630. };
  13631. break;
  13632. case BABYLON.PhysicsEngine.PlaneImpostor:
  13633. case BABYLON.PhysicsEngine.BoxImpostor:
  13634. bbox = mesh.getBoundingInfo().boundingBox;
  13635. var min = bbox.minimumWorld;
  13636. var max = bbox.maximumWorld;
  13637. var box = max.subtract(min);
  13638. var sizeX = this._checkWithEpsilon(box.x);
  13639. var sizeY = this._checkWithEpsilon(box.y);
  13640. var sizeZ = this._checkWithEpsilon(box.z);
  13641. var relativePosition = mesh.position;
  13642. bodyParameters = {
  13643. type: 'box',
  13644. size: [sizeX, sizeY, sizeZ],
  13645. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  13646. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  13647. };
  13648. break;
  13649. }
  13650. return bodyParameters;
  13651. };
  13652. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  13653. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13654. var registeredMesh = this._registeredMeshes[index];
  13655. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13656. if (registeredMesh.body) {
  13657. this._world.removeRigidBody(registeredMesh.body.body);
  13658. this._unbindBody(registeredMesh.body);
  13659. }
  13660. this._registeredMeshes.splice(index, 1);
  13661. return;
  13662. }
  13663. }
  13664. };
  13665. OimoJSPlugin.prototype._unbindBody = function (body) {
  13666. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13667. var registeredMesh = this._registeredMeshes[index];
  13668. if (registeredMesh.body === body) {
  13669. registeredMesh.body = null;
  13670. }
  13671. }
  13672. };
  13673. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  13674. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13675. var registeredMesh = this._registeredMeshes[index];
  13676. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13677. var mass = registeredMesh.body.body.massInfo.mass;
  13678. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  13679. return;
  13680. }
  13681. }
  13682. };
  13683. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13684. var body1 = null, body2 = null;
  13685. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13686. var registeredMesh = this._registeredMeshes[index];
  13687. if (registeredMesh.mesh === mesh1) {
  13688. body1 = registeredMesh.body.body;
  13689. } else if (registeredMesh.mesh === mesh2) {
  13690. body2 = registeredMesh.body.body;
  13691. }
  13692. }
  13693. if (!body1 || !body2) {
  13694. return false;
  13695. }
  13696. if (!options) {
  13697. options = {};
  13698. }
  13699. new OIMO.Link({
  13700. type: options.type,
  13701. body1: body1,
  13702. body2: body2,
  13703. min: options.min,
  13704. max: options.max,
  13705. axe1: options.axe1,
  13706. axe2: options.axe2,
  13707. pos1: [pivot1.x, pivot1.y, pivot1.z],
  13708. pos2: [pivot2.x, pivot2.y, pivot2.z],
  13709. collision: options.collision,
  13710. spring: options.spring,
  13711. world: this._world
  13712. });
  13713. return true;
  13714. };
  13715. OimoJSPlugin.prototype.dispose = function () {
  13716. this._world.clear();
  13717. while (this._registeredMeshes.length) {
  13718. this.unregisterMesh(this._registeredMeshes[0].mesh);
  13719. }
  13720. };
  13721. OimoJSPlugin.prototype.isSupported = function () {
  13722. return OIMO !== undefined;
  13723. };
  13724. OimoJSPlugin.prototype._getLastShape = function (body) {
  13725. var lastShape = body.shapes;
  13726. while (lastShape.next) {
  13727. lastShape = lastShape.next;
  13728. }
  13729. return lastShape;
  13730. };
  13731. OimoJSPlugin.prototype.runOneStep = function (time) {
  13732. this._world.step();
  13733. var i = this._registeredMeshes.length;
  13734. var m;
  13735. while (i--) {
  13736. var body = this._registeredMeshes[i].body.body;
  13737. var mesh = this._registeredMeshes[i].mesh;
  13738. var delta = this._registeredMeshes[i].delta;
  13739. if (!body.sleeping) {
  13740. if (body.shapes.next) {
  13741. var parentShape = this._getLastShape(body);
  13742. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  13743. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  13744. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  13745. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  13746. if (!mesh.rotationQuaternion) {
  13747. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13748. }
  13749. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13750. } else {
  13751. m = body.getMatrix();
  13752. mtx = BABYLON.Matrix.FromArray(m);
  13753. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  13754. if (!delta) {
  13755. mesh.position.x = bodyX;
  13756. mesh.position.y = bodyY;
  13757. mesh.position.z = bodyZ;
  13758. } else {
  13759. mesh.position.x = bodyX + delta.x;
  13760. mesh.position.y = bodyY + delta.y;
  13761. mesh.position.z = bodyZ + delta.z;
  13762. }
  13763. if (!mesh.rotationQuaternion) {
  13764. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13765. }
  13766. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13767. }
  13768. }
  13769. }
  13770. };
  13771. return OimoJSPlugin;
  13772. })();
  13773. BABYLON.OimoJSPlugin = OimoJSPlugin;
  13774. })(BABYLON || (BABYLON = {}));
  13775. var BABYLON;
  13776. (function (BABYLON) {
  13777. var PhysicsEngine = (function () {
  13778. function PhysicsEngine(plugin) {
  13779. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  13780. }
  13781. PhysicsEngine.prototype._initialize = function (gravity) {
  13782. this._currentPlugin.initialize();
  13783. this._setGravity(gravity);
  13784. };
  13785. PhysicsEngine.prototype._runOneStep = function (delta) {
  13786. if (delta > 0.1) {
  13787. delta = 0.1;
  13788. } else if (delta <= 0) {
  13789. delta = 1.0 / 60.0;
  13790. }
  13791. this._currentPlugin.runOneStep(delta);
  13792. };
  13793. PhysicsEngine.prototype._setGravity = function (gravity) {
  13794. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  13795. this._currentPlugin.setGravity(this.gravity);
  13796. };
  13797. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  13798. return this._currentPlugin.registerMesh(mesh, impostor, options);
  13799. };
  13800. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  13801. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  13802. };
  13803. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  13804. this._currentPlugin.unregisterMesh(mesh);
  13805. };
  13806. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  13807. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  13808. };
  13809. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13810. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  13811. };
  13812. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  13813. this._currentPlugin.updateBodyPosition(mesh);
  13814. };
  13815. PhysicsEngine.prototype.dispose = function () {
  13816. this._currentPlugin.dispose();
  13817. };
  13818. PhysicsEngine.prototype.isSupported = function () {
  13819. return this._currentPlugin.isSupported();
  13820. };
  13821. PhysicsEngine.NoImpostor = 0;
  13822. PhysicsEngine.SphereImpostor = 1;
  13823. PhysicsEngine.BoxImpostor = 2;
  13824. PhysicsEngine.PlaneImpostor = 3;
  13825. PhysicsEngine.MeshImpostor = 4;
  13826. PhysicsEngine.CapsuleImpostor = 5;
  13827. PhysicsEngine.ConeImpostor = 6;
  13828. PhysicsEngine.CylinderImpostor = 7;
  13829. PhysicsEngine.ConvexHullImpostor = 8;
  13830. PhysicsEngine.Epsilon = 0.001;
  13831. return PhysicsEngine;
  13832. })();
  13833. BABYLON.PhysicsEngine = PhysicsEngine;
  13834. })(BABYLON || (BABYLON = {}));
  13835. var BABYLON;
  13836. (function (BABYLON) {
  13837. var serializeLight = function (light) {
  13838. var serializationObject = {};
  13839. serializationObject.name = light.name;
  13840. serializationObject.id = light.id;
  13841. serializationObject.tags = BABYLON.Tags.GetTags(light);
  13842. if (light instanceof BABYLON.PointLight) {
  13843. serializationObject.type = 0;
  13844. serializationObject.position = light.position.asArray();
  13845. } else if (light instanceof BABYLON.DirectionalLight) {
  13846. serializationObject.type = 1;
  13847. var directionalLight = light;
  13848. serializationObject.position = directionalLight.position.asArray();
  13849. serializationObject.direction = directionalLight.direction.asArray();
  13850. } else if (light instanceof BABYLON.SpotLight) {
  13851. serializationObject.type = 2;
  13852. var spotLight = light;
  13853. serializationObject.position = spotLight.position.asArray();
  13854. serializationObject.direction = spotLight.position.asArray();
  13855. serializationObject.angle = spotLight.angle;
  13856. serializationObject.exponent = spotLight.exponent;
  13857. } else if (light instanceof BABYLON.HemisphericLight) {
  13858. serializationObject.type = 3;
  13859. var hemisphericLight = light;
  13860. serializationObject.direction = hemisphericLight.direction.asArray();
  13861. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  13862. }
  13863. if (light.intensity) {
  13864. serializationObject.intensity = light.intensity;
  13865. }
  13866. serializationObject.range = light.range;
  13867. serializationObject.diffuse = light.diffuse.asArray();
  13868. serializationObject.specular = light.specular.asArray();
  13869. return serializationObject;
  13870. };
  13871. var serializeFresnelParameter = function (fresnelParameter) {
  13872. var serializationObject = {};
  13873. serializationObject.isEnabled = fresnelParameter.isEnabled;
  13874. serializationObject.leftColor = fresnelParameter.leftColor;
  13875. serializationObject.rightColor = fresnelParameter.rightColor;
  13876. serializationObject.bias = fresnelParameter.bias;
  13877. serializationObject.power = fresnelParameter.power;
  13878. return serializationObject;
  13879. };
  13880. var serializeCamera = function (camera) {
  13881. var serializationObject = {};
  13882. serializationObject.name = camera.name;
  13883. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  13884. serializationObject.id = camera.id;
  13885. serializationObject.position = camera.position.asArray();
  13886. if (camera.parent) {
  13887. serializationObject.parentId = camera.parent.id;
  13888. }
  13889. serializationObject.rotation = camera.rotation.asArray();
  13890. if (camera.lockedTarget && camera.lockedTarget.id) {
  13891. serializationObject.lockedTargetId = camera.lockedTarget.id;
  13892. }
  13893. serializationObject.fov = camera.fov;
  13894. serializationObject.minZ = camera.minZ;
  13895. serializationObject.maxZ = camera.maxZ;
  13896. serializationObject.speed = camera.speed;
  13897. serializationObject.inertia = camera.inertia;
  13898. serializationObject.checkCollisions = camera.checkCollisions;
  13899. serializationObject.applyGravity = camera.applyGravity;
  13900. if (camera.ellipsoid) {
  13901. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  13902. }
  13903. appendAnimations(camera, serializationObject);
  13904. serializationObject.layerMask = camera.layerMask;
  13905. return serializationObject;
  13906. };
  13907. var appendAnimations = function (source, destination) {
  13908. if (source.animations) {
  13909. destination.animations = [];
  13910. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  13911. var animation = source.animations[animationIndex];
  13912. destination.animations.push(serializeAnimation(animation));
  13913. }
  13914. }
  13915. };
  13916. var serializeAnimation = function (animation) {
  13917. var serializationObject = {};
  13918. serializationObject.name = animation.name;
  13919. serializationObject.property = animation.targetProperty;
  13920. serializationObject.framePerSecond = animation.framePerSecond;
  13921. serializationObject.dataType = animation.dataType;
  13922. serializationObject.loopBehavior = animation.loopMode;
  13923. var dataType = animation.dataType;
  13924. serializationObject.keys = [];
  13925. var keys = animation.getKeys();
  13926. for (var index = 0; index < keys.length; index++) {
  13927. var animationKey = keys[index];
  13928. var key = {};
  13929. key.frame = animationKey.frame;
  13930. switch (dataType) {
  13931. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  13932. key.values = [animationKey.value];
  13933. break;
  13934. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  13935. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  13936. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  13937. key.values = animationKey.value.asArray();
  13938. break;
  13939. }
  13940. serializationObject.keys.push(key);
  13941. }
  13942. return serializationObject;
  13943. };
  13944. var serializeMultiMaterial = function (material) {
  13945. var serializationObject = {};
  13946. serializationObject.name = material.name;
  13947. serializationObject.id = material.id;
  13948. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13949. serializationObject.materials = [];
  13950. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  13951. var subMat = material.subMaterials[matIndex];
  13952. if (subMat) {
  13953. serializationObject.materials.push(subMat.id);
  13954. } else {
  13955. serializationObject.materials.push(null);
  13956. }
  13957. }
  13958. return serializationObject;
  13959. };
  13960. var serializeMaterial = function (material) {
  13961. var serializationObject = {};
  13962. serializationObject.name = material.name;
  13963. serializationObject.ambient = material.ambientColor.asArray();
  13964. serializationObject.diffuse = material.diffuseColor.asArray();
  13965. serializationObject.specular = material.specularColor.asArray();
  13966. serializationObject.specularPower = material.specularPower;
  13967. serializationObject.emissive = material.emissiveColor.asArray();
  13968. serializationObject.alpha = material.alpha;
  13969. serializationObject.id = material.id;
  13970. serializationObject.tags = BABYLON.Tags.GetTags(material);
  13971. serializationObject.backFaceCulling = material.backFaceCulling;
  13972. if (material.diffuseTexture) {
  13973. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  13974. }
  13975. if (material.diffuseFresnelParameters) {
  13976. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  13977. }
  13978. if (material.ambientTexture) {
  13979. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  13980. }
  13981. if (material.opacityTexture) {
  13982. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  13983. }
  13984. if (material.opacityFresnelParameters) {
  13985. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  13986. }
  13987. if (material.reflectionTexture) {
  13988. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  13989. }
  13990. if (material.reflectionFresnelParameters) {
  13991. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  13992. }
  13993. if (material.emissiveTexture) {
  13994. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  13995. }
  13996. if (material.emissiveFresnelParameters) {
  13997. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  13998. }
  13999. if (material.specularTexture) {
  14000. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  14001. }
  14002. if (material.bumpTexture) {
  14003. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  14004. }
  14005. return serializationObject;
  14006. };
  14007. var serializeTexture = function (texture) {
  14008. var serializationObject = {};
  14009. if (!texture.name) {
  14010. return null;
  14011. }
  14012. if (texture instanceof BABYLON.CubeTexture) {
  14013. serializationObject.name = texture.name;
  14014. serializationObject.hasAlpha = texture.hasAlpha;
  14015. serializationObject.level = texture.level;
  14016. serializationObject.coordinatesMode = texture.coordinatesMode;
  14017. return serializationObject;
  14018. }
  14019. if (texture instanceof BABYLON.MirrorTexture) {
  14020. var mirrorTexture = texture;
  14021. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  14022. serializationObject.renderList = [];
  14023. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  14024. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  14025. }
  14026. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  14027. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  14028. var renderTargetTexture = texture;
  14029. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  14030. serializationObject.renderList = [];
  14031. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  14032. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  14033. }
  14034. }
  14035. var regularTexture = texture;
  14036. serializationObject.name = texture.name;
  14037. serializationObject.hasAlpha = texture.hasAlpha;
  14038. serializationObject.level = texture.level;
  14039. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  14040. serializationObject.coordinatesMode = texture.coordinatesMode;
  14041. serializationObject.uOffset = regularTexture.uOffset;
  14042. serializationObject.vOffset = regularTexture.vOffset;
  14043. serializationObject.uScale = regularTexture.uScale;
  14044. serializationObject.vScale = regularTexture.vScale;
  14045. serializationObject.uAng = regularTexture.uAng;
  14046. serializationObject.vAng = regularTexture.vAng;
  14047. serializationObject.wAng = regularTexture.wAng;
  14048. serializationObject.wrapU = texture.wrapU;
  14049. serializationObject.wrapV = texture.wrapV;
  14050. appendAnimations(texture, serializationObject);
  14051. return serializationObject;
  14052. };
  14053. var serializeSkeleton = function (skeleton) {
  14054. var serializationObject = {};
  14055. serializationObject.name = skeleton.name;
  14056. serializationObject.id = skeleton.id;
  14057. serializationObject.bones = [];
  14058. for (var index = 0; index < skeleton.bones.length; index++) {
  14059. var bone = skeleton.bones[index];
  14060. var serializedBone = {
  14061. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  14062. name: bone.name,
  14063. matrix: bone.getLocalMatrix().toArray()
  14064. };
  14065. serializationObject.bones.push(serializedBone);
  14066. if (bone.animations && bone.animations.length > 0) {
  14067. serializedBone.animation = serializeAnimation(bone.animations[0]);
  14068. }
  14069. }
  14070. return serializationObject;
  14071. };
  14072. var serializeParticleSystem = function (particleSystem) {
  14073. var serializationObject = {};
  14074. serializationObject.emitterId = particleSystem.emitter.id;
  14075. serializationObject.capacity = particleSystem.getCapacity();
  14076. if (particleSystem.particleTexture) {
  14077. serializationObject.textureName = particleSystem.particleTexture.name;
  14078. }
  14079. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  14080. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  14081. serializationObject.minSize = particleSystem.minSize;
  14082. serializationObject.maxSize = particleSystem.maxSize;
  14083. serializationObject.minLifeTime = particleSystem.minLifeTime;
  14084. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  14085. serializationObject.emitRate = particleSystem.emitRate;
  14086. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  14087. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  14088. serializationObject.gravity = particleSystem.gravity.asArray();
  14089. serializationObject.direction1 = particleSystem.direction1.asArray();
  14090. serializationObject.direction2 = particleSystem.direction2.asArray();
  14091. serializationObject.color1 = particleSystem.color1.asArray();
  14092. serializationObject.color2 = particleSystem.color2.asArray();
  14093. serializationObject.colorDead = particleSystem.colorDead.asArray();
  14094. serializationObject.updateSpeed = particleSystem.updateSpeed;
  14095. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  14096. serializationObject.textureMask = particleSystem.textureMask.asArray();
  14097. serializationObject.blendMode = particleSystem.blendMode;
  14098. return serializationObject;
  14099. };
  14100. var serializeLensFlareSystem = function (lensFlareSystem) {
  14101. var serializationObject = {};
  14102. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  14103. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  14104. serializationObject.flares = [];
  14105. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  14106. var flare = lensFlareSystem.lensFlares[index];
  14107. serializationObject.flares.push({
  14108. size: flare.size,
  14109. position: flare.position,
  14110. color: flare.color.asArray(),
  14111. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  14112. });
  14113. }
  14114. return serializationObject;
  14115. };
  14116. var serializeShadowGenerator = function (light) {
  14117. var serializationObject = {};
  14118. var shadowGenerator = light.getShadowGenerator();
  14119. serializationObject.lightId = light.id;
  14120. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  14121. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  14122. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  14123. serializationObject.renderList = [];
  14124. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  14125. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  14126. serializationObject.renderList.push(mesh.id);
  14127. }
  14128. return serializationObject;
  14129. };
  14130. var serializedGeometries = [];
  14131. var serializeGeometry = function (geometry, serializationGeometries) {
  14132. if (serializedGeometries[geometry.id]) {
  14133. return;
  14134. }
  14135. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  14136. serializationGeometries.boxes.push(serializeBox(geometry));
  14137. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  14138. serializationGeometries.spheres.push(serializeSphere(geometry));
  14139. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  14140. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  14141. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  14142. serializationGeometries.toruses.push(serializeTorus(geometry));
  14143. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  14144. serializationGeometries.grounds.push(serializeGround(geometry));
  14145. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  14146. serializationGeometries.planes.push(serializePlane(geometry));
  14147. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  14148. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  14149. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  14150. throw new Error("Unknow primitive type");
  14151. } else {
  14152. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  14153. }
  14154. serializedGeometries[geometry.id] = true;
  14155. };
  14156. var serializeGeometryBase = function (geometry) {
  14157. var serializationObject = {};
  14158. serializationObject.id = geometry.id;
  14159. if (BABYLON.Tags.HasTags(geometry)) {
  14160. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  14161. }
  14162. return serializationObject;
  14163. };
  14164. var serializeVertexData = function (vertexData) {
  14165. var serializationObject = serializeGeometryBase(vertexData);
  14166. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14167. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14168. }
  14169. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14170. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14171. }
  14172. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14173. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14174. }
  14175. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14176. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  14177. }
  14178. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14179. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  14180. }
  14181. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  14182. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  14183. serializationObject.matricesIndices._isExpanded = true;
  14184. }
  14185. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  14186. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  14187. }
  14188. serializationObject.indices = vertexData.getIndices();
  14189. return serializationObject;
  14190. };
  14191. var serializePrimitive = function (primitive) {
  14192. var serializationObject = serializeGeometryBase(primitive);
  14193. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  14194. return serializationObject;
  14195. };
  14196. var serializeBox = function (box) {
  14197. var serializationObject = serializePrimitive(box);
  14198. serializationObject.size = box.size;
  14199. return serializationObject;
  14200. };
  14201. var serializeSphere = function (sphere) {
  14202. var serializationObject = serializePrimitive(sphere);
  14203. serializationObject.segments = sphere.segments;
  14204. serializationObject.diameter = sphere.diameter;
  14205. return serializationObject;
  14206. };
  14207. var serializeCylinder = function (cylinder) {
  14208. var serializationObject = serializePrimitive(cylinder);
  14209. serializationObject.height = cylinder.height;
  14210. serializationObject.diameterTop = cylinder.diameterTop;
  14211. serializationObject.diameterBottom = cylinder.diameterBottom;
  14212. serializationObject.tessellation = cylinder.tessellation;
  14213. return serializationObject;
  14214. };
  14215. var serializeTorus = function (torus) {
  14216. var serializationObject = serializePrimitive(torus);
  14217. serializationObject.diameter = torus.diameter;
  14218. serializationObject.thickness = torus.thickness;
  14219. serializationObject.tessellation = torus.tessellation;
  14220. return serializationObject;
  14221. };
  14222. var serializeGround = function (ground) {
  14223. var serializationObject = serializePrimitive(ground);
  14224. serializationObject.width = ground.width;
  14225. serializationObject.height = ground.height;
  14226. serializationObject.subdivisions = ground.subdivisions;
  14227. return serializationObject;
  14228. };
  14229. var serializePlane = function (plane) {
  14230. var serializationObject = serializePrimitive(plane);
  14231. serializationObject.size = plane.size;
  14232. return serializationObject;
  14233. };
  14234. var serializeTorusKnot = function (torusKnot) {
  14235. var serializationObject = serializePrimitive(torusKnot);
  14236. serializationObject.radius = torusKnot.radius;
  14237. serializationObject.tube = torusKnot.tube;
  14238. serializationObject.radialSegments = torusKnot.radialSegments;
  14239. serializationObject.tubularSegments = torusKnot.tubularSegments;
  14240. serializationObject.p = torusKnot.p;
  14241. serializationObject.q = torusKnot.q;
  14242. return serializationObject;
  14243. };
  14244. var serializeMesh = function (mesh, serializationScene) {
  14245. var serializationObject = {};
  14246. serializationObject.name = mesh.name;
  14247. serializationObject.id = mesh.id;
  14248. if (BABYLON.Tags.HasTags(mesh)) {
  14249. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  14250. }
  14251. serializationObject.position = mesh.position.asArray();
  14252. if (mesh.rotationQuaternion) {
  14253. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  14254. } else if (mesh.rotation) {
  14255. serializationObject.rotation = mesh.rotation.asArray();
  14256. }
  14257. serializationObject.scaling = mesh.scaling.asArray();
  14258. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  14259. serializationObject.isEnabled = mesh.isEnabled();
  14260. serializationObject.isVisible = mesh.isVisible;
  14261. serializationObject.infiniteDistance = mesh.infiniteDistance;
  14262. serializationObject.pickable = mesh.isPickable;
  14263. serializationObject.receiveShadows = mesh.receiveShadows;
  14264. serializationObject.billboardMode = mesh.billboardMode;
  14265. serializationObject.visibility = mesh.visibility;
  14266. serializationObject.checkCollisions = mesh.checkCollisions;
  14267. if (mesh.parent) {
  14268. serializationObject.parentId = mesh.parent.id;
  14269. }
  14270. var geometry = mesh._geometry;
  14271. if (geometry) {
  14272. var geometryId = geometry.id;
  14273. serializationObject.geometryId = geometryId;
  14274. if (!mesh.getScene().getGeometryByID(geometryId)) {
  14275. serializeGeometry(geometry, serializationScene.geometries);
  14276. }
  14277. serializationObject.subMeshes = [];
  14278. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  14279. var subMesh = mesh.subMeshes[subIndex];
  14280. serializationObject.subMeshes.push({
  14281. materialIndex: subMesh.materialIndex,
  14282. verticesStart: subMesh.verticesStart,
  14283. verticesCount: subMesh.verticesCount,
  14284. indexStart: subMesh.indexStart,
  14285. indexCount: subMesh.indexCount
  14286. });
  14287. }
  14288. }
  14289. if (mesh.material) {
  14290. serializationObject.materialId = mesh.material.id;
  14291. } else {
  14292. mesh.material = null;
  14293. }
  14294. if (mesh.skeleton) {
  14295. serializationObject.skeletonId = mesh.skeleton.id;
  14296. }
  14297. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  14298. serializationObject.physicsMass = mesh.getPhysicsMass();
  14299. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  14300. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  14301. switch (mesh.getPhysicsImpostor()) {
  14302. case BABYLON.PhysicsEngine.BoxImpostor:
  14303. serializationObject.physicsImpostor = 1;
  14304. break;
  14305. case BABYLON.PhysicsEngine.SphereImpostor:
  14306. serializationObject.physicsImpostor = 2;
  14307. break;
  14308. }
  14309. }
  14310. serializationObject.instances = [];
  14311. for (var index = 0; index < mesh.instances.length; index++) {
  14312. var instance = mesh.instances[index];
  14313. var serializationInstance = {
  14314. name: instance.name,
  14315. position: instance.position,
  14316. rotation: instance.rotation,
  14317. rotationQuaternion: instance.rotationQuaternion,
  14318. scaling: instance.scaling
  14319. };
  14320. serializationObject.instances.push(serializationInstance);
  14321. appendAnimations(instance, serializationInstance);
  14322. }
  14323. appendAnimations(mesh, serializationObject);
  14324. serializationObject.layerMask = mesh.layerMask;
  14325. return serializationObject;
  14326. };
  14327. var SceneSerializer = (function () {
  14328. function SceneSerializer() {
  14329. }
  14330. SceneSerializer.Serialize = function (scene) {
  14331. var serializationObject = {};
  14332. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  14333. serializationObject.autoClear = scene.autoClear;
  14334. serializationObject.clearColor = scene.clearColor.asArray();
  14335. serializationObject.ambientColor = scene.ambientColor.asArray();
  14336. serializationObject.gravity = scene.gravity.asArray();
  14337. if (scene.fogMode && scene.fogMode !== 0) {
  14338. serializationObject.fogMode = scene.fogMode;
  14339. serializationObject.fogColor = scene.fogColor.asArray();
  14340. serializationObject.fogStart = scene.fogStart;
  14341. serializationObject.fogEnd = scene.fogEnd;
  14342. serializationObject.fogDensity = scene.fogDensity;
  14343. }
  14344. serializationObject.lights = [];
  14345. for (var index = 0; index < scene.lights.length; index++) {
  14346. var light = scene.lights[index];
  14347. serializationObject.lights.push(serializeLight(light));
  14348. }
  14349. serializationObject.cameras = [];
  14350. for (index = 0; index < scene.cameras.length; index++) {
  14351. var camera = scene.cameras[index];
  14352. if (camera instanceof BABYLON.FreeCamera) {
  14353. serializationObject.cameras.push(serializeCamera(camera));
  14354. }
  14355. }
  14356. if (scene.activeCamera) {
  14357. serializationObject.activeCameraID = scene.activeCamera.id;
  14358. }
  14359. serializationObject.materials = [];
  14360. serializationObject.multiMaterials = [];
  14361. for (index = 0; index < scene.materials.length; index++) {
  14362. var material = scene.materials[index];
  14363. if (material instanceof BABYLON.StandardMaterial) {
  14364. serializationObject.materials.push(serializeMaterial(material));
  14365. } else if (material instanceof BABYLON.MultiMaterial) {
  14366. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  14367. }
  14368. }
  14369. serializationObject.skeletons = [];
  14370. for (index = 0; index < scene.skeletons.length; index++) {
  14371. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  14372. }
  14373. serializationObject.geometries = {};
  14374. serializationObject.geometries.boxes = [];
  14375. serializationObject.geometries.spheres = [];
  14376. serializationObject.geometries.cylinders = [];
  14377. serializationObject.geometries.toruses = [];
  14378. serializationObject.geometries.grounds = [];
  14379. serializationObject.geometries.planes = [];
  14380. serializationObject.geometries.torusKnots = [];
  14381. serializationObject.geometries.vertexData = [];
  14382. serializedGeometries = [];
  14383. var geometries = scene.getGeometries();
  14384. for (var index = 0; index < geometries.length; index++) {
  14385. var geometry = geometries[index];
  14386. if (geometry.isReady()) {
  14387. serializeGeometry(geometry, serializationObject.geometries);
  14388. }
  14389. }
  14390. serializationObject.meshes = [];
  14391. for (index = 0; index < scene.meshes.length; index++) {
  14392. var abstractMesh = scene.meshes[index];
  14393. if (abstractMesh instanceof BABYLON.Mesh) {
  14394. var mesh = abstractMesh;
  14395. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  14396. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  14397. }
  14398. }
  14399. }
  14400. serializationObject.particleSystems = [];
  14401. for (index = 0; index < scene.particleSystems.length; index++) {
  14402. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  14403. }
  14404. serializationObject.lensFlareSystems = [];
  14405. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  14406. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  14407. }
  14408. serializationObject.shadowGenerators = [];
  14409. for (index = 0; index < scene.lights.length; index++) {
  14410. light = scene.lights[index];
  14411. if (light.getShadowGenerator()) {
  14412. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  14413. }
  14414. }
  14415. return serializationObject;
  14416. };
  14417. return SceneSerializer;
  14418. })();
  14419. BABYLON.SceneSerializer = SceneSerializer;
  14420. })(BABYLON || (BABYLON = {}));
  14421. var BABYLON;
  14422. (function (BABYLON) {
  14423. var SceneLoader = (function () {
  14424. function SceneLoader() {
  14425. }
  14426. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  14427. get: function () {
  14428. return SceneLoader._ForceFullSceneLoadingForIncremental;
  14429. },
  14430. set: function (value) {
  14431. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  14432. },
  14433. enumerable: true,
  14434. configurable: true
  14435. });
  14436. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  14437. get: function () {
  14438. return SceneLoader._ShowLoadingScreen;
  14439. },
  14440. set: function (value) {
  14441. SceneLoader._ShowLoadingScreen = value;
  14442. },
  14443. enumerable: true,
  14444. configurable: true
  14445. });
  14446. SceneLoader._getPluginForFilename = function (sceneFilename) {
  14447. var dotPosition = sceneFilename.lastIndexOf(".");
  14448. var queryStringPosition = sceneFilename.indexOf("?");
  14449. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  14450. for (var index = 0; index < this._registeredPlugins.length; index++) {
  14451. var plugin = this._registeredPlugins[index];
  14452. if (plugin.extensions.indexOf(extension) !== -1) {
  14453. return plugin;
  14454. }
  14455. }
  14456. return this._registeredPlugins[this._registeredPlugins.length - 1];
  14457. };
  14458. SceneLoader.RegisterPlugin = function (plugin) {
  14459. plugin.extensions = plugin.extensions.toLowerCase();
  14460. SceneLoader._registeredPlugins.push(plugin);
  14461. };
  14462. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  14463. var _this = this;
  14464. var manifestChecked = function (success) {
  14465. scene.database = database;
  14466. var plugin = _this._getPluginForFilename(sceneFilename);
  14467. var importMeshFromData = function (data) {
  14468. var meshes = [];
  14469. var particleSystems = [];
  14470. var skeletons = [];
  14471. try {
  14472. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  14473. if (onerror) {
  14474. onerror(scene);
  14475. }
  14476. return;
  14477. }
  14478. } catch (e) {
  14479. if (onerror) {
  14480. onerror(scene);
  14481. }
  14482. return;
  14483. }
  14484. if (onsuccess) {
  14485. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  14486. onsuccess(meshes, particleSystems, skeletons);
  14487. }
  14488. };
  14489. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  14490. importMeshFromData(sceneFilename.substr(5));
  14491. return;
  14492. }
  14493. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  14494. importMeshFromData(data);
  14495. }, progressCallBack, database);
  14496. };
  14497. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  14498. };
  14499. /**
  14500. * Load a scene
  14501. * @param rootUrl a string that defines the root url for scene and resources
  14502. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  14503. * @param engine is the instance of BABYLON.Engine to use to create the scene
  14504. */
  14505. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  14506. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  14507. };
  14508. /**
  14509. * Append a scene
  14510. * @param rootUrl a string that defines the root url for scene and resources
  14511. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  14512. * @param scene is the instance of BABYLON.Scene to append to
  14513. */
  14514. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  14515. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  14516. var database;
  14517. if (SceneLoader.ShowLoadingScreen) {
  14518. scene.getEngine().displayLoadingUI();
  14519. }
  14520. var loadSceneFromData = function (data) {
  14521. scene.database = database;
  14522. if (!plugin.load(scene, data, rootUrl)) {
  14523. if (onerror) {
  14524. onerror(scene);
  14525. }
  14526. scene.getEngine().hideLoadingUI();
  14527. return;
  14528. }
  14529. if (onsuccess) {
  14530. onsuccess(scene);
  14531. }
  14532. if (SceneLoader.ShowLoadingScreen) {
  14533. scene.executeWhenReady(function () {
  14534. scene.getEngine().hideLoadingUI();
  14535. });
  14536. }
  14537. };
  14538. var manifestChecked = function (success) {
  14539. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  14540. };
  14541. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  14542. loadSceneFromData(sceneFilename.substr(5));
  14543. return;
  14544. }
  14545. if (rootUrl.indexOf("file:") === -1) {
  14546. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  14547. } else {
  14548. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  14549. }
  14550. };
  14551. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  14552. SceneLoader._ShowLoadingScreen = true;
  14553. SceneLoader._registeredPlugins = new Array();
  14554. return SceneLoader;
  14555. })();
  14556. BABYLON.SceneLoader = SceneLoader;
  14557. ;
  14558. })(BABYLON || (BABYLON = {}));
  14559. var BABYLON;
  14560. (function (BABYLON) {
  14561. (function (Internals) {
  14562. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  14563. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  14564. texture.name = parsedTexture.name;
  14565. texture.hasAlpha = parsedTexture.hasAlpha;
  14566. texture.level = parsedTexture.level;
  14567. texture.coordinatesMode = parsedTexture.coordinatesMode;
  14568. return texture;
  14569. };
  14570. var loadTexture = function (rootUrl, parsedTexture, scene) {
  14571. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  14572. return null;
  14573. }
  14574. if (parsedTexture.isCube) {
  14575. return loadCubeTexture(rootUrl, parsedTexture, scene);
  14576. }
  14577. var texture;
  14578. if (parsedTexture.mirrorPlane) {
  14579. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  14580. texture._waitingRenderList = parsedTexture.renderList;
  14581. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  14582. } else if (parsedTexture.isRenderTarget) {
  14583. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  14584. texture._waitingRenderList = parsedTexture.renderList;
  14585. } else {
  14586. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  14587. }
  14588. texture.name = parsedTexture.name;
  14589. texture.hasAlpha = parsedTexture.hasAlpha;
  14590. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  14591. texture.level = parsedTexture.level;
  14592. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  14593. texture.coordinatesMode = parsedTexture.coordinatesMode;
  14594. texture.uOffset = parsedTexture.uOffset;
  14595. texture.vOffset = parsedTexture.vOffset;
  14596. texture.uScale = parsedTexture.uScale;
  14597. texture.vScale = parsedTexture.vScale;
  14598. texture.uAng = parsedTexture.uAng;
  14599. texture.vAng = parsedTexture.vAng;
  14600. texture.wAng = parsedTexture.wAng;
  14601. texture.wrapU = parsedTexture.wrapU;
  14602. texture.wrapV = parsedTexture.wrapV;
  14603. if (parsedTexture.animations) {
  14604. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  14605. var parsedAnimation = parsedTexture.animations[animationIndex];
  14606. texture.animations.push(parseAnimation(parsedAnimation));
  14607. }
  14608. }
  14609. return texture;
  14610. };
  14611. var parseSkeleton = function (parsedSkeleton, scene) {
  14612. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  14613. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  14614. var parsedBone = parsedSkeleton.bones[index];
  14615. var parentBone = null;
  14616. if (parsedBone.parentBoneIndex > -1) {
  14617. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  14618. }
  14619. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  14620. if (parsedBone.animation) {
  14621. bone.animations.push(parseAnimation(parsedBone.animation));
  14622. }
  14623. }
  14624. return skeleton;
  14625. };
  14626. var parseFresnelParameters = function (parsedFresnelParameters) {
  14627. var fresnelParameters = new BABYLON.FresnelParameters();
  14628. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  14629. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  14630. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  14631. fresnelParameters.bias = parsedFresnelParameters.bias;
  14632. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  14633. return fresnelParameters;
  14634. };
  14635. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  14636. var material;
  14637. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  14638. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  14639. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  14640. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  14641. material.specularPower = parsedMaterial.specularPower;
  14642. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  14643. material.alpha = parsedMaterial.alpha;
  14644. material.id = parsedMaterial.id;
  14645. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  14646. material.backFaceCulling = parsedMaterial.backFaceCulling;
  14647. material.wireframe = parsedMaterial.wireframe;
  14648. if (parsedMaterial.diffuseTexture) {
  14649. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  14650. }
  14651. if (parsedMaterial.diffuseFresnelParameters) {
  14652. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  14653. }
  14654. if (parsedMaterial.ambientTexture) {
  14655. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  14656. }
  14657. if (parsedMaterial.opacityTexture) {
  14658. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  14659. }
  14660. if (parsedMaterial.opacityFresnelParameters) {
  14661. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  14662. }
  14663. if (parsedMaterial.reflectionTexture) {
  14664. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  14665. }
  14666. if (parsedMaterial.reflectionFresnelParameters) {
  14667. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  14668. }
  14669. if (parsedMaterial.emissiveTexture) {
  14670. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  14671. }
  14672. if (parsedMaterial.emissiveFresnelParameters) {
  14673. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  14674. }
  14675. if (parsedMaterial.specularTexture) {
  14676. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  14677. }
  14678. if (parsedMaterial.bumpTexture) {
  14679. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  14680. }
  14681. return material;
  14682. };
  14683. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  14684. for (var index = 0; index < parsedData.materials.length; index++) {
  14685. var parsedMaterial = parsedData.materials[index];
  14686. if (parsedMaterial.id === id) {
  14687. return parseMaterial(parsedMaterial, scene, rootUrl);
  14688. }
  14689. }
  14690. return null;
  14691. };
  14692. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  14693. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  14694. multiMaterial.id = parsedMultiMaterial.id;
  14695. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  14696. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14697. var subMatId = parsedMultiMaterial.materials[matIndex];
  14698. if (subMatId) {
  14699. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  14700. } else {
  14701. multiMaterial.subMaterials.push(null);
  14702. }
  14703. }
  14704. return multiMaterial;
  14705. };
  14706. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  14707. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  14708. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  14709. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  14710. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  14711. var parsedFlare = parsedLensFlareSystem.flares[index];
  14712. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  14713. }
  14714. return lensFlareSystem;
  14715. };
  14716. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  14717. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  14718. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  14719. if (parsedParticleSystem.textureName) {
  14720. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  14721. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  14722. }
  14723. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  14724. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  14725. particleSystem.minSize = parsedParticleSystem.minSize;
  14726. particleSystem.maxSize = parsedParticleSystem.maxSize;
  14727. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  14728. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  14729. particleSystem.emitter = emitter;
  14730. particleSystem.emitRate = parsedParticleSystem.emitRate;
  14731. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  14732. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  14733. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  14734. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  14735. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  14736. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  14737. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  14738. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  14739. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  14740. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  14741. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  14742. particleSystem.blendMode = parsedParticleSystem.blendMode;
  14743. particleSystem.start();
  14744. return particleSystem;
  14745. };
  14746. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  14747. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  14748. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  14749. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  14750. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  14751. shadowGenerator.getShadowMap().renderList.push(mesh);
  14752. }
  14753. if (parsedShadowGenerator.usePoissonSampling) {
  14754. shadowGenerator.usePoissonSampling = true;
  14755. } else {
  14756. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  14757. }
  14758. return shadowGenerator;
  14759. };
  14760. var parseAnimation = function (parsedAnimation) {
  14761. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  14762. var dataType = parsedAnimation.dataType;
  14763. var keys = [];
  14764. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  14765. var key = parsedAnimation.keys[index];
  14766. var data;
  14767. switch (dataType) {
  14768. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  14769. data = key.values[0];
  14770. break;
  14771. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  14772. data = BABYLON.Quaternion.FromArray(key.values);
  14773. break;
  14774. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  14775. data = BABYLON.Matrix.FromArray(key.values);
  14776. break;
  14777. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  14778. default:
  14779. data = BABYLON.Vector3.FromArray(key.values);
  14780. break;
  14781. }
  14782. keys.push({
  14783. frame: key.frame,
  14784. value: data
  14785. });
  14786. }
  14787. animation.setKeys(keys);
  14788. return animation;
  14789. };
  14790. var parseLight = function (parsedLight, scene) {
  14791. var light;
  14792. switch (parsedLight.type) {
  14793. case 0:
  14794. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  14795. break;
  14796. case 1:
  14797. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14798. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  14799. break;
  14800. case 2:
  14801. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  14802. break;
  14803. case 3:
  14804. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  14805. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  14806. break;
  14807. }
  14808. light.id = parsedLight.id;
  14809. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  14810. if (parsedLight.intensity !== undefined) {
  14811. light.intensity = parsedLight.intensity;
  14812. }
  14813. if (parsedLight.range) {
  14814. light.range = parsedLight.range;
  14815. }
  14816. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  14817. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  14818. if (parsedLight.excludedMeshesIds) {
  14819. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14820. }
  14821. if (parsedLight.includedOnlyMeshesIds) {
  14822. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14823. }
  14824. if (parsedLight.animations) {
  14825. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14826. var parsedAnimation = parsedLight.animations[animationIndex];
  14827. light.animations.push(parseAnimation(parsedAnimation));
  14828. }
  14829. }
  14830. if (parsedLight.autoAnimate) {
  14831. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  14832. }
  14833. };
  14834. var parseCamera = function (parsedCamera, scene) {
  14835. var camera;
  14836. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  14837. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  14838. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  14839. var alpha = parsedCamera.alpha;
  14840. var beta = parsedCamera.beta;
  14841. var radius = parsedCamera.radius;
  14842. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  14843. var eye_space = parsedCamera.eye_space;
  14844. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  14845. } else {
  14846. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  14847. }
  14848. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  14849. var eye_space = parsedCamera.eye_space;
  14850. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  14851. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  14852. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  14853. } else if (parsedCamera.type === "FollowCamera") {
  14854. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  14855. camera.heightOffset = parsedCamera.heightOffset;
  14856. camera.radius = parsedCamera.radius;
  14857. camera.rotationOffset = parsedCamera.rotationOffset;
  14858. if (lockedTargetMesh)
  14859. camera.target = lockedTargetMesh;
  14860. } else if (parsedCamera.type === "GamepadCamera") {
  14861. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  14862. } else if (parsedCamera.type === "OculusCamera") {
  14863. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  14864. } else if (parsedCamera.type === "TouchCamera") {
  14865. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  14866. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  14867. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  14868. } else if (parsedCamera.type === "WebVRCamera") {
  14869. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  14870. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  14871. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  14872. } else {
  14873. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  14874. }
  14875. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  14876. camera.lockedTarget = lockedTargetMesh;
  14877. }
  14878. camera.id = parsedCamera.id;
  14879. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  14880. if (parsedCamera.parentId) {
  14881. camera._waitingParentId = parsedCamera.parentId;
  14882. }
  14883. if (parsedCamera.target) {
  14884. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14885. } else {
  14886. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  14887. }
  14888. camera.fov = parsedCamera.fov;
  14889. camera.minZ = parsedCamera.minZ;
  14890. camera.maxZ = parsedCamera.maxZ;
  14891. camera.speed = parsedCamera.speed;
  14892. camera.inertia = parsedCamera.inertia;
  14893. camera.checkCollisions = parsedCamera.checkCollisions;
  14894. camera.applyGravity = parsedCamera.applyGravity;
  14895. if (parsedCamera.ellipsoid) {
  14896. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  14897. }
  14898. if (parsedCamera.animations) {
  14899. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14900. var parsedAnimation = parsedCamera.animations[animationIndex];
  14901. camera.animations.push(parseAnimation(parsedAnimation));
  14902. }
  14903. }
  14904. if (parsedCamera.autoAnimate) {
  14905. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  14906. }
  14907. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  14908. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  14909. } else {
  14910. camera.layerMask = 0xFFFFFFFF;
  14911. }
  14912. return camera;
  14913. };
  14914. var parseGeometry = function (parsedGeometry, scene) {
  14915. var id = parsedGeometry.id;
  14916. return scene.getGeometryByID(id);
  14917. };
  14918. var parseBox = function (parsedBox, scene) {
  14919. if (parseGeometry(parsedBox, scene)) {
  14920. return null;
  14921. }
  14922. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  14923. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  14924. scene.pushGeometry(box, true);
  14925. return box;
  14926. };
  14927. var parseSphere = function (parsedSphere, scene) {
  14928. if (parseGeometry(parsedSphere, scene)) {
  14929. return null;
  14930. }
  14931. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  14932. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  14933. scene.pushGeometry(sphere, true);
  14934. return sphere;
  14935. };
  14936. var parseCylinder = function (parsedCylinder, scene) {
  14937. if (parseGeometry(parsedCylinder, scene)) {
  14938. return null;
  14939. }
  14940. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  14941. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  14942. scene.pushGeometry(cylinder, true);
  14943. return cylinder;
  14944. };
  14945. var parseTorus = function (parsedTorus, scene) {
  14946. if (parseGeometry(parsedTorus, scene)) {
  14947. return null;
  14948. }
  14949. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  14950. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  14951. scene.pushGeometry(torus, true);
  14952. return torus;
  14953. };
  14954. var parseGround = function (parsedGround, scene) {
  14955. if (parseGeometry(parsedGround, scene)) {
  14956. return null;
  14957. }
  14958. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  14959. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  14960. scene.pushGeometry(ground, true);
  14961. return ground;
  14962. };
  14963. var parsePlane = function (parsedPlane, scene) {
  14964. if (parseGeometry(parsedPlane, scene)) {
  14965. return null;
  14966. }
  14967. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  14968. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  14969. scene.pushGeometry(plane, true);
  14970. return plane;
  14971. };
  14972. var parseTorusKnot = function (parsedTorusKnot, scene) {
  14973. if (parseGeometry(parsedTorusKnot, scene)) {
  14974. return null;
  14975. }
  14976. 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);
  14977. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  14978. scene.pushGeometry(torusKnot, true);
  14979. return torusKnot;
  14980. };
  14981. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  14982. if (parseGeometry(parsedVertexData, scene)) {
  14983. return null;
  14984. }
  14985. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  14986. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  14987. if (parsedVertexData.delayLoadingFile) {
  14988. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14989. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  14990. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  14991. geometry._delayInfo = [];
  14992. if (parsedVertexData.hasUVs) {
  14993. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  14994. }
  14995. if (parsedVertexData.hasUVs2) {
  14996. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  14997. }
  14998. if (parsedVertexData.hasColors) {
  14999. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15000. }
  15001. if (parsedVertexData.hasMatricesIndices) {
  15002. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15003. }
  15004. if (parsedVertexData.hasMatricesWeights) {
  15005. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15006. }
  15007. geometry._delayLoadingFunction = importVertexData;
  15008. } else {
  15009. importVertexData(parsedVertexData, geometry);
  15010. }
  15011. scene.pushGeometry(geometry, true);
  15012. return geometry;
  15013. };
  15014. var parseMesh = function (parsedMesh, scene, rootUrl) {
  15015. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  15016. mesh.id = parsedMesh.id;
  15017. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15018. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15019. if (parsedMesh.rotationQuaternion) {
  15020. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15021. } else if (parsedMesh.rotation) {
  15022. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15023. }
  15024. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15025. if (parsedMesh.localMatrix) {
  15026. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15027. } else if (parsedMesh.pivotMatrix) {
  15028. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15029. }
  15030. mesh.setEnabled(parsedMesh.isEnabled);
  15031. mesh.isVisible = parsedMesh.isVisible;
  15032. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15033. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15034. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15035. if (parsedMesh.pickable !== undefined) {
  15036. mesh.isPickable = parsedMesh.pickable;
  15037. }
  15038. mesh.receiveShadows = parsedMesh.receiveShadows;
  15039. mesh.billboardMode = parsedMesh.billboardMode;
  15040. if (parsedMesh.visibility !== undefined) {
  15041. mesh.visibility = parsedMesh.visibility;
  15042. }
  15043. mesh.checkCollisions = parsedMesh.checkCollisions;
  15044. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15045. if (parsedMesh.parentId) {
  15046. mesh._waitingParentId = parsedMesh.parentId;
  15047. }
  15048. if (parsedMesh.delayLoadingFile) {
  15049. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15050. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15051. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15052. if (parsedMesh._binaryInfo) {
  15053. mesh._binaryInfo = parsedMesh._binaryInfo;
  15054. }
  15055. mesh._delayInfo = [];
  15056. if (parsedMesh.hasUVs) {
  15057. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15058. }
  15059. if (parsedMesh.hasUVs2) {
  15060. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15061. }
  15062. if (parsedMesh.hasColors) {
  15063. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15064. }
  15065. if (parsedMesh.hasMatricesIndices) {
  15066. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15067. }
  15068. if (parsedMesh.hasMatricesWeights) {
  15069. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15070. }
  15071. mesh._delayLoadingFunction = importGeometry;
  15072. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15073. mesh._checkDelayState();
  15074. }
  15075. } else {
  15076. importGeometry(parsedMesh, mesh);
  15077. }
  15078. if (parsedMesh.materialId) {
  15079. mesh.setMaterialByID(parsedMesh.materialId);
  15080. } else {
  15081. mesh.material = null;
  15082. }
  15083. if (parsedMesh.skeletonId > -1) {
  15084. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15085. }
  15086. if (parsedMesh.physicsImpostor) {
  15087. if (!scene.isPhysicsEnabled()) {
  15088. scene.enablePhysics();
  15089. }
  15090. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15091. }
  15092. if (parsedMesh.animations) {
  15093. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15094. var parsedAnimation = parsedMesh.animations[animationIndex];
  15095. mesh.animations.push(parseAnimation(parsedAnimation));
  15096. }
  15097. }
  15098. if (parsedMesh.autoAnimate) {
  15099. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15100. }
  15101. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15102. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15103. } else {
  15104. mesh.layerMask = 0xFFFFFFFF;
  15105. }
  15106. if (parsedMesh.instances) {
  15107. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15108. var parsedInstance = parsedMesh.instances[index];
  15109. var instance = mesh.createInstance(parsedInstance.name);
  15110. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  15111. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  15112. if (parsedInstance.rotationQuaternion) {
  15113. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  15114. } else if (parsedInstance.rotation) {
  15115. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  15116. }
  15117. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  15118. instance.checkCollisions = mesh.checkCollisions;
  15119. if (parsedMesh.animations) {
  15120. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15121. parsedAnimation = parsedMesh.animations[animationIndex];
  15122. instance.animations.push(parseAnimation(parsedAnimation));
  15123. }
  15124. }
  15125. }
  15126. }
  15127. return mesh;
  15128. };
  15129. var isDescendantOf = function (mesh, names, hierarchyIds) {
  15130. names = (names instanceof Array) ? names : [names];
  15131. for (var i in names) {
  15132. if (mesh.name === names[i]) {
  15133. hierarchyIds.push(mesh.id);
  15134. return true;
  15135. }
  15136. }
  15137. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  15138. hierarchyIds.push(mesh.id);
  15139. return true;
  15140. }
  15141. return false;
  15142. };
  15143. var importVertexData = function (parsedVertexData, geometry) {
  15144. var vertexData = new BABYLON.VertexData();
  15145. var positions = parsedVertexData.positions;
  15146. if (positions) {
  15147. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  15148. }
  15149. var normals = parsedVertexData.normals;
  15150. if (normals) {
  15151. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  15152. }
  15153. var uvs = parsedVertexData.uvs;
  15154. if (uvs) {
  15155. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  15156. }
  15157. var uv2s = parsedVertexData.uv2s;
  15158. if (uv2s) {
  15159. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  15160. }
  15161. var colors = parsedVertexData.colors;
  15162. if (colors) {
  15163. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  15164. }
  15165. var matricesIndices = parsedVertexData.matricesIndices;
  15166. if (matricesIndices) {
  15167. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  15168. }
  15169. var matricesWeights = parsedVertexData.matricesWeights;
  15170. if (matricesWeights) {
  15171. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  15172. }
  15173. var indices = parsedVertexData.indices;
  15174. if (indices) {
  15175. vertexData.indices = indices;
  15176. }
  15177. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  15178. };
  15179. var importGeometry = function (parsedGeometry, mesh) {
  15180. var scene = mesh.getScene();
  15181. var geometryId = parsedGeometry.geometryId;
  15182. if (geometryId) {
  15183. var geometry = scene.getGeometryByID(geometryId);
  15184. if (geometry) {
  15185. geometry.applyToMesh(mesh);
  15186. }
  15187. } else if (parsedGeometry instanceof ArrayBuffer) {
  15188. var binaryInfo = mesh._binaryInfo;
  15189. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  15190. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  15191. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  15192. }
  15193. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  15194. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  15195. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  15196. }
  15197. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  15198. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  15199. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  15200. }
  15201. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  15202. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  15203. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  15204. }
  15205. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  15206. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  15207. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  15208. }
  15209. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  15210. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  15211. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  15212. }
  15213. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  15214. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  15215. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  15216. }
  15217. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  15218. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  15219. mesh.setIndices(indicesData);
  15220. }
  15221. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  15222. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  15223. mesh.subMeshes = [];
  15224. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  15225. var materialIndex = subMeshesData[(i * 5) + 0];
  15226. var verticesStart = subMeshesData[(i * 5) + 1];
  15227. var verticesCount = subMeshesData[(i * 5) + 2];
  15228. var indexStart = subMeshesData[(i * 5) + 3];
  15229. var indexCount = subMeshesData[(i * 5) + 4];
  15230. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  15231. }
  15232. }
  15233. return;
  15234. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  15235. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  15236. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  15237. if (parsedGeometry.uvs) {
  15238. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  15239. }
  15240. if (parsedGeometry.uvs2) {
  15241. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  15242. }
  15243. if (parsedGeometry.colors) {
  15244. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, parsedGeometry.colors, false);
  15245. }
  15246. if (parsedGeometry.matricesIndices) {
  15247. if (!parsedGeometry.matricesIndices._isExpanded) {
  15248. var floatIndices = [];
  15249. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  15250. var matricesIndex = parsedGeometry.matricesIndices[i];
  15251. floatIndices.push(matricesIndex & 0x000000FF);
  15252. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  15253. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  15254. floatIndices.push(matricesIndex >> 24);
  15255. }
  15256. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  15257. } else {
  15258. delete parsedGeometry.matricesIndices._isExpanded;
  15259. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  15260. }
  15261. }
  15262. if (parsedGeometry.matricesWeights) {
  15263. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  15264. }
  15265. mesh.setIndices(parsedGeometry.indices);
  15266. }
  15267. if (parsedGeometry.subMeshes) {
  15268. mesh.subMeshes = [];
  15269. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  15270. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  15271. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  15272. }
  15273. }
  15274. if (mesh._shouldGenerateFlatShading) {
  15275. mesh.convertToFlatShadedMesh();
  15276. delete mesh._shouldGenerateFlatShading;
  15277. }
  15278. mesh.computeWorldMatrix(true);
  15279. if (scene._selectionOctree) {
  15280. scene._selectionOctree.addMesh(mesh);
  15281. }
  15282. };
  15283. BABYLON.SceneLoader.RegisterPlugin({
  15284. extensions: ".babylon",
  15285. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  15286. var parsedData = JSON.parse(data);
  15287. var loadedSkeletonsIds = [];
  15288. var loadedMaterialsIds = [];
  15289. var hierarchyIds = [];
  15290. for (var index = 0; index < parsedData.meshes.length; index++) {
  15291. var parsedMesh = parsedData.meshes[index];
  15292. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  15293. if (meshesNames instanceof Array) {
  15294. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  15295. }
  15296. if (parsedMesh.materialId) {
  15297. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  15298. if (!materialFound) {
  15299. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  15300. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  15301. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  15302. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  15303. var subMatId = parsedMultiMaterial.materials[matIndex];
  15304. loadedMaterialsIds.push(subMatId);
  15305. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  15306. }
  15307. loadedMaterialsIds.push(parsedMultiMaterial.id);
  15308. parseMultiMaterial(parsedMultiMaterial, scene);
  15309. materialFound = true;
  15310. break;
  15311. }
  15312. }
  15313. }
  15314. if (!materialFound) {
  15315. loadedMaterialsIds.push(parsedMesh.materialId);
  15316. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  15317. }
  15318. }
  15319. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  15320. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  15321. if (!skeletonAlreadyLoaded) {
  15322. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  15323. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  15324. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  15325. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  15326. loadedSkeletonsIds.push(parsedSkeleton.id);
  15327. }
  15328. }
  15329. }
  15330. }
  15331. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  15332. meshes.push(mesh);
  15333. }
  15334. }
  15335. for (index = 0; index < scene.meshes.length; index++) {
  15336. var currentMesh = scene.meshes[index];
  15337. if (currentMesh._waitingParentId) {
  15338. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  15339. currentMesh._waitingParentId = undefined;
  15340. }
  15341. }
  15342. if (parsedData.particleSystems) {
  15343. for (index = 0; index < parsedData.particleSystems.length; index++) {
  15344. var parsedParticleSystem = parsedData.particleSystems[index];
  15345. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  15346. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  15347. }
  15348. }
  15349. }
  15350. return true;
  15351. },
  15352. load: function (scene, data, rootUrl) {
  15353. var parsedData = JSON.parse(data);
  15354. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  15355. scene.autoClear = parsedData.autoClear;
  15356. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  15357. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  15358. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  15359. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  15360. scene.fogMode = parsedData.fogMode;
  15361. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  15362. scene.fogStart = parsedData.fogStart;
  15363. scene.fogEnd = parsedData.fogEnd;
  15364. scene.fogDensity = parsedData.fogDensity;
  15365. }
  15366. for (var index = 0; index < parsedData.lights.length; index++) {
  15367. var parsedLight = parsedData.lights[index];
  15368. parseLight(parsedLight, scene);
  15369. }
  15370. if (parsedData.materials) {
  15371. for (index = 0; index < parsedData.materials.length; index++) {
  15372. var parsedMaterial = parsedData.materials[index];
  15373. parseMaterial(parsedMaterial, scene, rootUrl);
  15374. }
  15375. }
  15376. if (parsedData.multiMaterials) {
  15377. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  15378. var parsedMultiMaterial = parsedData.multiMaterials[index];
  15379. parseMultiMaterial(parsedMultiMaterial, scene);
  15380. }
  15381. }
  15382. if (parsedData.skeletons) {
  15383. for (index = 0; index < parsedData.skeletons.length; index++) {
  15384. var parsedSkeleton = parsedData.skeletons[index];
  15385. parseSkeleton(parsedSkeleton, scene);
  15386. }
  15387. }
  15388. var geometries = parsedData.geometries;
  15389. if (geometries) {
  15390. var boxes = geometries.boxes;
  15391. if (boxes) {
  15392. for (index = 0; index < boxes.length; index++) {
  15393. var parsedBox = boxes[index];
  15394. parseBox(parsedBox, scene);
  15395. }
  15396. }
  15397. var spheres = geometries.spheres;
  15398. if (spheres) {
  15399. for (index = 0; index < spheres.length; index++) {
  15400. var parsedSphere = spheres[index];
  15401. parseSphere(parsedSphere, scene);
  15402. }
  15403. }
  15404. var cylinders = geometries.cylinders;
  15405. if (cylinders) {
  15406. for (index = 0; index < cylinders.length; index++) {
  15407. var parsedCylinder = cylinders[index];
  15408. parseCylinder(parsedCylinder, scene);
  15409. }
  15410. }
  15411. var toruses = geometries.toruses;
  15412. if (toruses) {
  15413. for (index = 0; index < toruses.length; index++) {
  15414. var parsedTorus = toruses[index];
  15415. parseTorus(parsedTorus, scene);
  15416. }
  15417. }
  15418. var grounds = geometries.grounds;
  15419. if (grounds) {
  15420. for (index = 0; index < grounds.length; index++) {
  15421. var parsedGround = grounds[index];
  15422. parseGround(parsedGround, scene);
  15423. }
  15424. }
  15425. var planes = geometries.planes;
  15426. if (planes) {
  15427. for (index = 0; index < planes.length; index++) {
  15428. var parsedPlane = planes[index];
  15429. parsePlane(parsedPlane, scene);
  15430. }
  15431. }
  15432. var torusKnots = geometries.torusKnots;
  15433. if (torusKnots) {
  15434. for (index = 0; index < torusKnots.length; index++) {
  15435. var parsedTorusKnot = torusKnots[index];
  15436. parseTorusKnot(parsedTorusKnot, scene);
  15437. }
  15438. }
  15439. var vertexData = geometries.vertexData;
  15440. if (vertexData) {
  15441. for (index = 0; index < vertexData.length; index++) {
  15442. var parsedVertexData = vertexData[index];
  15443. parseVertexData(parsedVertexData, scene, rootUrl);
  15444. }
  15445. }
  15446. }
  15447. for (index = 0; index < parsedData.meshes.length; index++) {
  15448. var parsedMesh = parsedData.meshes[index];
  15449. parseMesh(parsedMesh, scene, rootUrl);
  15450. }
  15451. for (index = 0; index < parsedData.cameras.length; index++) {
  15452. var parsedCamera = parsedData.cameras[index];
  15453. parseCamera(parsedCamera, scene);
  15454. }
  15455. if (parsedData.activeCameraID) {
  15456. scene.setActiveCameraByID(parsedData.activeCameraID);
  15457. }
  15458. for (index = 0; index < scene.cameras.length; index++) {
  15459. var camera = scene.cameras[index];
  15460. if (camera._waitingParentId) {
  15461. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  15462. camera._waitingParentId = undefined;
  15463. }
  15464. }
  15465. for (index = 0; index < scene.meshes.length; index++) {
  15466. var mesh = scene.meshes[index];
  15467. if (mesh._waitingParentId) {
  15468. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  15469. mesh._waitingParentId = undefined;
  15470. }
  15471. }
  15472. if (parsedData.particleSystems) {
  15473. for (index = 0; index < parsedData.particleSystems.length; index++) {
  15474. var parsedParticleSystem = parsedData.particleSystems[index];
  15475. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  15476. }
  15477. }
  15478. if (parsedData.lensFlareSystems) {
  15479. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  15480. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  15481. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  15482. }
  15483. }
  15484. if (parsedData.shadowGenerators) {
  15485. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  15486. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  15487. parseShadowGenerator(parsedShadowGenerator, scene);
  15488. }
  15489. }
  15490. return true;
  15491. }
  15492. });
  15493. })(BABYLON.Internals || (BABYLON.Internals = {}));
  15494. var Internals = BABYLON.Internals;
  15495. })(BABYLON || (BABYLON = {}));
  15496. var BABYLON;
  15497. (function (BABYLON) {
  15498. var currentCSGMeshId = 0;
  15499. var Vertex = (function () {
  15500. function Vertex(pos, normal, uv) {
  15501. this.pos = pos;
  15502. this.normal = normal;
  15503. this.uv = uv;
  15504. }
  15505. Vertex.prototype.clone = function () {
  15506. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  15507. };
  15508. Vertex.prototype.flip = function () {
  15509. this.normal = this.normal.scale(-1);
  15510. };
  15511. Vertex.prototype.interpolate = function (other, t) {
  15512. 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));
  15513. };
  15514. return Vertex;
  15515. })();
  15516. var Plane = (function () {
  15517. function Plane(normal, w) {
  15518. this.normal = normal;
  15519. this.w = w;
  15520. }
  15521. Plane.FromPoints = function (a, b, c) {
  15522. var v0 = c.subtract(a);
  15523. var v1 = b.subtract(a);
  15524. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  15525. return null;
  15526. }
  15527. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  15528. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  15529. };
  15530. Plane.prototype.clone = function () {
  15531. return new Plane(this.normal.clone(), this.w);
  15532. };
  15533. Plane.prototype.flip = function () {
  15534. this.normal.scaleInPlace(-1);
  15535. this.w = -this.w;
  15536. };
  15537. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  15538. var COPLANAR = 0;
  15539. var FRONT = 1;
  15540. var BACK = 2;
  15541. var SPANNING = 3;
  15542. var polygonType = 0;
  15543. var types = [];
  15544. for (var i = 0; i < polygon.vertices.length; i++) {
  15545. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  15546. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  15547. polygonType |= type;
  15548. types.push(type);
  15549. }
  15550. switch (polygonType) {
  15551. case COPLANAR:
  15552. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  15553. break;
  15554. case FRONT:
  15555. front.push(polygon);
  15556. break;
  15557. case BACK:
  15558. back.push(polygon);
  15559. break;
  15560. case SPANNING:
  15561. var f = [], b = [];
  15562. for (i = 0; i < polygon.vertices.length; i++) {
  15563. var j = (i + 1) % polygon.vertices.length;
  15564. var ti = types[i], tj = types[j];
  15565. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  15566. if (ti != BACK)
  15567. f.push(vi);
  15568. if (ti != FRONT)
  15569. b.push(ti != BACK ? vi.clone() : vi);
  15570. if ((ti | tj) == SPANNING) {
  15571. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  15572. var v = vi.interpolate(vj, t);
  15573. f.push(v);
  15574. b.push(v.clone());
  15575. }
  15576. }
  15577. if (f.length >= 3) {
  15578. var poly = new Polygon(f, polygon.shared);
  15579. if (poly.plane)
  15580. front.push(poly);
  15581. }
  15582. if (b.length >= 3) {
  15583. poly = new Polygon(b, polygon.shared);
  15584. if (poly.plane)
  15585. back.push(poly);
  15586. }
  15587. break;
  15588. }
  15589. };
  15590. Plane.EPSILON = 1e-5;
  15591. return Plane;
  15592. })();
  15593. var Polygon = (function () {
  15594. function Polygon(vertices, shared) {
  15595. this.vertices = vertices;
  15596. this.shared = shared;
  15597. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  15598. }
  15599. Polygon.prototype.clone = function () {
  15600. var vertices = this.vertices.map(function (v) {
  15601. return v.clone();
  15602. });
  15603. return new Polygon(vertices, this.shared);
  15604. };
  15605. Polygon.prototype.flip = function () {
  15606. this.vertices.reverse().map(function (v) {
  15607. v.flip();
  15608. });
  15609. this.plane.flip();
  15610. };
  15611. return Polygon;
  15612. })();
  15613. var Node = (function () {
  15614. function Node(polygons) {
  15615. this.plane = null;
  15616. this.front = null;
  15617. this.back = null;
  15618. this.polygons = [];
  15619. if (polygons) {
  15620. this.build(polygons);
  15621. }
  15622. }
  15623. Node.prototype.clone = function () {
  15624. var node = new Node();
  15625. node.plane = this.plane && this.plane.clone();
  15626. node.front = this.front && this.front.clone();
  15627. node.back = this.back && this.back.clone();
  15628. node.polygons = this.polygons.map(function (p) {
  15629. return p.clone();
  15630. });
  15631. return node;
  15632. };
  15633. Node.prototype.invert = function () {
  15634. for (var i = 0; i < this.polygons.length; i++) {
  15635. this.polygons[i].flip();
  15636. }
  15637. if (this.plane) {
  15638. this.plane.flip();
  15639. }
  15640. if (this.front) {
  15641. this.front.invert();
  15642. }
  15643. if (this.back) {
  15644. this.back.invert();
  15645. }
  15646. var temp = this.front;
  15647. this.front = this.back;
  15648. this.back = temp;
  15649. };
  15650. Node.prototype.clipPolygons = function (polygons) {
  15651. if (!this.plane)
  15652. return polygons.slice();
  15653. var front = [], back = [];
  15654. for (var i = 0; i < polygons.length; i++) {
  15655. this.plane.splitPolygon(polygons[i], front, back, front, back);
  15656. }
  15657. if (this.front) {
  15658. front = this.front.clipPolygons(front);
  15659. }
  15660. if (this.back) {
  15661. back = this.back.clipPolygons(back);
  15662. } else {
  15663. back = [];
  15664. }
  15665. return front.concat(back);
  15666. };
  15667. Node.prototype.clipTo = function (bsp) {
  15668. this.polygons = bsp.clipPolygons(this.polygons);
  15669. if (this.front)
  15670. this.front.clipTo(bsp);
  15671. if (this.back)
  15672. this.back.clipTo(bsp);
  15673. };
  15674. Node.prototype.allPolygons = function () {
  15675. var polygons = this.polygons.slice();
  15676. if (this.front)
  15677. polygons = polygons.concat(this.front.allPolygons());
  15678. if (this.back)
  15679. polygons = polygons.concat(this.back.allPolygons());
  15680. return polygons;
  15681. };
  15682. Node.prototype.build = function (polygons) {
  15683. if (!polygons.length)
  15684. return;
  15685. if (!this.plane)
  15686. this.plane = polygons[0].plane.clone();
  15687. var front = [], back = [];
  15688. for (var i = 0; i < polygons.length; i++) {
  15689. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  15690. }
  15691. if (front.length) {
  15692. if (!this.front)
  15693. this.front = new Node();
  15694. this.front.build(front);
  15695. }
  15696. if (back.length) {
  15697. if (!this.back)
  15698. this.back = new Node();
  15699. this.back.build(back);
  15700. }
  15701. };
  15702. return Node;
  15703. })();
  15704. var CSG = (function () {
  15705. function CSG() {
  15706. this.polygons = new Array();
  15707. }
  15708. CSG.FromMesh = function (mesh) {
  15709. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  15710. if (mesh instanceof BABYLON.Mesh) {
  15711. mesh.computeWorldMatrix(true);
  15712. var matrix = mesh.getWorldMatrix();
  15713. var meshPosition = mesh.position.clone();
  15714. var meshRotation = mesh.rotation.clone();
  15715. var meshScaling = mesh.scaling.clone();
  15716. } else {
  15717. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  15718. }
  15719. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15720. var subMeshes = mesh.subMeshes;
  15721. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  15722. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  15723. vertices = [];
  15724. for (var j = 0; j < 3; j++) {
  15725. normal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  15726. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  15727. position = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  15728. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, position);
  15729. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15730. vertex = new Vertex(position, normal, uv);
  15731. vertices.push(vertex);
  15732. }
  15733. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  15734. if (polygon.plane)
  15735. polygons.push(polygon);
  15736. }
  15737. }
  15738. var csg = CSG.FromPolygons(polygons);
  15739. csg.matrix = matrix;
  15740. csg.position = meshPosition;
  15741. csg.rotation = meshRotation;
  15742. csg.scaling = meshScaling;
  15743. currentCSGMeshId++;
  15744. return csg;
  15745. };
  15746. CSG.FromPolygons = function (polygons) {
  15747. var csg = new BABYLON.CSG();
  15748. csg.polygons = polygons;
  15749. return csg;
  15750. };
  15751. CSG.prototype.clone = function () {
  15752. var csg = new BABYLON.CSG();
  15753. csg.polygons = this.polygons.map(function (p) {
  15754. return p.clone();
  15755. });
  15756. csg.copyTransformAttributes(this);
  15757. return csg;
  15758. };
  15759. CSG.prototype.toPolygons = function () {
  15760. return this.polygons;
  15761. };
  15762. CSG.prototype.union = function (csg) {
  15763. var a = new Node(this.clone().polygons);
  15764. var b = new Node(csg.clone().polygons);
  15765. a.clipTo(b);
  15766. b.clipTo(a);
  15767. b.invert();
  15768. b.clipTo(a);
  15769. b.invert();
  15770. a.build(b.allPolygons());
  15771. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15772. };
  15773. CSG.prototype.unionInPlace = function (csg) {
  15774. var a = new Node(this.polygons);
  15775. var b = new Node(csg.polygons);
  15776. a.clipTo(b);
  15777. b.clipTo(a);
  15778. b.invert();
  15779. b.clipTo(a);
  15780. b.invert();
  15781. a.build(b.allPolygons());
  15782. this.polygons = a.allPolygons();
  15783. };
  15784. CSG.prototype.subtract = function (csg) {
  15785. var a = new Node(this.clone().polygons);
  15786. var b = new Node(csg.clone().polygons);
  15787. a.invert();
  15788. a.clipTo(b);
  15789. b.clipTo(a);
  15790. b.invert();
  15791. b.clipTo(a);
  15792. b.invert();
  15793. a.build(b.allPolygons());
  15794. a.invert();
  15795. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15796. };
  15797. CSG.prototype.subtractInPlace = function (csg) {
  15798. var a = new Node(this.polygons);
  15799. var b = new Node(csg.polygons);
  15800. a.invert();
  15801. a.clipTo(b);
  15802. b.clipTo(a);
  15803. b.invert();
  15804. b.clipTo(a);
  15805. b.invert();
  15806. a.build(b.allPolygons());
  15807. a.invert();
  15808. this.polygons = a.allPolygons();
  15809. };
  15810. CSG.prototype.intersect = function (csg) {
  15811. var a = new Node(this.clone().polygons);
  15812. var b = new Node(csg.clone().polygons);
  15813. a.invert();
  15814. b.clipTo(a);
  15815. b.invert();
  15816. a.clipTo(b);
  15817. b.clipTo(a);
  15818. a.build(b.allPolygons());
  15819. a.invert();
  15820. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15821. };
  15822. CSG.prototype.intersectInPlace = function (csg) {
  15823. var a = new Node(this.polygons);
  15824. var b = new Node(csg.polygons);
  15825. a.invert();
  15826. b.clipTo(a);
  15827. b.invert();
  15828. a.clipTo(b);
  15829. b.clipTo(a);
  15830. a.build(b.allPolygons());
  15831. a.invert();
  15832. this.polygons = a.allPolygons();
  15833. };
  15834. CSG.prototype.inverse = function () {
  15835. var csg = this.clone();
  15836. csg.inverseInPlace();
  15837. return csg;
  15838. };
  15839. CSG.prototype.inverseInPlace = function () {
  15840. this.polygons.map(function (p) {
  15841. p.flip();
  15842. });
  15843. };
  15844. CSG.prototype.copyTransformAttributes = function (csg) {
  15845. this.matrix = csg.matrix;
  15846. this.position = csg.position;
  15847. this.rotation = csg.rotation;
  15848. this.scaling = csg.scaling;
  15849. return this;
  15850. };
  15851. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  15852. var matrix = this.matrix.clone();
  15853. matrix.invert();
  15854. 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;
  15855. if (keepSubMeshes) {
  15856. polygons.sort(function (a, b) {
  15857. if (a.shared.meshId === b.shared.meshId) {
  15858. return a.shared.subMeshId - b.shared.subMeshId;
  15859. } else {
  15860. return a.shared.meshId - b.shared.meshId;
  15861. }
  15862. });
  15863. }
  15864. for (var i = 0, il = polygons.length; i < il; i++) {
  15865. polygon = polygons[i];
  15866. if (!subMesh_dict[polygon.shared.meshId]) {
  15867. subMesh_dict[polygon.shared.meshId] = {};
  15868. }
  15869. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  15870. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  15871. indexStart: +Infinity,
  15872. indexEnd: -Infinity,
  15873. materialIndex: polygon.shared.materialIndex
  15874. };
  15875. }
  15876. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  15877. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  15878. polygonIndices[0] = 0;
  15879. polygonIndices[1] = j - 1;
  15880. polygonIndices[2] = j;
  15881. for (var k = 0; k < 3; k++) {
  15882. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  15883. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  15884. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  15885. BABYLON.Vector3.TransformCoordinatesToRef(vertex, matrix, vertex);
  15886. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15887. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z];
  15888. 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)) {
  15889. vertices.push(vertex.x, vertex.y, vertex.z);
  15890. uvs.push(uv.x, uv.y);
  15891. normals.push(normal.x, normal.y, normal.z);
  15892. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z] = (vertices.length / 3) - 1;
  15893. }
  15894. indices.push(vertex_idx);
  15895. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  15896. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  15897. currentIndex++;
  15898. }
  15899. }
  15900. }
  15901. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  15902. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15903. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  15904. mesh.setIndices(indices);
  15905. if (keepSubMeshes) {
  15906. var materialIndexOffset = 0, materialMaxIndex;
  15907. mesh.subMeshes.length = 0;
  15908. for (var m in subMesh_dict) {
  15909. materialMaxIndex = -1;
  15910. for (var sm in subMesh_dict[m]) {
  15911. subMesh_obj = subMesh_dict[m][sm];
  15912. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  15913. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  15914. }
  15915. materialIndexOffset += ++materialMaxIndex;
  15916. }
  15917. }
  15918. return mesh;
  15919. };
  15920. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  15921. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  15922. mesh.material = material;
  15923. mesh.position.copyFrom(this.position);
  15924. mesh.rotation.copyFrom(this.rotation);
  15925. mesh.scaling.copyFrom(this.scaling);
  15926. mesh.computeWorldMatrix(true);
  15927. return mesh;
  15928. };
  15929. return CSG;
  15930. })();
  15931. BABYLON.CSG = CSG;
  15932. })(BABYLON || (BABYLON = {}));
  15933. var __extends = this.__extends || function (d, b) {
  15934. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15935. function __() { this.constructor = d; }
  15936. __.prototype = b.prototype;
  15937. d.prototype = new __();
  15938. };
  15939. var BABYLON;
  15940. (function (BABYLON) {
  15941. var OculusDistortionCorrectionPostProcess = (function (_super) {
  15942. __extends(OculusDistortionCorrectionPostProcess, _super);
  15943. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  15944. var _this = this;
  15945. _super.call(this, name, "oculusDistortionCorrection", [
  15946. 'LensCenter',
  15947. 'Scale',
  15948. 'ScaleIn',
  15949. 'HmdWarpParam'
  15950. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  15951. this._isRightEye = isRightEye;
  15952. this._distortionFactors = cameraSettings.DistortionK;
  15953. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  15954. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  15955. this.onSizeChanged = function () {
  15956. _this.aspectRatio = _this.width * .5 / _this.height;
  15957. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  15958. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  15959. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  15960. };
  15961. this.onApply = function (effect) {
  15962. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  15963. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  15964. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  15965. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  15966. };
  15967. }
  15968. return OculusDistortionCorrectionPostProcess;
  15969. })(BABYLON.PostProcess);
  15970. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  15971. })(BABYLON || (BABYLON = {}));
  15972. var BABYLON;
  15973. (function (BABYLON) {
  15974. (function (JoystickAxis) {
  15975. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  15976. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  15977. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  15978. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  15979. var JoystickAxis = BABYLON.JoystickAxis;
  15980. var VirtualJoystick = (function () {
  15981. function VirtualJoystick(leftJoystick) {
  15982. var _this = this;
  15983. if (leftJoystick) {
  15984. this._leftJoystick = true;
  15985. } else {
  15986. this._leftJoystick = false;
  15987. }
  15988. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  15989. VirtualJoystick._globalJoystickIndex++;
  15990. this._axisTargetedByLeftAndRight = 0 /* X */;
  15991. this._axisTargetedByUpAndDown = 1 /* Y */;
  15992. this.reverseLeftRight = false;
  15993. this.reverseUpDown = false;
  15994. this._touches = new BABYLON.VirtualJoystick.Collection();
  15995. this.deltaPosition = BABYLON.Vector3.Zero();
  15996. this._joystickSensibility = 25;
  15997. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  15998. this._rotationSpeed = 25;
  15999. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  16000. this._rotateOnAxisRelativeToMesh = false;
  16001. if (!VirtualJoystick.vjCanvas) {
  16002. window.addEventListener("resize", function () {
  16003. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  16004. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  16005. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  16006. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  16007. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  16008. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  16009. }, false);
  16010. VirtualJoystick.vjCanvas = document.createElement("canvas");
  16011. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  16012. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  16013. VirtualJoystick.vjCanvas.width = window.innerWidth;
  16014. VirtualJoystick.vjCanvas.height = window.innerHeight;
  16015. VirtualJoystick.vjCanvas.style.width = "100%";
  16016. VirtualJoystick.vjCanvas.style.height = "100%";
  16017. VirtualJoystick.vjCanvas.style.position = "absolute";
  16018. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  16019. VirtualJoystick.vjCanvas.style.top = "0px";
  16020. VirtualJoystick.vjCanvas.style.left = "0px";
  16021. VirtualJoystick.vjCanvas.style.zIndex = "5";
  16022. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  16023. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  16024. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  16025. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  16026. document.body.appendChild(VirtualJoystick.vjCanvas);
  16027. }
  16028. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  16029. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  16030. this.pressed = false;
  16031. this._joystickColor = "cyan";
  16032. this._joystickPointerID = -1;
  16033. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  16034. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  16035. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  16036. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  16037. _this._onPointerDown(evt);
  16038. }, false);
  16039. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  16040. _this._onPointerMove(evt);
  16041. }, false);
  16042. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  16043. _this._onPointerUp(evt);
  16044. }, false);
  16045. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  16046. _this._onPointerUp(evt);
  16047. }, false);
  16048. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  16049. evt.preventDefault();
  16050. }, false);
  16051. requestAnimationFrame(function () {
  16052. _this._drawVirtualJoystick();
  16053. });
  16054. }
  16055. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  16056. this._joystickSensibility = newJoystickSensibility;
  16057. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  16058. };
  16059. VirtualJoystick.prototype._onPointerDown = function (e) {
  16060. var positionOnScreenCondition;
  16061. e.preventDefault();
  16062. if (this._leftJoystick === true) {
  16063. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  16064. } else {
  16065. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  16066. }
  16067. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  16068. this._joystickPointerID = e.pointerId;
  16069. this._joystickPointerStartPos.x = e.clientX;
  16070. this._joystickPointerStartPos.y = e.clientY;
  16071. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  16072. this._deltaJoystickVector.x = 0;
  16073. this._deltaJoystickVector.y = 0;
  16074. this.pressed = true;
  16075. this._touches.add(e.pointerId.toString(), e);
  16076. } else {
  16077. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  16078. this._action();
  16079. this._touches.add(e.pointerId.toString(), e);
  16080. }
  16081. }
  16082. };
  16083. VirtualJoystick.prototype._onPointerMove = function (e) {
  16084. if (this._joystickPointerID == e.pointerId) {
  16085. this._joystickPointerPos.x = e.clientX;
  16086. this._joystickPointerPos.y = e.clientY;
  16087. this._deltaJoystickVector = this._joystickPointerPos.clone();
  16088. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  16089. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  16090. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  16091. switch (this._axisTargetedByLeftAndRight) {
  16092. case 0 /* X */:
  16093. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  16094. break;
  16095. case 1 /* Y */:
  16096. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  16097. break;
  16098. case 2 /* Z */:
  16099. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  16100. break;
  16101. }
  16102. var directionUpDown = this.reverseUpDown ? 1 : -1;
  16103. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  16104. switch (this._axisTargetedByUpAndDown) {
  16105. case 0 /* X */:
  16106. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  16107. break;
  16108. case 1 /* Y */:
  16109. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  16110. break;
  16111. case 2 /* Z */:
  16112. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  16113. break;
  16114. }
  16115. } else {
  16116. if (this._touches.item(e.pointerId.toString())) {
  16117. this._touches.item(e.pointerId.toString()).x = e.clientX;
  16118. this._touches.item(e.pointerId.toString()).y = e.clientY;
  16119. }
  16120. }
  16121. };
  16122. VirtualJoystick.prototype._onPointerUp = function (e) {
  16123. this._clearCanvas();
  16124. if (this._joystickPointerID == e.pointerId) {
  16125. this._joystickPointerID = -1;
  16126. this.pressed = false;
  16127. }
  16128. this._deltaJoystickVector.x = 0;
  16129. this._deltaJoystickVector.y = 0;
  16130. this._touches.remove(e.pointerId.toString());
  16131. };
  16132. /**
  16133. * Change the color of the virtual joystick
  16134. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  16135. */
  16136. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  16137. this._joystickColor = newColor;
  16138. };
  16139. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  16140. this._action = action;
  16141. };
  16142. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  16143. switch (axis) {
  16144. case 0 /* X */:
  16145. case 1 /* Y */:
  16146. case 2 /* Z */:
  16147. this._axisTargetedByLeftAndRight = axis;
  16148. break;
  16149. default:
  16150. this._axisTargetedByLeftAndRight = 0 /* X */;
  16151. break;
  16152. }
  16153. };
  16154. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  16155. switch (axis) {
  16156. case 0 /* X */:
  16157. case 1 /* Y */:
  16158. case 2 /* Z */:
  16159. this._axisTargetedByUpAndDown = axis;
  16160. break;
  16161. default:
  16162. this._axisTargetedByUpAndDown = 1 /* Y */;
  16163. break;
  16164. }
  16165. };
  16166. VirtualJoystick.prototype._clearCanvas = function () {
  16167. if (this._leftJoystick) {
  16168. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  16169. } else {
  16170. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  16171. }
  16172. };
  16173. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  16174. var _this = this;
  16175. if (this.pressed) {
  16176. this._clearCanvas();
  16177. this._touches.forEach(function (touch) {
  16178. if (touch.pointerId === _this._joystickPointerID) {
  16179. VirtualJoystick.vjCanvasContext.beginPath();
  16180. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16181. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  16182. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  16183. VirtualJoystick.vjCanvasContext.stroke();
  16184. VirtualJoystick.vjCanvasContext.beginPath();
  16185. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16186. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  16187. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  16188. VirtualJoystick.vjCanvasContext.stroke();
  16189. VirtualJoystick.vjCanvasContext.beginPath();
  16190. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16191. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  16192. VirtualJoystick.vjCanvasContext.stroke();
  16193. } else {
  16194. VirtualJoystick.vjCanvasContext.beginPath();
  16195. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  16196. VirtualJoystick.vjCanvasContext.beginPath();
  16197. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  16198. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  16199. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  16200. VirtualJoystick.vjCanvasContext.stroke();
  16201. }
  16202. ;
  16203. });
  16204. }
  16205. requestAnimationFrame(function () {
  16206. _this._drawVirtualJoystick();
  16207. });
  16208. };
  16209. VirtualJoystick.prototype.releaseCanvas = function () {
  16210. if (VirtualJoystick.vjCanvas) {
  16211. document.body.removeChild(VirtualJoystick.vjCanvas);
  16212. VirtualJoystick.vjCanvas = null;
  16213. }
  16214. };
  16215. VirtualJoystick._globalJoystickIndex = 0;
  16216. return VirtualJoystick;
  16217. })();
  16218. BABYLON.VirtualJoystick = VirtualJoystick;
  16219. })(BABYLON || (BABYLON = {}));
  16220. var BABYLON;
  16221. (function (BABYLON) {
  16222. (function (VirtualJoystick) {
  16223. var Collection = (function () {
  16224. function Collection() {
  16225. this._count = 0;
  16226. this._collection = new Array();
  16227. }
  16228. Collection.prototype.Count = function () {
  16229. return this._count;
  16230. };
  16231. Collection.prototype.add = function (key, item) {
  16232. if (this._collection[key] != undefined) {
  16233. return undefined;
  16234. }
  16235. this._collection[key] = item;
  16236. return ++this._count;
  16237. };
  16238. Collection.prototype.remove = function (key) {
  16239. if (this._collection[key] == undefined) {
  16240. return undefined;
  16241. }
  16242. delete this._collection[key];
  16243. return --this._count;
  16244. };
  16245. Collection.prototype.item = function (key) {
  16246. return this._collection[key];
  16247. };
  16248. Collection.prototype.forEach = function (block) {
  16249. var key;
  16250. for (key in this._collection) {
  16251. if (this._collection.hasOwnProperty(key)) {
  16252. block(this._collection[key]);
  16253. }
  16254. }
  16255. };
  16256. return Collection;
  16257. })();
  16258. VirtualJoystick.Collection = Collection;
  16259. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  16260. var VirtualJoystick = BABYLON.VirtualJoystick;
  16261. })(BABYLON || (BABYLON = {}));
  16262. var __extends = this.__extends || function (d, b) {
  16263. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16264. function __() { this.constructor = d; }
  16265. __.prototype = b.prototype;
  16266. d.prototype = new __();
  16267. };
  16268. var BABYLON;
  16269. (function (BABYLON) {
  16270. var OculusRiftDevKit2013_Metric = {
  16271. HResolution: 1280,
  16272. VResolution: 800,
  16273. HScreenSize: 0.149759993,
  16274. VScreenSize: 0.0935999975,
  16275. VScreenCenter: 0.0467999987,
  16276. EyeToScreenDistance: 0.0410000011,
  16277. LensSeparationDistance: 0.0635000020,
  16278. InterpupillaryDistance: 0.0640000030,
  16279. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  16280. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  16281. PostProcessScaleFactor: 1.714605507808412,
  16282. LensCenterOffset: 0.151976421
  16283. };
  16284. var _OculusInnerCamera = (function (_super) {
  16285. __extends(_OculusInnerCamera, _super);
  16286. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  16287. _super.call(this, name, position, scene);
  16288. this._workMatrix = new BABYLON.Matrix();
  16289. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  16290. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  16291. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  16292. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  16293. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  16294. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  16295. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  16296. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  16297. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  16298. }
  16299. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  16300. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  16301. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  16302. return this._projectionMatrix;
  16303. };
  16304. _OculusInnerCamera.prototype._getViewMatrix = function () {
  16305. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  16306. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  16307. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  16308. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  16309. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  16310. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  16311. return this._viewMatrix;
  16312. };
  16313. return _OculusInnerCamera;
  16314. })(BABYLON.FreeCamera);
  16315. var OculusCamera = (function (_super) {
  16316. __extends(OculusCamera, _super);
  16317. function OculusCamera(name, position, scene) {
  16318. _super.call(this, name, position, scene);
  16319. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  16320. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  16321. this.subCameras.push(this._leftCamera);
  16322. this.subCameras.push(this._rightCamera);
  16323. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  16324. }
  16325. OculusCamera.prototype._update = function () {
  16326. this._leftCamera.position.copyFrom(this.position);
  16327. this._rightCamera.position.copyFrom(this.position);
  16328. this._updateCamera(this._leftCamera);
  16329. this._updateCamera(this._rightCamera);
  16330. _super.prototype._update.call(this);
  16331. };
  16332. OculusCamera.prototype._updateCamera = function (camera) {
  16333. camera.minZ = this.minZ;
  16334. camera.maxZ = this.maxZ;
  16335. camera.rotation.x = this.rotation.x;
  16336. camera.rotation.y = this.rotation.y;
  16337. camera.rotation.z = this.rotation.z;
  16338. };
  16339. OculusCamera.prototype._onOrientationEvent = function (evt) {
  16340. var yaw = evt.alpha / 180 * Math.PI;
  16341. var pitch = evt.beta / 180 * Math.PI;
  16342. var roll = evt.gamma / 180 * Math.PI;
  16343. if (!this._offsetOrientation) {
  16344. this._offsetOrientation = {
  16345. yaw: yaw,
  16346. pitch: pitch,
  16347. roll: roll
  16348. };
  16349. return;
  16350. } else {
  16351. this.rotation.y += yaw - this._offsetOrientation.yaw;
  16352. this.rotation.x += pitch - this._offsetOrientation.pitch;
  16353. this.rotation.z += this._offsetOrientation.roll - roll;
  16354. this._offsetOrientation.yaw = yaw;
  16355. this._offsetOrientation.pitch = pitch;
  16356. this._offsetOrientation.roll = roll;
  16357. }
  16358. };
  16359. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  16360. _super.prototype.attachControl.call(this, element, noPreventDefault);
  16361. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  16362. };
  16363. OculusCamera.prototype.detachControl = function (element) {
  16364. _super.prototype.detachControl.call(this, element);
  16365. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  16366. };
  16367. return OculusCamera;
  16368. })(BABYLON.FreeCamera);
  16369. BABYLON.OculusCamera = OculusCamera;
  16370. })(BABYLON || (BABYLON = {}));
  16371. var __extends = this.__extends || function (d, b) {
  16372. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16373. function __() { this.constructor = d; }
  16374. __.prototype = b.prototype;
  16375. d.prototype = new __();
  16376. };
  16377. var BABYLON;
  16378. (function (BABYLON) {
  16379. var OculusRiftDevKit2013_Metric = {
  16380. HResolution: 1280,
  16381. VResolution: 800,
  16382. HScreenSize: 0.149759993,
  16383. VScreenSize: 0.0935999975,
  16384. VScreenCenter: 0.0467999987,
  16385. EyeToScreenDistance: 0.0410000011,
  16386. LensSeparationDistance: 0.0635000020,
  16387. InterpupillaryDistance: 0.0640000030,
  16388. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  16389. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  16390. PostProcessScaleFactor: 1.714605507808412,
  16391. LensCenterOffset: 0.151976421
  16392. };
  16393. var _OculusInnerGamepadCamera = (function (_super) {
  16394. __extends(_OculusInnerGamepadCamera, _super);
  16395. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  16396. _super.call(this, name, position, scene);
  16397. this._workMatrix = new BABYLON.Matrix();
  16398. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  16399. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  16400. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  16401. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  16402. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  16403. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  16404. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  16405. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  16406. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  16407. }
  16408. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  16409. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  16410. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  16411. return this._projectionMatrix;
  16412. };
  16413. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  16414. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  16415. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  16416. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  16417. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  16418. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  16419. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  16420. return this._viewMatrix;
  16421. };
  16422. return _OculusInnerGamepadCamera;
  16423. })(BABYLON.FreeCamera);
  16424. var OculusGamepadCamera = (function (_super) {
  16425. __extends(OculusGamepadCamera, _super);
  16426. function OculusGamepadCamera(name, position, scene) {
  16427. var _this = this;
  16428. _super.call(this, name, position, scene);
  16429. this.angularSensibility = 200;
  16430. this.moveSensibility = 75;
  16431. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  16432. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  16433. this.subCameras.push(this._leftCamera);
  16434. this.subCameras.push(this._rightCamera);
  16435. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  16436. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  16437. _this._onNewGameConnected(gamepad);
  16438. });
  16439. }
  16440. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  16441. if (gamepad.index === 0) {
  16442. this._gamepad = gamepad;
  16443. }
  16444. };
  16445. OculusGamepadCamera.prototype._update = function () {
  16446. this._leftCamera.position.copyFrom(this.position);
  16447. this._rightCamera.position.copyFrom(this.position);
  16448. this._updateCamera(this._leftCamera);
  16449. this._updateCamera(this._rightCamera);
  16450. _super.prototype._update.call(this);
  16451. };
  16452. OculusGamepadCamera.prototype._checkInputs = function () {
  16453. if (!this._gamepad) {
  16454. return;
  16455. }
  16456. var LSValues = this._gamepad.leftStick;
  16457. var normalizedLX = LSValues.x / this.moveSensibility;
  16458. var normalizedLY = LSValues.y / this.moveSensibility;
  16459. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  16460. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  16461. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  16462. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  16463. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  16464. };
  16465. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  16466. camera.minZ = this.minZ;
  16467. camera.maxZ = this.maxZ;
  16468. camera.rotation.x = this.rotation.x;
  16469. camera.rotation.y = this.rotation.y;
  16470. camera.rotation.z = this.rotation.z;
  16471. };
  16472. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  16473. var yaw = evt.alpha / 180 * Math.PI;
  16474. var pitch = evt.beta / 180 * Math.PI;
  16475. var roll = evt.gamma / 180 * Math.PI;
  16476. if (!this._offsetOrientation) {
  16477. this._offsetOrientation = {
  16478. yaw: yaw,
  16479. pitch: pitch,
  16480. roll: roll
  16481. };
  16482. return;
  16483. } else {
  16484. this.rotation.y += yaw - this._offsetOrientation.yaw;
  16485. this.rotation.x += pitch - this._offsetOrientation.pitch;
  16486. this.rotation.z += this._offsetOrientation.roll - roll;
  16487. this._offsetOrientation.yaw = yaw;
  16488. this._offsetOrientation.pitch = pitch;
  16489. this._offsetOrientation.roll = roll;
  16490. }
  16491. };
  16492. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  16493. _super.prototype.attachControl.call(this, element, noPreventDefault);
  16494. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  16495. };
  16496. OculusGamepadCamera.prototype.detachControl = function (element) {
  16497. _super.prototype.detachControl.call(this, element);
  16498. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  16499. };
  16500. OculusGamepadCamera.prototype.dispose = function () {
  16501. this._gamepads.dispose();
  16502. _super.prototype.dispose.call(this);
  16503. };
  16504. return OculusGamepadCamera;
  16505. })(BABYLON.FreeCamera);
  16506. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  16507. })(BABYLON || (BABYLON = {}));
  16508. var __extends = this.__extends || function (d, b) {
  16509. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16510. function __() { this.constructor = d; }
  16511. __.prototype = b.prototype;
  16512. d.prototype = new __();
  16513. };
  16514. var BABYLON;
  16515. (function (BABYLON) {
  16516. var VirtualJoysticksCamera = (function (_super) {
  16517. __extends(VirtualJoysticksCamera, _super);
  16518. function VirtualJoysticksCamera(name, position, scene) {
  16519. _super.call(this, name, position, scene);
  16520. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  16521. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  16522. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  16523. this._leftjoystick.setJoystickSensibility(0.15);
  16524. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  16525. this._rightjoystick.setAxisForUpDown(0 /* X */);
  16526. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  16527. this._rightjoystick.reverseUpDown = true;
  16528. this._rightjoystick.setJoystickSensibility(0.05);
  16529. this._rightjoystick.setJoystickColor("yellow");
  16530. }
  16531. VirtualJoysticksCamera.prototype._checkInputs = function () {
  16532. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  16533. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  16534. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  16535. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  16536. if (!this._leftjoystick.pressed) {
  16537. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  16538. }
  16539. if (!this._rightjoystick.pressed) {
  16540. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  16541. }
  16542. };
  16543. VirtualJoysticksCamera.prototype.dispose = function () {
  16544. this._leftjoystick.releaseCanvas();
  16545. _super.prototype.dispose.call(this);
  16546. };
  16547. return VirtualJoysticksCamera;
  16548. })(BABYLON.FreeCamera);
  16549. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  16550. })(BABYLON || (BABYLON = {}));
  16551. var __extends = this.__extends || function (d, b) {
  16552. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16553. function __() { this.constructor = d; }
  16554. __.prototype = b.prototype;
  16555. d.prototype = new __();
  16556. };
  16557. var BABYLON;
  16558. (function (BABYLON) {
  16559. var ShaderMaterial = (function (_super) {
  16560. __extends(ShaderMaterial, _super);
  16561. function ShaderMaterial(name, scene, shaderPath, options) {
  16562. _super.call(this, name, scene);
  16563. this._textures = new Array();
  16564. this._floats = new Array();
  16565. this._floatsArrays = {};
  16566. this._colors3 = new Array();
  16567. this._colors4 = new Array();
  16568. this._vectors2 = new Array();
  16569. this._vectors3 = new Array();
  16570. this._matrices = new Array();
  16571. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  16572. this._shaderPath = shaderPath;
  16573. options.needAlphaBlending = options.needAlphaBlending || false;
  16574. options.needAlphaTesting = options.needAlphaTesting || false;
  16575. options.attributes = options.attributes || ["position", "normal", "uv"];
  16576. options.uniforms = options.uniforms || ["worldViewProjection"];
  16577. options.samplers = options.samplers || [];
  16578. this._options = options;
  16579. }
  16580. ShaderMaterial.prototype.needAlphaBlending = function () {
  16581. return this._options.needAlphaBlending;
  16582. };
  16583. ShaderMaterial.prototype.needAlphaTesting = function () {
  16584. return this._options.needAlphaTesting;
  16585. };
  16586. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  16587. if (this._options.uniforms.indexOf(uniformName) === -1) {
  16588. this._options.uniforms.push(uniformName);
  16589. }
  16590. };
  16591. ShaderMaterial.prototype.setTexture = function (name, texture) {
  16592. if (this._options.samplers.indexOf(name) === -1) {
  16593. this._options.samplers.push(name);
  16594. }
  16595. this._textures[name] = texture;
  16596. return this;
  16597. };
  16598. ShaderMaterial.prototype.setFloat = function (name, value) {
  16599. this._checkUniform(name);
  16600. this._floats[name] = value;
  16601. return this;
  16602. };
  16603. ShaderMaterial.prototype.setFloats = function (name, value) {
  16604. this._checkUniform(name);
  16605. this._floatsArrays[name] = value;
  16606. return this;
  16607. };
  16608. ShaderMaterial.prototype.setColor3 = function (name, value) {
  16609. this._checkUniform(name);
  16610. this._colors3[name] = value;
  16611. return this;
  16612. };
  16613. ShaderMaterial.prototype.setColor4 = function (name, value) {
  16614. this._checkUniform(name);
  16615. this._colors4[name] = value;
  16616. return this;
  16617. };
  16618. ShaderMaterial.prototype.setVector2 = function (name, value) {
  16619. this._checkUniform(name);
  16620. this._vectors2[name] = value;
  16621. return this;
  16622. };
  16623. ShaderMaterial.prototype.setVector3 = function (name, value) {
  16624. this._checkUniform(name);
  16625. this._vectors3[name] = value;
  16626. return this;
  16627. };
  16628. ShaderMaterial.prototype.setMatrix = function (name, value) {
  16629. this._checkUniform(name);
  16630. this._matrices[name] = value;
  16631. return this;
  16632. };
  16633. ShaderMaterial.prototype.isReady = function () {
  16634. var engine = this.getScene().getEngine();
  16635. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  16636. if (!this._effect.isReady()) {
  16637. return false;
  16638. }
  16639. return true;
  16640. };
  16641. ShaderMaterial.prototype.bind = function (world) {
  16642. if (this._options.uniforms.indexOf("world") !== -1) {
  16643. this._effect.setMatrix("world", world);
  16644. }
  16645. if (this._options.uniforms.indexOf("view") !== -1) {
  16646. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  16647. }
  16648. if (this._options.uniforms.indexOf("worldView") !== -1) {
  16649. world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
  16650. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  16651. }
  16652. if (this._options.uniforms.indexOf("projection") !== -1) {
  16653. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  16654. }
  16655. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  16656. this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
  16657. }
  16658. for (var name in this._textures) {
  16659. this._effect.setTexture(name, this._textures[name]);
  16660. }
  16661. for (name in this._floats) {
  16662. this._effect.setFloat(name, this._floats[name]);
  16663. }
  16664. for (name in this._floatsArrays) {
  16665. this._effect.setArray(name, this._floatsArrays[name]);
  16666. }
  16667. for (name in this._colors3) {
  16668. this._effect.setColor3(name, this._colors3[name]);
  16669. }
  16670. for (name in this._colors4) {
  16671. var color = this._colors4[name];
  16672. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16673. }
  16674. for (name in this._vectors2) {
  16675. this._effect.setVector2(name, this._vectors2[name]);
  16676. }
  16677. for (name in this._vectors3) {
  16678. this._effect.setVector3(name, this._vectors3[name]);
  16679. }
  16680. for (name in this._matrices) {
  16681. this._effect.setMatrix(name, this._matrices[name]);
  16682. }
  16683. };
  16684. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  16685. for (var name in this._textures) {
  16686. this._textures[name].dispose();
  16687. }
  16688. this._textures = [];
  16689. _super.prototype.dispose.call(this, forceDisposeEffect);
  16690. };
  16691. return ShaderMaterial;
  16692. })(BABYLON.Material);
  16693. BABYLON.ShaderMaterial = ShaderMaterial;
  16694. })(BABYLON || (BABYLON = {}));
  16695. var BABYLON;
  16696. (function (BABYLON) {
  16697. var VertexData = (function () {
  16698. function VertexData() {
  16699. }
  16700. VertexData.prototype.set = function (data, kind) {
  16701. switch (kind) {
  16702. case BABYLON.VertexBuffer.PositionKind:
  16703. this.positions = data;
  16704. break;
  16705. case BABYLON.VertexBuffer.NormalKind:
  16706. this.normals = data;
  16707. break;
  16708. case BABYLON.VertexBuffer.UVKind:
  16709. this.uvs = data;
  16710. break;
  16711. case BABYLON.VertexBuffer.UV2Kind:
  16712. this.uv2s = data;
  16713. break;
  16714. case BABYLON.VertexBuffer.ColorKind:
  16715. this.colors = data;
  16716. break;
  16717. case BABYLON.VertexBuffer.MatricesIndicesKind:
  16718. this.matricesIndices = data;
  16719. break;
  16720. case BABYLON.VertexBuffer.MatricesWeightsKind:
  16721. this.matricesWeights = data;
  16722. break;
  16723. }
  16724. };
  16725. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  16726. this._applyTo(mesh, updatable);
  16727. };
  16728. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  16729. this._applyTo(geometry, updatable);
  16730. };
  16731. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  16732. this._update(mesh);
  16733. };
  16734. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  16735. this._update(geometry);
  16736. };
  16737. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  16738. if (this.positions) {
  16739. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  16740. }
  16741. if (this.normals) {
  16742. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  16743. }
  16744. if (this.uvs) {
  16745. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  16746. }
  16747. if (this.uv2s) {
  16748. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  16749. }
  16750. if (this.colors) {
  16751. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  16752. }
  16753. if (this.matricesIndices) {
  16754. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  16755. }
  16756. if (this.matricesWeights) {
  16757. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  16758. }
  16759. if (this.indices) {
  16760. meshOrGeometry.setIndices(this.indices);
  16761. }
  16762. };
  16763. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  16764. if (this.positions) {
  16765. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  16766. }
  16767. if (this.normals) {
  16768. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  16769. }
  16770. if (this.uvs) {
  16771. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  16772. }
  16773. if (this.uv2s) {
  16774. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  16775. }
  16776. if (this.colors) {
  16777. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  16778. }
  16779. if (this.matricesIndices) {
  16780. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  16781. }
  16782. if (this.matricesWeights) {
  16783. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  16784. }
  16785. if (this.indices) {
  16786. meshOrGeometry.setIndices(this.indices);
  16787. }
  16788. };
  16789. VertexData.prototype.transform = function (matrix) {
  16790. var transformed = BABYLON.Vector3.Zero();
  16791. if (this.positions) {
  16792. var position = BABYLON.Vector3.Zero();
  16793. for (var index = 0; index < this.positions.length; index += 3) {
  16794. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  16795. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  16796. this.positions[index] = transformed.x;
  16797. this.positions[index + 1] = transformed.y;
  16798. this.positions[index + 2] = transformed.z;
  16799. }
  16800. }
  16801. if (this.normals) {
  16802. var normal = BABYLON.Vector3.Zero();
  16803. for (index = 0; index < this.normals.length; index += 3) {
  16804. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  16805. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  16806. this.normals[index] = transformed.x;
  16807. this.normals[index + 1] = transformed.y;
  16808. this.normals[index + 2] = transformed.z;
  16809. }
  16810. }
  16811. };
  16812. VertexData.prototype.merge = function (other) {
  16813. if (other.indices) {
  16814. if (!this.indices) {
  16815. this.indices = [];
  16816. }
  16817. var offset = this.positions ? this.positions.length / 3 : 0;
  16818. for (var index = 0; index < other.indices.length; index++) {
  16819. this.indices.push(other.indices[index] + offset);
  16820. }
  16821. }
  16822. if (other.positions) {
  16823. if (!this.positions) {
  16824. this.positions = [];
  16825. }
  16826. for (index = 0; index < other.positions.length; index++) {
  16827. this.positions.push(other.positions[index]);
  16828. }
  16829. }
  16830. if (other.normals) {
  16831. if (!this.normals) {
  16832. this.normals = [];
  16833. }
  16834. for (index = 0; index < other.normals.length; index++) {
  16835. this.normals.push(other.normals[index]);
  16836. }
  16837. }
  16838. if (other.uvs) {
  16839. if (!this.uvs) {
  16840. this.uvs = [];
  16841. }
  16842. for (index = 0; index < other.uvs.length; index++) {
  16843. this.uvs.push(other.uvs[index]);
  16844. }
  16845. }
  16846. if (other.uv2s) {
  16847. if (!this.uv2s) {
  16848. this.uv2s = [];
  16849. }
  16850. for (index = 0; index < other.uv2s.length; index++) {
  16851. this.uv2s.push(other.uv2s[index]);
  16852. }
  16853. }
  16854. if (other.matricesIndices) {
  16855. if (!this.matricesIndices) {
  16856. this.matricesIndices = [];
  16857. }
  16858. for (index = 0; index < other.matricesIndices.length; index++) {
  16859. this.matricesIndices.push(other.matricesIndices[index]);
  16860. }
  16861. }
  16862. if (other.matricesWeights) {
  16863. if (!this.matricesWeights) {
  16864. this.matricesWeights = [];
  16865. }
  16866. for (index = 0; index < other.matricesWeights.length; index++) {
  16867. this.matricesWeights.push(other.matricesWeights[index]);
  16868. }
  16869. }
  16870. if (other.colors) {
  16871. if (!this.colors) {
  16872. this.colors = [];
  16873. }
  16874. for (index = 0; index < other.colors.length; index++) {
  16875. this.colors.push(other.colors[index]);
  16876. }
  16877. }
  16878. };
  16879. VertexData.ExtractFromMesh = function (mesh) {
  16880. return VertexData._ExtractFrom(mesh);
  16881. };
  16882. VertexData.ExtractFromGeometry = function (geometry) {
  16883. return VertexData._ExtractFrom(geometry);
  16884. };
  16885. VertexData._ExtractFrom = function (meshOrGeometry) {
  16886. var result = new BABYLON.VertexData();
  16887. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16888. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16889. }
  16890. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16891. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16892. }
  16893. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16894. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16895. }
  16896. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  16897. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  16898. }
  16899. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  16900. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  16901. }
  16902. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16903. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16904. }
  16905. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16906. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16907. }
  16908. result.indices = meshOrGeometry.getIndices();
  16909. return result;
  16910. };
  16911. VertexData.CreateBox = function (size) {
  16912. var normalsSource = [
  16913. new BABYLON.Vector3(0, 0, 1),
  16914. new BABYLON.Vector3(0, 0, -1),
  16915. new BABYLON.Vector3(1, 0, 0),
  16916. new BABYLON.Vector3(-1, 0, 0),
  16917. new BABYLON.Vector3(0, 1, 0),
  16918. new BABYLON.Vector3(0, -1, 0)
  16919. ];
  16920. var indices = [];
  16921. var positions = [];
  16922. var normals = [];
  16923. var uvs = [];
  16924. size = size || 1;
  16925. for (var index = 0; index < normalsSource.length; index++) {
  16926. var normal = normalsSource[index];
  16927. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  16928. var side2 = BABYLON.Vector3.Cross(normal, side1);
  16929. var verticesLength = positions.length / 3;
  16930. indices.push(verticesLength);
  16931. indices.push(verticesLength + 1);
  16932. indices.push(verticesLength + 2);
  16933. indices.push(verticesLength);
  16934. indices.push(verticesLength + 2);
  16935. indices.push(verticesLength + 3);
  16936. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  16937. positions.push(vertex.x, vertex.y, vertex.z);
  16938. normals.push(normal.x, normal.y, normal.z);
  16939. uvs.push(1.0, 1.0);
  16940. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  16941. positions.push(vertex.x, vertex.y, vertex.z);
  16942. normals.push(normal.x, normal.y, normal.z);
  16943. uvs.push(0.0, 1.0);
  16944. vertex = normal.add(side1).add(side2).scale(size / 2);
  16945. positions.push(vertex.x, vertex.y, vertex.z);
  16946. normals.push(normal.x, normal.y, normal.z);
  16947. uvs.push(0.0, 0.0);
  16948. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  16949. positions.push(vertex.x, vertex.y, vertex.z);
  16950. normals.push(normal.x, normal.y, normal.z);
  16951. uvs.push(1.0, 0.0);
  16952. }
  16953. var vertexData = new BABYLON.VertexData();
  16954. vertexData.indices = indices;
  16955. vertexData.positions = positions;
  16956. vertexData.normals = normals;
  16957. vertexData.uvs = uvs;
  16958. return vertexData;
  16959. };
  16960. VertexData.CreateSphere = function (segments, diameter) {
  16961. segments = segments || 32;
  16962. diameter = diameter || 1;
  16963. var radius = diameter / 2;
  16964. var totalZRotationSteps = 2 + segments;
  16965. var totalYRotationSteps = 2 * totalZRotationSteps;
  16966. var indices = [];
  16967. var positions = [];
  16968. var normals = [];
  16969. var uvs = [];
  16970. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  16971. var normalizedZ = zRotationStep / totalZRotationSteps;
  16972. var angleZ = (normalizedZ * Math.PI);
  16973. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  16974. var normalizedY = yRotationStep / totalYRotationSteps;
  16975. var angleY = normalizedY * Math.PI * 2;
  16976. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  16977. var rotationY = BABYLON.Matrix.RotationY(angleY);
  16978. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  16979. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  16980. var vertex = complete.scale(radius);
  16981. var normal = BABYLON.Vector3.Normalize(vertex);
  16982. positions.push(vertex.x, vertex.y, vertex.z);
  16983. normals.push(normal.x, normal.y, normal.z);
  16984. uvs.push(normalizedZ, normalizedY);
  16985. }
  16986. if (zRotationStep > 0) {
  16987. var verticesCount = positions.length / 3;
  16988. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  16989. indices.push((firstIndex));
  16990. indices.push((firstIndex + 1));
  16991. indices.push(firstIndex + totalYRotationSteps + 1);
  16992. indices.push((firstIndex + totalYRotationSteps + 1));
  16993. indices.push((firstIndex + 1));
  16994. indices.push((firstIndex + totalYRotationSteps + 2));
  16995. }
  16996. }
  16997. }
  16998. var vertexData = new BABYLON.VertexData();
  16999. vertexData.indices = indices;
  17000. vertexData.positions = positions;
  17001. vertexData.normals = normals;
  17002. vertexData.uvs = uvs;
  17003. return vertexData;
  17004. };
  17005. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  17006. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  17007. var radiusTop = diameterTop / 2;
  17008. var radiusBottom = diameterBottom / 2;
  17009. var indices = [];
  17010. var positions = [];
  17011. var normals = [];
  17012. var uvs = [];
  17013. height = height || 1;
  17014. diameterTop = diameterTop || 0.5;
  17015. diameterBottom = diameterBottom || 1;
  17016. tessellation = tessellation || 16;
  17017. subdivisions = subdivisions || 1;
  17018. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  17019. var getCircleVector = function (i) {
  17020. var angle = (i * 2.0 * Math.PI / tessellation);
  17021. var dx = Math.cos(angle);
  17022. var dz = Math.sin(angle);
  17023. return new BABYLON.Vector3(dx, 0, dz);
  17024. };
  17025. var createCylinderCap = function (isTop) {
  17026. var radius = isTop ? radiusTop : radiusBottom;
  17027. if (radius == 0) {
  17028. return;
  17029. }
  17030. var vbase = positions.length / 3;
  17031. var offset = new BABYLON.Vector3(0, height / 2, 0);
  17032. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  17033. if (!isTop) {
  17034. offset.scaleInPlace(-1);
  17035. textureScale.x = -textureScale.x;
  17036. }
  17037. for (i = 0; i < tessellation; i++) {
  17038. var circleVector = getCircleVector(i);
  17039. var position = circleVector.scale(radius).add(offset);
  17040. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  17041. positions.push(position.x, position.y, position.z);
  17042. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17043. }
  17044. for (var i = 0; i < tessellation - 2; i++) {
  17045. if (!isTop) {
  17046. indices.push(vbase);
  17047. indices.push(vbase + (i + 2) % tessellation);
  17048. indices.push(vbase + (i + 1) % tessellation);
  17049. } else {
  17050. indices.push(vbase);
  17051. indices.push(vbase + (i + 1) % tessellation);
  17052. indices.push(vbase + (i + 2) % tessellation);
  17053. }
  17054. }
  17055. };
  17056. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  17057. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  17058. var stride = tessellation + 1;
  17059. for (var i = 0; i <= tessellation; i++) {
  17060. var circleVector = getCircleVector(i);
  17061. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  17062. var position, radius = radiusBottom;
  17063. for (var s = 0; s <= subdivisions; s++) {
  17064. position = circleVector.scale(radius);
  17065. position.addInPlace(base.add(offset.scale(s)));
  17066. textureCoordinate.y += 1 / subdivisions;
  17067. radius += (radiusTop - radiusBottom) / subdivisions;
  17068. positions.push(position.x, position.y, position.z);
  17069. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17070. }
  17071. }
  17072. subdivisions += 1;
  17073. for (var s = 0; s < subdivisions - 1; s++) {
  17074. for (var i = 0; i <= tessellation; i++) {
  17075. indices.push(i * subdivisions + s);
  17076. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  17077. indices.push(i * subdivisions + (s + 1));
  17078. indices.push(i * subdivisions + (s + 1));
  17079. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  17080. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  17081. }
  17082. }
  17083. createCylinderCap(true);
  17084. createCylinderCap(false);
  17085. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17086. var vertexData = new BABYLON.VertexData();
  17087. vertexData.indices = indices;
  17088. vertexData.positions = positions;
  17089. vertexData.normals = normals;
  17090. vertexData.uvs = uvs;
  17091. return vertexData;
  17092. };
  17093. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  17094. var indices = [];
  17095. var positions = [];
  17096. var normals = [];
  17097. var uvs = [];
  17098. diameter = diameter || 1;
  17099. thickness = thickness || 0.5;
  17100. tessellation = tessellation || 16;
  17101. var stride = tessellation + 1;
  17102. for (var i = 0; i <= tessellation; i++) {
  17103. var u = i / tessellation;
  17104. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  17105. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  17106. for (var j = 0; j <= tessellation; j++) {
  17107. var v = 1 - j / tessellation;
  17108. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  17109. var dx = Math.cos(innerAngle);
  17110. var dy = Math.sin(innerAngle);
  17111. var normal = new BABYLON.Vector3(dx, dy, 0);
  17112. var position = normal.scale(thickness / 2);
  17113. var textureCoordinate = new BABYLON.Vector2(u, v);
  17114. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  17115. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  17116. positions.push(position.x, position.y, position.z);
  17117. normals.push(normal.x, normal.y, normal.z);
  17118. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17119. var nextI = (i + 1) % stride;
  17120. var nextJ = (j + 1) % stride;
  17121. indices.push(i * stride + j);
  17122. indices.push(i * stride + nextJ);
  17123. indices.push(nextI * stride + j);
  17124. indices.push(i * stride + nextJ);
  17125. indices.push(nextI * stride + nextJ);
  17126. indices.push(nextI * stride + j);
  17127. }
  17128. }
  17129. var vertexData = new BABYLON.VertexData();
  17130. vertexData.indices = indices;
  17131. vertexData.positions = positions;
  17132. vertexData.normals = normals;
  17133. vertexData.uvs = uvs;
  17134. return vertexData;
  17135. };
  17136. VertexData.CreateLines = function (points) {
  17137. var indices = [];
  17138. var positions = [];
  17139. for (var index = 0; index < points.length; index++) {
  17140. positions.push(points[index].x, points[index].y, points[index].z);
  17141. if (index > 0) {
  17142. indices.push(index - 1);
  17143. indices.push(index);
  17144. }
  17145. }
  17146. var vertexData = new BABYLON.VertexData();
  17147. vertexData.indices = indices;
  17148. vertexData.positions = positions;
  17149. return vertexData;
  17150. };
  17151. VertexData.CreateGround = function (width, height, subdivisions) {
  17152. var indices = [];
  17153. var positions = [];
  17154. var normals = [];
  17155. var uvs = [];
  17156. var row, col;
  17157. width = width || 1;
  17158. height = height || 1;
  17159. subdivisions = subdivisions || 1;
  17160. for (row = 0; row <= subdivisions; row++) {
  17161. for (col = 0; col <= subdivisions; col++) {
  17162. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  17163. var normal = new BABYLON.Vector3(0, 1.0, 0);
  17164. positions.push(position.x, position.y, position.z);
  17165. normals.push(normal.x, normal.y, normal.z);
  17166. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  17167. }
  17168. }
  17169. for (row = 0; row < subdivisions; row++) {
  17170. for (col = 0; col < subdivisions; col++) {
  17171. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17172. indices.push(col + 1 + row * (subdivisions + 1));
  17173. indices.push(col + row * (subdivisions + 1));
  17174. indices.push(col + (row + 1) * (subdivisions + 1));
  17175. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17176. indices.push(col + row * (subdivisions + 1));
  17177. }
  17178. }
  17179. var vertexData = new BABYLON.VertexData();
  17180. vertexData.indices = indices;
  17181. vertexData.positions = positions;
  17182. vertexData.normals = normals;
  17183. vertexData.uvs = uvs;
  17184. return vertexData;
  17185. };
  17186. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  17187. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  17188. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  17189. var indices = [];
  17190. var positions = [];
  17191. var normals = [];
  17192. var uvs = [];
  17193. var row, col, tileRow, tileCol;
  17194. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  17195. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  17196. precision.w = (precision.w < 1) ? 1 : precision.w;
  17197. precision.h = (precision.h < 1) ? 1 : precision.h;
  17198. var tileSize = {
  17199. 'w': (xmax - xmin) / subdivisions.w,
  17200. 'h': (zmax - zmin) / subdivisions.h
  17201. };
  17202. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  17203. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  17204. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  17205. }
  17206. }
  17207. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  17208. var base = positions.length / 3;
  17209. var rowLength = precision.w + 1;
  17210. for (row = 0; row < precision.h; row++) {
  17211. for (col = 0; col < precision.w; col++) {
  17212. var square = [
  17213. base + col + row * rowLength,
  17214. base + (col + 1) + row * rowLength,
  17215. base + (col + 1) + (row + 1) * rowLength,
  17216. base + col + (row + 1) * rowLength
  17217. ];
  17218. indices.push(square[1]);
  17219. indices.push(square[2]);
  17220. indices.push(square[3]);
  17221. indices.push(square[0]);
  17222. indices.push(square[1]);
  17223. indices.push(square[3]);
  17224. }
  17225. }
  17226. var position = BABYLON.Vector3.Zero();
  17227. var normal = new BABYLON.Vector3(0, 1.0, 0);
  17228. for (row = 0; row <= precision.h; row++) {
  17229. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  17230. for (col = 0; col <= precision.w; col++) {
  17231. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  17232. position.y = 0;
  17233. positions.push(position.x, position.y, position.z);
  17234. normals.push(normal.x, normal.y, normal.z);
  17235. uvs.push(col / precision.w, row / precision.h);
  17236. }
  17237. }
  17238. }
  17239. var vertexData = new BABYLON.VertexData();
  17240. vertexData.indices = indices;
  17241. vertexData.positions = positions;
  17242. vertexData.normals = normals;
  17243. vertexData.uvs = uvs;
  17244. return vertexData;
  17245. };
  17246. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  17247. var indices = [];
  17248. var positions = [];
  17249. var normals = [];
  17250. var uvs = [];
  17251. var row, col;
  17252. for (row = 0; row <= subdivisions; row++) {
  17253. for (col = 0; col <= subdivisions; col++) {
  17254. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  17255. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  17256. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  17257. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  17258. var r = buffer[pos] / 255.0;
  17259. var g = buffer[pos + 1] / 255.0;
  17260. var b = buffer[pos + 2] / 255.0;
  17261. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  17262. position.y = minHeight + (maxHeight - minHeight) * gradient;
  17263. positions.push(position.x, position.y, position.z);
  17264. normals.push(0, 0, 0);
  17265. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  17266. }
  17267. }
  17268. for (row = 0; row < subdivisions; row++) {
  17269. for (col = 0; col < subdivisions; col++) {
  17270. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17271. indices.push(col + 1 + row * (subdivisions + 1));
  17272. indices.push(col + row * (subdivisions + 1));
  17273. indices.push(col + (row + 1) * (subdivisions + 1));
  17274. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17275. indices.push(col + row * (subdivisions + 1));
  17276. }
  17277. }
  17278. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17279. var vertexData = new BABYLON.VertexData();
  17280. vertexData.indices = indices;
  17281. vertexData.positions = positions;
  17282. vertexData.normals = normals;
  17283. vertexData.uvs = uvs;
  17284. return vertexData;
  17285. };
  17286. VertexData.CreatePlane = function (size) {
  17287. var indices = [];
  17288. var positions = [];
  17289. var normals = [];
  17290. var uvs = [];
  17291. size = size || 1;
  17292. var halfSize = size / 2.0;
  17293. positions.push(-halfSize, -halfSize, 0);
  17294. normals.push(0, 0, -1.0);
  17295. uvs.push(0.0, 0.0);
  17296. positions.push(halfSize, -halfSize, 0);
  17297. normals.push(0, 0, -1.0);
  17298. uvs.push(1.0, 0.0);
  17299. positions.push(halfSize, halfSize, 0);
  17300. normals.push(0, 0, -1.0);
  17301. uvs.push(1.0, 1.0);
  17302. positions.push(-halfSize, halfSize, 0);
  17303. normals.push(0, 0, -1.0);
  17304. uvs.push(0.0, 1.0);
  17305. indices.push(0);
  17306. indices.push(1);
  17307. indices.push(2);
  17308. indices.push(0);
  17309. indices.push(2);
  17310. indices.push(3);
  17311. var vertexData = new BABYLON.VertexData();
  17312. vertexData.indices = indices;
  17313. vertexData.positions = positions;
  17314. vertexData.normals = normals;
  17315. vertexData.uvs = uvs;
  17316. return vertexData;
  17317. };
  17318. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  17319. var indices = [];
  17320. var positions = [];
  17321. var normals = [];
  17322. var uvs = [];
  17323. radius = radius || 2;
  17324. tube = tube || 0.5;
  17325. radialSegments = radialSegments || 32;
  17326. tubularSegments = tubularSegments || 32;
  17327. p = p || 2;
  17328. q = q || 3;
  17329. var getPos = function (angle) {
  17330. var cu = Math.cos(angle);
  17331. var su = Math.sin(angle);
  17332. var quOverP = q / p * angle;
  17333. var cs = Math.cos(quOverP);
  17334. var tx = radius * (2 + cs) * 0.5 * cu;
  17335. var ty = radius * (2 + cs) * su * 0.5;
  17336. var tz = radius * Math.sin(quOverP) * 0.5;
  17337. return new BABYLON.Vector3(tx, ty, tz);
  17338. };
  17339. for (var i = 0; i <= radialSegments; i++) {
  17340. var modI = i % radialSegments;
  17341. var u = modI / radialSegments * 2 * p * Math.PI;
  17342. var p1 = getPos(u);
  17343. var p2 = getPos(u + 0.01);
  17344. var tang = p2.subtract(p1);
  17345. var n = p2.add(p1);
  17346. var bitan = BABYLON.Vector3.Cross(tang, n);
  17347. n = BABYLON.Vector3.Cross(bitan, tang);
  17348. bitan.normalize();
  17349. n.normalize();
  17350. for (var j = 0; j < tubularSegments; j++) {
  17351. var modJ = j % tubularSegments;
  17352. var v = modJ / tubularSegments * 2 * Math.PI;
  17353. var cx = -tube * Math.cos(v);
  17354. var cy = tube * Math.sin(v);
  17355. positions.push(p1.x + cx * n.x + cy * bitan.x);
  17356. positions.push(p1.y + cx * n.y + cy * bitan.y);
  17357. positions.push(p1.z + cx * n.z + cy * bitan.z);
  17358. uvs.push(i / radialSegments);
  17359. uvs.push(j / tubularSegments);
  17360. }
  17361. }
  17362. for (i = 0; i < radialSegments; i++) {
  17363. for (j = 0; j < tubularSegments; j++) {
  17364. var jNext = (j + 1) % tubularSegments;
  17365. var a = i * tubularSegments + j;
  17366. var b = (i + 1) * tubularSegments + j;
  17367. var c = (i + 1) * tubularSegments + jNext;
  17368. var d = i * tubularSegments + jNext;
  17369. indices.push(d);
  17370. indices.push(b);
  17371. indices.push(a);
  17372. indices.push(d);
  17373. indices.push(c);
  17374. indices.push(b);
  17375. }
  17376. }
  17377. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17378. var vertexData = new BABYLON.VertexData();
  17379. vertexData.indices = indices;
  17380. vertexData.positions = positions;
  17381. vertexData.normals = normals;
  17382. vertexData.uvs = uvs;
  17383. return vertexData;
  17384. };
  17385. VertexData.ComputeNormals = function (positions, indices, normals) {
  17386. var positionVectors = [];
  17387. var facesOfVertices = [];
  17388. var index;
  17389. for (index = 0; index < positions.length; index += 3) {
  17390. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  17391. positionVectors.push(vector3);
  17392. facesOfVertices.push([]);
  17393. }
  17394. var facesNormals = [];
  17395. for (index = 0; index < indices.length / 3; index++) {
  17396. var i1 = indices[index * 3];
  17397. var i2 = indices[index * 3 + 1];
  17398. var i3 = indices[index * 3 + 2];
  17399. var p1 = positionVectors[i1];
  17400. var p2 = positionVectors[i2];
  17401. var p3 = positionVectors[i3];
  17402. var p1p2 = p1.subtract(p2);
  17403. var p3p2 = p3.subtract(p2);
  17404. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  17405. facesOfVertices[i1].push(index);
  17406. facesOfVertices[i2].push(index);
  17407. facesOfVertices[i3].push(index);
  17408. }
  17409. for (index = 0; index < positionVectors.length; index++) {
  17410. var faces = facesOfVertices[index];
  17411. var normal = BABYLON.Vector3.Zero();
  17412. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  17413. normal.addInPlace(facesNormals[faces[faceIndex]]);
  17414. }
  17415. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  17416. normals[index * 3] = normal.x;
  17417. normals[index * 3 + 1] = normal.y;
  17418. normals[index * 3 + 2] = normal.z;
  17419. }
  17420. };
  17421. return VertexData;
  17422. })();
  17423. BABYLON.VertexData = VertexData;
  17424. })(BABYLON || (BABYLON = {}));
  17425. var __extends = this.__extends || function (d, b) {
  17426. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17427. function __() { this.constructor = d; }
  17428. __.prototype = b.prototype;
  17429. d.prototype = new __();
  17430. };
  17431. var BABYLON;
  17432. (function (BABYLON) {
  17433. var buildCamera = function (that, name) {
  17434. that._leftCamera.isIntermediate = true;
  17435. that.subCameras.push(that._leftCamera);
  17436. that.subCameras.push(that._rightCamera);
  17437. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  17438. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  17439. that._anaglyphPostProcess.onApply = function (effect) {
  17440. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  17441. };
  17442. that._update();
  17443. };
  17444. var AnaglyphArcRotateCamera = (function (_super) {
  17445. __extends(AnaglyphArcRotateCamera, _super);
  17446. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  17447. _super.call(this, name, alpha, beta, radius, target, scene);
  17448. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  17449. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  17450. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  17451. buildCamera(this, name);
  17452. }
  17453. AnaglyphArcRotateCamera.prototype._update = function () {
  17454. this._updateCamera(this._leftCamera);
  17455. this._updateCamera(this._rightCamera);
  17456. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  17457. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  17458. _super.prototype._update.call(this);
  17459. };
  17460. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  17461. camera.beta = this.beta;
  17462. camera.radius = this.radius;
  17463. camera.minZ = this.minZ;
  17464. camera.maxZ = this.maxZ;
  17465. camera.fov = this.fov;
  17466. camera.target = this.target;
  17467. };
  17468. return AnaglyphArcRotateCamera;
  17469. })(BABYLON.ArcRotateCamera);
  17470. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  17471. var AnaglyphFreeCamera = (function (_super) {
  17472. __extends(AnaglyphFreeCamera, _super);
  17473. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  17474. _super.call(this, name, position, scene);
  17475. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  17476. this._transformMatrix = new BABYLON.Matrix();
  17477. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  17478. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  17479. buildCamera(this, name);
  17480. }
  17481. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  17482. var target = this.getTarget();
  17483. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  17484. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  17485. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  17486. };
  17487. AnaglyphFreeCamera.prototype._update = function () {
  17488. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  17489. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  17490. this._updateCamera(this._leftCamera);
  17491. this._updateCamera(this._rightCamera);
  17492. _super.prototype._update.call(this);
  17493. };
  17494. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  17495. camera.minZ = this.minZ;
  17496. camera.maxZ = this.maxZ;
  17497. camera.fov = this.fov;
  17498. camera.viewport = this.viewport;
  17499. camera.setTarget(this.getTarget());
  17500. };
  17501. return AnaglyphFreeCamera;
  17502. })(BABYLON.FreeCamera);
  17503. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  17504. })(BABYLON || (BABYLON = {}));
  17505. var __extends = this.__extends || function (d, b) {
  17506. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17507. function __() { this.constructor = d; }
  17508. __.prototype = b.prototype;
  17509. d.prototype = new __();
  17510. };
  17511. var BABYLON;
  17512. (function (BABYLON) {
  17513. var AnaglyphPostProcess = (function (_super) {
  17514. __extends(AnaglyphPostProcess, _super);
  17515. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17516. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  17517. }
  17518. return AnaglyphPostProcess;
  17519. })(BABYLON.PostProcess);
  17520. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  17521. })(BABYLON || (BABYLON = {}));
  17522. var BABYLON;
  17523. (function (BABYLON) {
  17524. var Tags = (function () {
  17525. function Tags() {
  17526. }
  17527. Tags.EnableFor = function (obj) {
  17528. obj._tags = obj._tags || {};
  17529. obj.hasTags = function () {
  17530. return Tags.HasTags(obj);
  17531. };
  17532. obj.addTags = function (tagsString) {
  17533. return Tags.AddTagsTo(obj, tagsString);
  17534. };
  17535. obj.removeTags = function (tagsString) {
  17536. return Tags.RemoveTagsFrom(obj, tagsString);
  17537. };
  17538. obj.matchesTagsQuery = function (tagsQuery) {
  17539. return Tags.MatchesQuery(obj, tagsQuery);
  17540. };
  17541. };
  17542. Tags.DisableFor = function (obj) {
  17543. delete obj._tags;
  17544. delete obj.hasTags;
  17545. delete obj.addTags;
  17546. delete obj.removeTags;
  17547. delete obj.matchesTagsQuery;
  17548. };
  17549. Tags.HasTags = function (obj) {
  17550. if (!obj._tags) {
  17551. return false;
  17552. }
  17553. return !BABYLON.Tools.IsEmpty(obj._tags);
  17554. };
  17555. Tags.GetTags = function (obj) {
  17556. if (!obj._tags) {
  17557. return null;
  17558. }
  17559. return obj._tags;
  17560. };
  17561. Tags.AddTagsTo = function (obj, tagsString) {
  17562. if (!tagsString) {
  17563. return;
  17564. }
  17565. var tags = tagsString.split(" ");
  17566. for (var t in tags) {
  17567. Tags._AddTagTo(obj, tags[t]);
  17568. }
  17569. };
  17570. Tags._AddTagTo = function (obj, tag) {
  17571. tag = tag.trim();
  17572. if (tag === "" || tag === "true" || tag === "false") {
  17573. return;
  17574. }
  17575. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  17576. return;
  17577. }
  17578. Tags.EnableFor(obj);
  17579. obj._tags[tag] = true;
  17580. };
  17581. Tags.RemoveTagsFrom = function (obj, tagsString) {
  17582. if (!Tags.HasTags(obj)) {
  17583. return;
  17584. }
  17585. var tags = tagsString.split(" ");
  17586. for (var t in tags) {
  17587. Tags._RemoveTagFrom(obj, tags[t]);
  17588. }
  17589. };
  17590. Tags._RemoveTagFrom = function (obj, tag) {
  17591. delete obj._tags[tag];
  17592. };
  17593. Tags.MatchesQuery = function (obj, tagsQuery) {
  17594. if (tagsQuery === undefined) {
  17595. return true;
  17596. }
  17597. if (tagsQuery === "") {
  17598. return Tags.HasTags(obj);
  17599. }
  17600. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  17601. return Tags.HasTags(obj) && obj._tags[r];
  17602. });
  17603. };
  17604. return Tags;
  17605. })();
  17606. BABYLON.Tags = Tags;
  17607. })(BABYLON || (BABYLON = {}));
  17608. var BABYLON;
  17609. (function (BABYLON) {
  17610. (function (Internals) {
  17611. var AndOrNotEvaluator = (function () {
  17612. function AndOrNotEvaluator() {
  17613. }
  17614. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  17615. if (!query.match(/\([^\(\)]*\)/g)) {
  17616. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  17617. } else {
  17618. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  17619. r = r.slice(1, r.length - 1);
  17620. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  17621. });
  17622. }
  17623. if (query === "true") {
  17624. return true;
  17625. }
  17626. if (query === "false") {
  17627. return false;
  17628. }
  17629. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  17630. };
  17631. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  17632. evaluateCallback = evaluateCallback || (function (r) {
  17633. return r === "true" ? true : false;
  17634. });
  17635. var result;
  17636. var or = parenthesisContent.split("||");
  17637. for (var i in or) {
  17638. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  17639. var and = ori.split("&&");
  17640. if (and.length > 1) {
  17641. for (var j = 0; j < and.length; ++j) {
  17642. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  17643. if (andj !== "true" && andj !== "false") {
  17644. if (andj[0] === "!") {
  17645. result = !evaluateCallback(andj.substring(1));
  17646. } else {
  17647. result = evaluateCallback(andj);
  17648. }
  17649. } else {
  17650. result = andj === "true" ? true : false;
  17651. }
  17652. if (!result) {
  17653. ori = "false";
  17654. break;
  17655. }
  17656. }
  17657. }
  17658. if (result || ori === "true") {
  17659. result = true;
  17660. break;
  17661. }
  17662. if (ori !== "true" && ori !== "false") {
  17663. if (ori[0] === "!") {
  17664. result = !evaluateCallback(ori.substring(1));
  17665. } else {
  17666. result = evaluateCallback(ori);
  17667. }
  17668. } else {
  17669. result = ori === "true" ? true : false;
  17670. }
  17671. }
  17672. return result ? "true" : "false";
  17673. };
  17674. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  17675. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  17676. r = r.replace(/[\s]/g, function () {
  17677. return "";
  17678. });
  17679. return r.length % 2 ? "!" : "";
  17680. });
  17681. booleanString = booleanString.trim();
  17682. if (booleanString === "!true") {
  17683. booleanString = "false";
  17684. } else if (booleanString === "!false") {
  17685. booleanString = "true";
  17686. }
  17687. return booleanString;
  17688. };
  17689. return AndOrNotEvaluator;
  17690. })();
  17691. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  17692. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17693. var Internals = BABYLON.Internals;
  17694. })(BABYLON || (BABYLON = {}));
  17695. var BABYLON;
  17696. (function (BABYLON) {
  17697. var PostProcessRenderPass = (function () {
  17698. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  17699. this._enabled = true;
  17700. this._refCount = 0;
  17701. this._name = name;
  17702. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  17703. this.setRenderList(renderList);
  17704. this._renderTexture.onBeforeRender = beforeRender;
  17705. this._renderTexture.onAfterRender = afterRender;
  17706. this._scene = scene;
  17707. }
  17708. PostProcessRenderPass.prototype._incRefCount = function () {
  17709. if (this._refCount === 0) {
  17710. this._scene.customRenderTargets.push(this._renderTexture);
  17711. }
  17712. return ++this._refCount;
  17713. };
  17714. PostProcessRenderPass.prototype._decRefCount = function () {
  17715. this._refCount--;
  17716. if (this._refCount <= 0) {
  17717. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  17718. }
  17719. return this._refCount;
  17720. };
  17721. PostProcessRenderPass.prototype._update = function () {
  17722. this.setRenderList(this._renderList);
  17723. };
  17724. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  17725. this._renderTexture.renderList = renderList;
  17726. };
  17727. PostProcessRenderPass.prototype.getRenderTexture = function () {
  17728. return this._renderTexture;
  17729. };
  17730. return PostProcessRenderPass;
  17731. })();
  17732. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  17733. })(BABYLON || (BABYLON = {}));
  17734. var BABYLON;
  17735. (function (BABYLON) {
  17736. var PostProcessRenderEffect = (function () {
  17737. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  17738. this._engine = engine;
  17739. this._name = name;
  17740. this._singleInstance = singleInstance || true;
  17741. this._getPostProcess = getPostProcess;
  17742. this._cameras = [];
  17743. this._postProcesses = [];
  17744. this._indicesForCamera = [];
  17745. this._renderPasses = [];
  17746. this._renderEffectAsPasses = [];
  17747. }
  17748. PostProcessRenderEffect.prototype._update = function () {
  17749. for (var renderPassName in this._renderPasses) {
  17750. this._renderPasses[renderPassName]._update();
  17751. }
  17752. };
  17753. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  17754. this._renderPasses[renderPass._name] = renderPass;
  17755. this._linkParameters();
  17756. };
  17757. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  17758. delete this._renderPasses[renderPass._name];
  17759. this._linkParameters();
  17760. };
  17761. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  17762. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  17763. this._linkParameters();
  17764. };
  17765. PostProcessRenderEffect.prototype.getPass = function (passName) {
  17766. for (var renderPassName in this._renderPasses) {
  17767. if (renderPassName === passName) {
  17768. return this._renderPasses[passName];
  17769. }
  17770. }
  17771. };
  17772. PostProcessRenderEffect.prototype.emptyPasses = function () {
  17773. this._renderPasses.length = 0;
  17774. this._linkParameters();
  17775. };
  17776. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  17777. var cameraKey;
  17778. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17779. for (var i = 0; i < _cam.length; i++) {
  17780. var camera = _cam[i];
  17781. var cameraName = camera.name;
  17782. if (this._singleInstance) {
  17783. cameraKey = 0;
  17784. } else {
  17785. cameraKey = cameraName;
  17786. }
  17787. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  17788. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  17789. if (!this._indicesForCamera[cameraName]) {
  17790. this._indicesForCamera[cameraName] = [];
  17791. }
  17792. this._indicesForCamera[cameraName].push(index);
  17793. if (this._cameras.indexOf(camera) === -1) {
  17794. this._cameras[cameraName] = camera;
  17795. }
  17796. for (var passName in this._renderPasses) {
  17797. this._renderPasses[passName]._incRefCount();
  17798. }
  17799. }
  17800. this._linkParameters();
  17801. };
  17802. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  17803. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17804. for (var i = 0; i < _cam.length; i++) {
  17805. var camera = _cam[i];
  17806. var cameraName = camera.name;
  17807. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  17808. var index = this._cameras.indexOf(cameraName);
  17809. this._indicesForCamera.splice(index, 1);
  17810. this._cameras.splice(index, 1);
  17811. for (var passName in this._renderPasses) {
  17812. this._renderPasses[passName]._decRefCount();
  17813. }
  17814. }
  17815. };
  17816. PostProcessRenderEffect.prototype._enable = function (cameras) {
  17817. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17818. for (var i = 0; i < _cam.length; i++) {
  17819. var camera = _cam[i];
  17820. var cameraName = camera.name;
  17821. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  17822. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  17823. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  17824. }
  17825. }
  17826. for (var passName in this._renderPasses) {
  17827. this._renderPasses[passName]._incRefCount();
  17828. }
  17829. }
  17830. };
  17831. PostProcessRenderEffect.prototype._disable = function (cameras) {
  17832. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17833. for (var i = 0; i < _cam.length; i++) {
  17834. var camera = _cam[i];
  17835. var cameraName = camera.Name;
  17836. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  17837. for (var passName in this._renderPasses) {
  17838. this._renderPasses[passName]._decRefCount();
  17839. }
  17840. }
  17841. };
  17842. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  17843. if (this._singleInstance) {
  17844. return this._postProcesses[0];
  17845. } else {
  17846. return this._postProcesses[camera.name];
  17847. }
  17848. };
  17849. PostProcessRenderEffect.prototype._linkParameters = function () {
  17850. var _this = this;
  17851. for (var index in this._postProcesses) {
  17852. if (this.applyParameters) {
  17853. this.applyParameters(this._postProcesses[index]);
  17854. }
  17855. this._postProcesses[index].onBeforeRender = function (effect) {
  17856. _this._linkTextures(effect);
  17857. };
  17858. }
  17859. };
  17860. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  17861. for (var renderPassName in this._renderPasses) {
  17862. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  17863. }
  17864. for (var renderEffectName in this._renderEffectAsPasses) {
  17865. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  17866. }
  17867. };
  17868. return PostProcessRenderEffect;
  17869. })();
  17870. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  17871. })(BABYLON || (BABYLON = {}));
  17872. var BABYLON;
  17873. (function (BABYLON) {
  17874. var PostProcessRenderPipeline = (function () {
  17875. function PostProcessRenderPipeline(engine, name) {
  17876. this._engine = engine;
  17877. this._name = name;
  17878. this._renderEffects = [];
  17879. this._renderEffectsForIsolatedPass = [];
  17880. this._cameras = [];
  17881. }
  17882. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  17883. this._renderEffects[renderEffect._name] = renderEffect;
  17884. };
  17885. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  17886. var renderEffects = this._renderEffects[renderEffectName];
  17887. if (!renderEffects) {
  17888. return;
  17889. }
  17890. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17891. };
  17892. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  17893. var renderEffects = this._renderEffects[renderEffectName];
  17894. if (!renderEffects) {
  17895. return;
  17896. }
  17897. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  17898. };
  17899. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  17900. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17901. var indicesToDelete = [];
  17902. for (var i = 0; i < _cam.length; i++) {
  17903. var camera = _cam[i];
  17904. var cameraName = camera.name;
  17905. if (this._cameras.indexOf(camera) === -1) {
  17906. this._cameras[cameraName] = camera;
  17907. } else if (unique) {
  17908. indicesToDelete.push(i);
  17909. }
  17910. }
  17911. for (var i = 0; i < indicesToDelete.length; i++) {
  17912. cameras.splice(indicesToDelete[i], 1);
  17913. }
  17914. for (var renderEffectName in this._renderEffects) {
  17915. this._renderEffects[renderEffectName]._attachCameras(_cam);
  17916. }
  17917. };
  17918. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  17919. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17920. for (var renderEffectName in this._renderEffects) {
  17921. this._renderEffects[renderEffectName]._detachCameras(_cam);
  17922. }
  17923. for (var i = 0; i < _cam.length; i++) {
  17924. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  17925. }
  17926. };
  17927. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  17928. var _this = this;
  17929. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17930. var pass = null;
  17931. for (var renderEffectName in this._renderEffects) {
  17932. pass = this._renderEffects[renderEffectName].getPass(passName);
  17933. if (pass != null) {
  17934. break;
  17935. }
  17936. }
  17937. if (pass === null) {
  17938. return;
  17939. }
  17940. for (var renderEffectName in this._renderEffects) {
  17941. this._renderEffects[renderEffectName]._disable(_cam);
  17942. }
  17943. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  17944. for (var i = 0; i < _cam.length; i++) {
  17945. var camera = _cam[i];
  17946. var cameraName = camera.name;
  17947. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  17948. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  17949. });
  17950. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  17951. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  17952. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  17953. }
  17954. };
  17955. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  17956. var _this = this;
  17957. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17958. for (var i = 0; i < _cam.length; i++) {
  17959. var camera = _cam[i];
  17960. var cameraName = camera.name;
  17961. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  17962. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  17963. });
  17964. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  17965. }
  17966. for (var renderEffectName in this._renderEffects) {
  17967. this._renderEffects[renderEffectName]._enable(_cam);
  17968. }
  17969. };
  17970. PostProcessRenderPipeline.prototype._update = function () {
  17971. for (var renderEffectName in this._renderEffects) {
  17972. this._renderEffects[renderEffectName]._update();
  17973. }
  17974. for (var i = 0; i < this._cameras.length; i++) {
  17975. var cameraName = this._cameras[i].name;
  17976. if (this._renderEffectsForIsolatedPass[cameraName]) {
  17977. this._renderEffectsForIsolatedPass[cameraName]._update();
  17978. }
  17979. }
  17980. };
  17981. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  17982. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  17983. return PostProcessRenderPipeline;
  17984. })();
  17985. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  17986. })(BABYLON || (BABYLON = {}));
  17987. var BABYLON;
  17988. (function (BABYLON) {
  17989. var PostProcessRenderPipelineManager = (function () {
  17990. function PostProcessRenderPipelineManager() {
  17991. this._renderPipelines = new Array();
  17992. }
  17993. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  17994. this._renderPipelines[renderPipeline._name] = renderPipeline;
  17995. };
  17996. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  17997. var renderPipeline = this._renderPipelines[renderPipelineName];
  17998. if (!renderPipeline) {
  17999. return;
  18000. }
  18001. renderPipeline._attachCameras(cameras, unique);
  18002. };
  18003. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  18004. var renderPipeline = this._renderPipelines[renderPipelineName];
  18005. if (!renderPipeline) {
  18006. return;
  18007. }
  18008. renderPipeline._detachCameras(cameras);
  18009. };
  18010. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  18011. var renderPipeline = this._renderPipelines[renderPipelineName];
  18012. if (!renderPipeline) {
  18013. return;
  18014. }
  18015. renderPipeline._enableEffect(renderEffectName, cameras);
  18016. };
  18017. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  18018. var renderPipeline = this._renderPipelines[renderPipelineName];
  18019. if (!renderPipeline) {
  18020. return;
  18021. }
  18022. renderPipeline._disableEffect(renderEffectName, cameras);
  18023. };
  18024. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  18025. var renderPipeline = this._renderPipelines[renderPipelineName];
  18026. if (!renderPipeline) {
  18027. return;
  18028. }
  18029. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  18030. };
  18031. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  18032. var renderPipeline = this._renderPipelines[renderPipelineName];
  18033. if (!renderPipeline) {
  18034. return;
  18035. }
  18036. renderPipeline._disableDisplayOnlyPass(cameras);
  18037. };
  18038. PostProcessRenderPipelineManager.prototype.update = function () {
  18039. for (var renderPipelineName in this._renderPipelines) {
  18040. this._renderPipelines[renderPipelineName]._update();
  18041. }
  18042. };
  18043. return PostProcessRenderPipelineManager;
  18044. })();
  18045. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  18046. })(BABYLON || (BABYLON = {}));
  18047. var __extends = this.__extends || function (d, b) {
  18048. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18049. function __() { this.constructor = d; }
  18050. __.prototype = b.prototype;
  18051. d.prototype = new __();
  18052. };
  18053. var BABYLON;
  18054. (function (BABYLON) {
  18055. var DisplayPassPostProcess = (function (_super) {
  18056. __extends(DisplayPassPostProcess, _super);
  18057. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18058. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  18059. }
  18060. return DisplayPassPostProcess;
  18061. })(BABYLON.PostProcess);
  18062. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  18063. })(BABYLON || (BABYLON = {}));
  18064. var BABYLON;
  18065. (function (BABYLON) {
  18066. var BoundingBoxRenderer = (function () {
  18067. function BoundingBoxRenderer(scene) {
  18068. this.frontColor = new BABYLON.Color3(1, 1, 1);
  18069. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  18070. this.showBackLines = true;
  18071. this.renderList = new BABYLON.SmartArray(32);
  18072. this._scene = scene;
  18073. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  18074. attributes: ["position"],
  18075. uniforms: ["worldViewProjection", "color"]
  18076. });
  18077. var engine = this._scene.getEngine();
  18078. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  18079. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  18080. 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]);
  18081. }
  18082. BoundingBoxRenderer.prototype.reset = function () {
  18083. this.renderList.reset();
  18084. };
  18085. BoundingBoxRenderer.prototype.render = function () {
  18086. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  18087. return;
  18088. }
  18089. var engine = this._scene.getEngine();
  18090. engine.setDepthWrite(false);
  18091. this._colorShader._preBind();
  18092. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  18093. var boundingBox = this.renderList.data[boundingBoxIndex];
  18094. var min = boundingBox.minimum;
  18095. var max = boundingBox.maximum;
  18096. var diff = max.subtract(min);
  18097. var median = min.add(diff.scale(0.5));
  18098. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  18099. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  18100. if (this.showBackLines) {
  18101. engine.setDepthFunctionToGreaterOrEqual();
  18102. this._colorShader.setColor4("color", this.backColor.toColor4());
  18103. this._colorShader.bind(worldMatrix);
  18104. engine.draw(false, 0, 24);
  18105. }
  18106. engine.setDepthFunctionToLess();
  18107. this._colorShader.setColor4("color", this.frontColor.toColor4());
  18108. this._colorShader.bind(worldMatrix);
  18109. engine.draw(false, 0, 24);
  18110. }
  18111. this._colorShader.unbind();
  18112. engine.setDepthFunctionToLessOrEqual();
  18113. engine.setDepthWrite(true);
  18114. };
  18115. BoundingBoxRenderer.prototype.dispose = function () {
  18116. this._colorShader.dispose();
  18117. this._vb.dispose();
  18118. this._scene.getEngine()._releaseBuffer(this._ib);
  18119. };
  18120. return BoundingBoxRenderer;
  18121. })();
  18122. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  18123. })(BABYLON || (BABYLON = {}));
  18124. /**
  18125. * Based on jsTGALoader - Javascript loader for TGA file
  18126. * By Vincent Thibault
  18127. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  18128. */
  18129. var BABYLON;
  18130. (function (BABYLON) {
  18131. (function (Internals) {
  18132. var TGATools = (function () {
  18133. function TGATools() {
  18134. }
  18135. TGATools.GetTGAHeader = function (data) {
  18136. var offset = 0;
  18137. var header = {
  18138. id_length: data[offset++],
  18139. colormap_type: data[offset++],
  18140. image_type: data[offset++],
  18141. colormap_index: data[offset++] | data[offset++] << 8,
  18142. colormap_length: data[offset++] | data[offset++] << 8,
  18143. colormap_size: data[offset++],
  18144. origin: [
  18145. data[offset++] | data[offset++] << 8,
  18146. data[offset++] | data[offset++] << 8
  18147. ],
  18148. width: data[offset++] | data[offset++] << 8,
  18149. height: data[offset++] | data[offset++] << 8,
  18150. pixel_size: data[offset++],
  18151. flags: data[offset++]
  18152. };
  18153. return header;
  18154. };
  18155. TGATools.UploadContent = function (gl, data) {
  18156. if (data.length < 19) {
  18157. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  18158. return;
  18159. }
  18160. var offset = 18;
  18161. var header = TGATools.GetTGAHeader(data);
  18162. if (header.id_length + offset > data.length) {
  18163. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  18164. return;
  18165. }
  18166. offset += header.id_length;
  18167. var use_rle = false;
  18168. var use_pal = false;
  18169. var use_rgb = false;
  18170. var use_grey = false;
  18171. switch (header.image_type) {
  18172. case TGATools._TYPE_RLE_INDEXED:
  18173. use_rle = true;
  18174. case TGATools._TYPE_INDEXED:
  18175. use_pal = true;
  18176. break;
  18177. case TGATools._TYPE_RLE_RGB:
  18178. use_rle = true;
  18179. case TGATools._TYPE_RGB:
  18180. use_rgb = true;
  18181. break;
  18182. case TGATools._TYPE_RLE_GREY:
  18183. use_rle = true;
  18184. case TGATools._TYPE_GREY:
  18185. use_grey = true;
  18186. break;
  18187. }
  18188. var pixel_data;
  18189. var numAlphaBits = header.flags & 0xf;
  18190. var pixel_size = header.pixel_size >> 3;
  18191. var pixel_total = header.width * header.height * pixel_size;
  18192. var palettes;
  18193. if (use_pal) {
  18194. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  18195. }
  18196. if (use_rle) {
  18197. pixel_data = new Uint8Array(pixel_total);
  18198. var c, count, i;
  18199. var localOffset = 0;
  18200. var pixels = new Uint8Array(pixel_size);
  18201. while (offset < pixel_total && localOffset < pixel_total) {
  18202. c = data[offset++];
  18203. count = (c & 0x7f) + 1;
  18204. if (c & 0x80) {
  18205. for (i = 0; i < pixel_size; ++i) {
  18206. pixels[i] = data[offset++];
  18207. }
  18208. for (i = 0; i < count; ++i) {
  18209. pixel_data.set(pixels, localOffset + i * pixel_size);
  18210. }
  18211. localOffset += pixel_size * count;
  18212. } else {
  18213. count *= pixel_size;
  18214. for (i = 0; i < count; ++i) {
  18215. pixel_data[localOffset + i] = data[offset++];
  18216. }
  18217. localOffset += count;
  18218. }
  18219. }
  18220. } else {
  18221. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  18222. }
  18223. var x_start, y_start, x_step, y_step, y_end, x_end;
  18224. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  18225. default:
  18226. case TGATools._ORIGIN_UL:
  18227. x_start = 0;
  18228. x_step = 1;
  18229. x_end = header.width;
  18230. y_start = 0;
  18231. y_step = 1;
  18232. y_end = header.height;
  18233. break;
  18234. case TGATools._ORIGIN_BL:
  18235. x_start = 0;
  18236. x_step = 1;
  18237. x_end = header.width;
  18238. y_start = header.height - 1;
  18239. y_step = -1;
  18240. y_end = -1;
  18241. break;
  18242. case TGATools._ORIGIN_UR:
  18243. x_start = header.width - 1;
  18244. x_step = -1;
  18245. x_end = -1;
  18246. y_start = 0;
  18247. y_step = 1;
  18248. y_end = header.height;
  18249. break;
  18250. case TGATools._ORIGIN_BR:
  18251. x_start = header.width - 1;
  18252. x_step = -1;
  18253. x_end = -1;
  18254. y_start = header.height - 1;
  18255. y_step = -1;
  18256. y_end = -1;
  18257. break;
  18258. }
  18259. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  18260. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  18261. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  18262. };
  18263. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18264. var image = pixel_data, colormap = palettes;
  18265. var width = header.width, height = header.height;
  18266. var color, i = 0, x, y;
  18267. var imageData = new Uint8Array(width * height * 4);
  18268. for (y = y_start; y !== y_end; y += y_step) {
  18269. for (x = x_start; x !== x_end; x += x_step, i++) {
  18270. color = image[i];
  18271. imageData[(x + width * y) * 4 + 3] = 255;
  18272. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  18273. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  18274. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  18275. }
  18276. }
  18277. return imageData;
  18278. };
  18279. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18280. var image = pixel_data;
  18281. var width = header.width, height = header.height;
  18282. var color, i = 0, x, y;
  18283. var imageData = new Uint8Array(width * height * 4);
  18284. for (y = y_start; y !== y_end; y += y_step) {
  18285. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  18286. color = image[i + 0] + (image[i + 1] << 8);
  18287. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  18288. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  18289. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  18290. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  18291. }
  18292. }
  18293. return imageData;
  18294. };
  18295. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18296. var image = pixel_data;
  18297. var width = header.width, height = header.height;
  18298. var i = 0, x, y;
  18299. var imageData = new Uint8Array(width * height * 4);
  18300. for (y = y_start; y !== y_end; y += y_step) {
  18301. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  18302. imageData[(x + width * y) * 4 + 3] = 255;
  18303. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  18304. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  18305. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  18306. }
  18307. }
  18308. return imageData;
  18309. };
  18310. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18311. var image = pixel_data;
  18312. var width = header.width, height = header.height;
  18313. var i = 0, x, y;
  18314. var imageData = new Uint8Array(width * height * 4);
  18315. for (y = y_start; y !== y_end; y += y_step) {
  18316. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  18317. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  18318. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  18319. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  18320. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  18321. }
  18322. }
  18323. return imageData;
  18324. };
  18325. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18326. var image = pixel_data;
  18327. var width = header.width, height = header.height;
  18328. var color, i = 0, x, y;
  18329. var imageData = new Uint8Array(width * height * 4);
  18330. for (y = y_start; y !== y_end; y += y_step) {
  18331. for (x = x_start; x !== x_end; x += x_step, i++) {
  18332. color = image[i];
  18333. imageData[(x + width * y) * 4 + 0] = color;
  18334. imageData[(x + width * y) * 4 + 1] = color;
  18335. imageData[(x + width * y) * 4 + 2] = color;
  18336. imageData[(x + width * y) * 4 + 3] = 255;
  18337. }
  18338. }
  18339. return imageData;
  18340. };
  18341. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18342. var image = pixel_data;
  18343. var width = header.width, height = header.height;
  18344. var i = 0, x, y;
  18345. var imageData = new Uint8Array(width * height * 4);
  18346. for (y = y_start; y !== y_end; y += y_step) {
  18347. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  18348. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  18349. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  18350. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  18351. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  18352. }
  18353. }
  18354. return imageData;
  18355. };
  18356. TGATools._TYPE_NO_DATA = 0;
  18357. TGATools._TYPE_INDEXED = 1;
  18358. TGATools._TYPE_RGB = 2;
  18359. TGATools._TYPE_GREY = 3;
  18360. TGATools._TYPE_RLE_INDEXED = 9;
  18361. TGATools._TYPE_RLE_RGB = 10;
  18362. TGATools._TYPE_RLE_GREY = 11;
  18363. TGATools._ORIGIN_MASK = 0x30;
  18364. TGATools._ORIGIN_SHIFT = 0x04;
  18365. TGATools._ORIGIN_BL = 0x00;
  18366. TGATools._ORIGIN_BR = 0x01;
  18367. TGATools._ORIGIN_UL = 0x02;
  18368. TGATools._ORIGIN_UR = 0x03;
  18369. return TGATools;
  18370. })();
  18371. Internals.TGATools = TGATools;
  18372. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18373. var Internals = BABYLON.Internals;
  18374. })(BABYLON || (BABYLON = {}));
  18375. var BABYLON;
  18376. (function (BABYLON) {
  18377. (function (Internals) {
  18378. var DDS_MAGIC = 0x20534444;
  18379. 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;
  18380. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  18381. 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;
  18382. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  18383. function FourCCToInt32(value) {
  18384. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  18385. }
  18386. function Int32ToFourCC(value) {
  18387. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  18388. }
  18389. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  18390. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  18391. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  18392. var headerLengthInt = 31;
  18393. var off_magic = 0;
  18394. var off_size = 1;
  18395. var off_flags = 2;
  18396. var off_height = 3;
  18397. var off_width = 4;
  18398. var off_mipmapCount = 7;
  18399. var off_pfFlags = 20;
  18400. var off_pfFourCC = 21;
  18401. var off_RGBbpp = 22;
  18402. var off_RMask = 23;
  18403. var off_GMask = 24;
  18404. var off_BMask = 25;
  18405. var off_AMask = 26;
  18406. var off_caps1 = 27;
  18407. var off_caps2 = 28;
  18408. ;
  18409. var DDSTools = (function () {
  18410. function DDSTools() {
  18411. }
  18412. DDSTools.GetDDSInfo = function (arrayBuffer) {
  18413. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  18414. var mipmapCount = 1;
  18415. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  18416. mipmapCount = Math.max(1, header[off_mipmapCount]);
  18417. }
  18418. return {
  18419. width: header[off_width],
  18420. height: header[off_height],
  18421. mipmapCount: mipmapCount,
  18422. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  18423. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  18424. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  18425. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  18426. };
  18427. };
  18428. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  18429. var byteArray = new Uint8Array(dataLength);
  18430. var srcData = new Uint8Array(arrayBuffer);
  18431. var index = 0;
  18432. for (var y = height - 1; y >= 0; y--) {
  18433. for (var x = 0; x < width; x++) {
  18434. var srcPos = dataOffset + (x + y * width) * 4;
  18435. byteArray[index + 2] = srcData[srcPos];
  18436. byteArray[index + 1] = srcData[srcPos + 1];
  18437. byteArray[index] = srcData[srcPos + 2];
  18438. byteArray[index + 3] = srcData[srcPos + 3];
  18439. index += 4;
  18440. }
  18441. }
  18442. return byteArray;
  18443. };
  18444. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  18445. var byteArray = new Uint8Array(dataLength);
  18446. var srcData = new Uint8Array(arrayBuffer);
  18447. var index = 0;
  18448. for (var y = height - 1; y >= 0; y--) {
  18449. for (var x = 0; x < width; x++) {
  18450. var srcPos = dataOffset + (x + y * width) * 3;
  18451. byteArray[index + 2] = srcData[srcPos];
  18452. byteArray[index + 1] = srcData[srcPos + 1];
  18453. byteArray[index] = srcData[srcPos + 2];
  18454. index += 3;
  18455. }
  18456. }
  18457. return byteArray;
  18458. };
  18459. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  18460. var byteArray = new Uint8Array(dataLength);
  18461. var srcData = new Uint8Array(arrayBuffer);
  18462. var index = 0;
  18463. for (var y = height - 1; y >= 0; y--) {
  18464. for (var x = 0; x < width; x++) {
  18465. var srcPos = dataOffset + (x + y * width);
  18466. byteArray[index] = srcData[srcPos];
  18467. index++;
  18468. }
  18469. }
  18470. return byteArray;
  18471. };
  18472. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  18473. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  18474. if (header[off_magic] != DDS_MAGIC) {
  18475. BABYLON.Tools.Error("Invalid magic number in DDS header");
  18476. return;
  18477. }
  18478. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  18479. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  18480. return;
  18481. }
  18482. if (info.isFourCC) {
  18483. fourCC = header[off_pfFourCC];
  18484. switch (fourCC) {
  18485. case FOURCC_DXT1:
  18486. blockBytes = 8;
  18487. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  18488. break;
  18489. case FOURCC_DXT3:
  18490. blockBytes = 16;
  18491. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  18492. break;
  18493. case FOURCC_DXT5:
  18494. blockBytes = 16;
  18495. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  18496. break;
  18497. default:
  18498. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  18499. return;
  18500. }
  18501. }
  18502. mipmapCount = 1;
  18503. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  18504. mipmapCount = Math.max(1, header[off_mipmapCount]);
  18505. }
  18506. var bpp = header[off_RGBbpp];
  18507. for (var face = 0; face < faces; face++) {
  18508. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  18509. width = header[off_width];
  18510. height = header[off_height];
  18511. dataOffset = header[off_size] + 4;
  18512. for (i = 0; i < mipmapCount; ++i) {
  18513. if (info.isRGB) {
  18514. if (bpp == 24) {
  18515. dataLength = width * height * 3;
  18516. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  18517. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  18518. } else {
  18519. dataLength = width * height * 4;
  18520. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  18521. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  18522. }
  18523. } else if (info.isLuminance) {
  18524. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  18525. var unpaddedRowSize = width;
  18526. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  18527. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  18528. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  18529. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  18530. } else {
  18531. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  18532. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  18533. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  18534. }
  18535. dataOffset += dataLength;
  18536. width *= 0.5;
  18537. height *= 0.5;
  18538. width = Math.max(1.0, width);
  18539. height = Math.max(1.0, height);
  18540. }
  18541. }
  18542. };
  18543. return DDSTools;
  18544. })();
  18545. Internals.DDSTools = DDSTools;
  18546. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18547. var Internals = BABYLON.Internals;
  18548. })(BABYLON || (BABYLON = {}));
  18549. var BABYLON;
  18550. (function (BABYLON) {
  18551. var SmartArray = (function () {
  18552. function SmartArray(capacity) {
  18553. this.length = 0;
  18554. this._duplicateId = 0;
  18555. this.data = new Array(capacity);
  18556. this._id = SmartArray._GlobalId++;
  18557. }
  18558. SmartArray.prototype.push = function (value) {
  18559. this.data[this.length++] = value;
  18560. if (this.length > this.data.length) {
  18561. this.data.length *= 2;
  18562. }
  18563. if (!value.__smartArrayFlags) {
  18564. value.__smartArrayFlags = {};
  18565. }
  18566. value.__smartArrayFlags[this._id] = this._duplicateId;
  18567. };
  18568. SmartArray.prototype.pushNoDuplicate = function (value) {
  18569. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  18570. return;
  18571. }
  18572. this.push(value);
  18573. };
  18574. SmartArray.prototype.sort = function (compareFn) {
  18575. this.data.sort(compareFn);
  18576. };
  18577. SmartArray.prototype.reset = function () {
  18578. this.length = 0;
  18579. this._duplicateId++;
  18580. };
  18581. SmartArray.prototype.concat = function (array) {
  18582. if (array.length === 0) {
  18583. return;
  18584. }
  18585. if (this.length + array.length > this.data.length) {
  18586. this.data.length = (this.length + array.length) * 2;
  18587. }
  18588. for (var index = 0; index < array.length; index++) {
  18589. this.data[this.length++] = (array.data || array)[index];
  18590. }
  18591. };
  18592. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  18593. if (array.length === 0) {
  18594. return;
  18595. }
  18596. if (this.length + array.length > this.data.length) {
  18597. this.data.length = (this.length + array.length) * 2;
  18598. }
  18599. for (var index = 0; index < array.length; index++) {
  18600. var item = (array.data || array)[index];
  18601. this.pushNoDuplicate(item);
  18602. }
  18603. };
  18604. SmartArray.prototype.indexOf = function (value) {
  18605. var position = this.data.indexOf(value);
  18606. if (position >= this.length) {
  18607. return -1;
  18608. }
  18609. return position;
  18610. };
  18611. SmartArray._GlobalId = 0;
  18612. return SmartArray;
  18613. })();
  18614. BABYLON.SmartArray = SmartArray;
  18615. })(BABYLON || (BABYLON = {}));
  18616. var BABYLON;
  18617. (function (BABYLON) {
  18618. var CannonJSPlugin = (function () {
  18619. function CannonJSPlugin() {
  18620. this._registeredMeshes = [];
  18621. this._physicsMaterials = [];
  18622. this.updateBodyPosition = function (mesh) {
  18623. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18624. var registeredMesh = this._registeredMeshes[index];
  18625. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18626. var body = registeredMesh.body;
  18627. var center = mesh.getBoundingInfo().boundingBox.center;
  18628. body.position.set(center.x, center.z, center.y);
  18629. body.quaternion.x = mesh.rotationQuaternion.x;
  18630. body.quaternion.z = mesh.rotationQuaternion.y;
  18631. body.quaternion.y = mesh.rotationQuaternion.z;
  18632. body.quaternion.w = -mesh.rotationQuaternion.w;
  18633. return;
  18634. }
  18635. }
  18636. };
  18637. }
  18638. CannonJSPlugin.prototype.initialize = function (iterations) {
  18639. if (typeof iterations === "undefined") { iterations = 10; }
  18640. this._world = new CANNON.World();
  18641. this._world.broadphase = new CANNON.NaiveBroadphase();
  18642. this._world.solver.iterations = iterations;
  18643. };
  18644. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  18645. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  18646. };
  18647. CannonJSPlugin.prototype.runOneStep = function (delta) {
  18648. this._world.step(delta);
  18649. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18650. var registeredMesh = this._registeredMeshes[index];
  18651. if (registeredMesh.isChild) {
  18652. continue;
  18653. }
  18654. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  18655. var deltaPos = registeredMesh.delta;
  18656. if (deltaPos) {
  18657. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  18658. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  18659. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  18660. } else {
  18661. registeredMesh.mesh.position.x = bodyX;
  18662. registeredMesh.mesh.position.y = bodyZ;
  18663. registeredMesh.mesh.position.z = bodyY;
  18664. }
  18665. if (!registeredMesh.mesh.rotationQuaternion) {
  18666. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18667. }
  18668. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  18669. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  18670. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  18671. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  18672. }
  18673. };
  18674. CannonJSPlugin.prototype.setGravity = function (gravity) {
  18675. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  18676. };
  18677. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  18678. this.unregisterMesh(mesh);
  18679. mesh.computeWorldMatrix(true);
  18680. switch (impostor) {
  18681. case BABYLON.PhysicsEngine.SphereImpostor:
  18682. var bbox = mesh.getBoundingInfo().boundingBox;
  18683. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18684. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18685. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18686. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  18687. case BABYLON.PhysicsEngine.BoxImpostor:
  18688. bbox = mesh.getBoundingInfo().boundingBox;
  18689. var min = bbox.minimumWorld;
  18690. var max = bbox.maximumWorld;
  18691. var box = max.subtract(min).scale(0.5);
  18692. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  18693. case BABYLON.PhysicsEngine.PlaneImpostor:
  18694. return this._createPlane(mesh, options);
  18695. case BABYLON.PhysicsEngine.MeshImpostor:
  18696. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18697. var rawFaces = mesh.getIndices();
  18698. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  18699. }
  18700. return null;
  18701. };
  18702. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  18703. var shape = new CANNON.Sphere(radius);
  18704. if (!options) {
  18705. return shape;
  18706. }
  18707. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18708. };
  18709. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  18710. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  18711. if (!options) {
  18712. return shape;
  18713. }
  18714. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18715. };
  18716. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  18717. var shape = new CANNON.Plane();
  18718. if (!options) {
  18719. return shape;
  18720. }
  18721. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18722. };
  18723. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  18724. var verts = [], faces = [];
  18725. mesh.computeWorldMatrix(true);
  18726. for (var i = 0; i < rawVerts.length; i += 3) {
  18727. var transformed = BABYLON.Vector3.Zero();
  18728. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  18729. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  18730. }
  18731. for (var j = 0; j < rawFaces.length; j += 3) {
  18732. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  18733. }
  18734. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  18735. if (!options) {
  18736. return shape;
  18737. }
  18738. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18739. };
  18740. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  18741. var index;
  18742. var mat;
  18743. for (index = 0; index < this._physicsMaterials.length; index++) {
  18744. mat = this._physicsMaterials[index];
  18745. if (mat.friction === friction && mat.restitution === restitution) {
  18746. return mat;
  18747. }
  18748. }
  18749. var currentMat = new CANNON.Material();
  18750. currentMat.friction = friction;
  18751. currentMat.restitution = restitution;
  18752. this._physicsMaterials.push(currentMat);
  18753. for (index = 0; index < this._physicsMaterials.length; index++) {
  18754. mat = this._physicsMaterials[index];
  18755. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  18756. contactMaterial.contactEquationStiffness = 1e10;
  18757. contactMaterial.contactEquationRegularizationTime = 10;
  18758. this._world.addContactMaterial(contactMaterial);
  18759. }
  18760. return currentMat;
  18761. };
  18762. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  18763. var initialRotation = null;
  18764. if (mesh.rotationQuaternion) {
  18765. initialRotation = mesh.rotationQuaternion.clone();
  18766. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18767. }
  18768. var bbox = mesh.getBoundingInfo().boundingBox;
  18769. var deltaPosition = mesh.position.subtract(bbox.center);
  18770. var material = this._addMaterial(friction, restitution);
  18771. var body = new CANNON.RigidBody(mass, shape, material);
  18772. if (initialRotation) {
  18773. body.quaternion.x = initialRotation.x;
  18774. body.quaternion.z = initialRotation.y;
  18775. body.quaternion.y = initialRotation.z;
  18776. body.quaternion.w = -initialRotation.w;
  18777. }
  18778. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  18779. this._world.add(body);
  18780. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  18781. return body;
  18782. };
  18783. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18784. var compoundShape = new CANNON.Compound();
  18785. for (var index = 0; index < parts.length; index++) {
  18786. var mesh = parts[index].mesh;
  18787. var shape = this.registerMesh(mesh, parts[index].impostor);
  18788. if (index == 0) {
  18789. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  18790. } else {
  18791. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  18792. }
  18793. }
  18794. var initialMesh = parts[0].mesh;
  18795. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  18796. body.parts = parts;
  18797. return body;
  18798. };
  18799. CannonJSPlugin.prototype._unbindBody = function (body) {
  18800. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18801. var registeredMesh = this._registeredMeshes[index];
  18802. if (registeredMesh.body === body) {
  18803. registeredMesh.body = null;
  18804. registeredMesh.delta = 0;
  18805. }
  18806. }
  18807. };
  18808. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  18809. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18810. var registeredMesh = this._registeredMeshes[index];
  18811. if (registeredMesh.mesh === mesh) {
  18812. if (registeredMesh.body) {
  18813. this._world.remove(registeredMesh.body);
  18814. this._unbindBody(registeredMesh.body);
  18815. }
  18816. this._registeredMeshes.splice(index, 1);
  18817. return;
  18818. }
  18819. }
  18820. };
  18821. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  18822. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  18823. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  18824. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18825. var registeredMesh = this._registeredMeshes[index];
  18826. if (registeredMesh.mesh === mesh) {
  18827. registeredMesh.body.applyImpulse(impulse, worldPoint);
  18828. return;
  18829. }
  18830. }
  18831. };
  18832. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  18833. var body1 = null, body2 = null;
  18834. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18835. var registeredMesh = this._registeredMeshes[index];
  18836. if (registeredMesh.mesh === mesh1) {
  18837. body1 = registeredMesh.body;
  18838. } else if (registeredMesh.mesh === mesh2) {
  18839. body2 = registeredMesh.body;
  18840. }
  18841. }
  18842. if (!body1 || !body2) {
  18843. return false;
  18844. }
  18845. 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));
  18846. this._world.addConstraint(constraint);
  18847. return true;
  18848. };
  18849. CannonJSPlugin.prototype.dispose = function () {
  18850. while (this._registeredMeshes.length) {
  18851. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18852. }
  18853. };
  18854. CannonJSPlugin.prototype.isSupported = function () {
  18855. return window.CANNON !== undefined;
  18856. };
  18857. return CannonJSPlugin;
  18858. })();
  18859. BABYLON.CannonJSPlugin = CannonJSPlugin;
  18860. })(BABYLON || (BABYLON = {}));
  18861. var __extends = this.__extends || function (d, b) {
  18862. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18863. function __() { this.constructor = d; }
  18864. __.prototype = b.prototype;
  18865. d.prototype = new __();
  18866. };
  18867. var BABYLON;
  18868. (function (BABYLON) {
  18869. var Condition = (function () {
  18870. function Condition(actionManager) {
  18871. this._actionManager = actionManager;
  18872. }
  18873. Condition.prototype.isValid = function () {
  18874. return true;
  18875. };
  18876. Condition.prototype._getProperty = function (propertyPath) {
  18877. return this._actionManager._getProperty(propertyPath);
  18878. };
  18879. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  18880. return this._actionManager._getEffectiveTarget(target, propertyPath);
  18881. };
  18882. return Condition;
  18883. })();
  18884. BABYLON.Condition = Condition;
  18885. var ValueCondition = (function (_super) {
  18886. __extends(ValueCondition, _super);
  18887. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  18888. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  18889. _super.call(this, actionManager);
  18890. this.propertyPath = propertyPath;
  18891. this.value = value;
  18892. this.operator = operator;
  18893. this._target = this._getEffectiveTarget(target, this.propertyPath);
  18894. this._property = this._getProperty(this.propertyPath);
  18895. }
  18896. Object.defineProperty(ValueCondition, "IsEqual", {
  18897. get: function () {
  18898. return ValueCondition._IsEqual;
  18899. },
  18900. enumerable: true,
  18901. configurable: true
  18902. });
  18903. Object.defineProperty(ValueCondition, "IsDifferent", {
  18904. get: function () {
  18905. return ValueCondition._IsDifferent;
  18906. },
  18907. enumerable: true,
  18908. configurable: true
  18909. });
  18910. Object.defineProperty(ValueCondition, "IsGreater", {
  18911. get: function () {
  18912. return ValueCondition._IsGreater;
  18913. },
  18914. enumerable: true,
  18915. configurable: true
  18916. });
  18917. Object.defineProperty(ValueCondition, "IsLesser", {
  18918. get: function () {
  18919. return ValueCondition._IsLesser;
  18920. },
  18921. enumerable: true,
  18922. configurable: true
  18923. });
  18924. ValueCondition.prototype.isValid = function () {
  18925. switch (this.operator) {
  18926. case ValueCondition.IsGreater:
  18927. return this._target[this._property] > this.value;
  18928. case ValueCondition.IsLesser:
  18929. return this._target[this._property] < this.value;
  18930. case ValueCondition.IsEqual:
  18931. case ValueCondition.IsDifferent:
  18932. var check;
  18933. if (this.value.equals) {
  18934. check = this.value.equals(this._target[this._property]);
  18935. } else {
  18936. check = this.value === this._target[this._property];
  18937. }
  18938. return this.operator === ValueCondition.IsEqual ? check : !check;
  18939. }
  18940. return false;
  18941. };
  18942. ValueCondition._IsEqual = 0;
  18943. ValueCondition._IsDifferent = 1;
  18944. ValueCondition._IsGreater = 2;
  18945. ValueCondition._IsLesser = 3;
  18946. return ValueCondition;
  18947. })(Condition);
  18948. BABYLON.ValueCondition = ValueCondition;
  18949. var PredicateCondition = (function (_super) {
  18950. __extends(PredicateCondition, _super);
  18951. function PredicateCondition(actionManager, predicate) {
  18952. _super.call(this, actionManager);
  18953. this.predicate = predicate;
  18954. }
  18955. PredicateCondition.prototype.isValid = function () {
  18956. return this.predicate();
  18957. };
  18958. return PredicateCondition;
  18959. })(Condition);
  18960. BABYLON.PredicateCondition = PredicateCondition;
  18961. var StateCondition = (function (_super) {
  18962. __extends(StateCondition, _super);
  18963. function StateCondition(actionManager, target, value) {
  18964. _super.call(this, actionManager);
  18965. this.value = value;
  18966. this._target = target;
  18967. }
  18968. StateCondition.prototype.isValid = function () {
  18969. return this._target.state === this.value;
  18970. };
  18971. return StateCondition;
  18972. })(Condition);
  18973. BABYLON.StateCondition = StateCondition;
  18974. })(BABYLON || (BABYLON = {}));
  18975. var BABYLON;
  18976. (function (BABYLON) {
  18977. var Action = (function () {
  18978. function Action(triggerOptions, condition) {
  18979. this.triggerOptions = triggerOptions;
  18980. if (triggerOptions.parameter) {
  18981. this.trigger = triggerOptions.trigger;
  18982. this._triggerParameter = triggerOptions.parameter;
  18983. } else {
  18984. this.trigger = triggerOptions;
  18985. }
  18986. this._nextActiveAction = this;
  18987. this._condition = condition;
  18988. }
  18989. Action.prototype._prepare = function () {
  18990. };
  18991. Action.prototype.getTriggerParameter = function () {
  18992. return this._triggerParameter;
  18993. };
  18994. Action.prototype._executeCurrent = function (evt) {
  18995. if (this._condition) {
  18996. var currentRenderId = this._actionManager.getScene().getRenderId();
  18997. if (this._condition._evaluationId === currentRenderId) {
  18998. if (!this._condition._currentResult) {
  18999. return;
  19000. }
  19001. } else {
  19002. this._condition._evaluationId = currentRenderId;
  19003. if (!this._condition.isValid()) {
  19004. this._condition._currentResult = false;
  19005. return;
  19006. }
  19007. this._condition._currentResult = true;
  19008. }
  19009. }
  19010. this._nextActiveAction.execute(evt);
  19011. if (this._nextActiveAction._child) {
  19012. if (!this._nextActiveAction._child._actionManager) {
  19013. this._nextActiveAction._child._actionManager = this._actionManager;
  19014. }
  19015. this._nextActiveAction = this._nextActiveAction._child;
  19016. } else {
  19017. this._nextActiveAction = this;
  19018. }
  19019. };
  19020. Action.prototype.execute = function (evt) {
  19021. };
  19022. Action.prototype.then = function (action) {
  19023. this._child = action;
  19024. action._actionManager = this._actionManager;
  19025. action._prepare();
  19026. return action;
  19027. };
  19028. Action.prototype._getProperty = function (propertyPath) {
  19029. return this._actionManager._getProperty(propertyPath);
  19030. };
  19031. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  19032. return this._actionManager._getEffectiveTarget(target, propertyPath);
  19033. };
  19034. return Action;
  19035. })();
  19036. BABYLON.Action = Action;
  19037. })(BABYLON || (BABYLON = {}));
  19038. var BABYLON;
  19039. (function (BABYLON) {
  19040. var ActionEvent = (function () {
  19041. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  19042. this.source = source;
  19043. this.pointerX = pointerX;
  19044. this.pointerY = pointerY;
  19045. this.meshUnderPointer = meshUnderPointer;
  19046. this.sourceEvent = sourceEvent;
  19047. }
  19048. ActionEvent.CreateNew = function (source) {
  19049. var scene = source.getScene();
  19050. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer);
  19051. };
  19052. ActionEvent.CreateNewFromScene = function (scene, evt) {
  19053. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  19054. };
  19055. return ActionEvent;
  19056. })();
  19057. BABYLON.ActionEvent = ActionEvent;
  19058. var ActionManager = (function () {
  19059. function ActionManager(scene) {
  19060. this.actions = new Array();
  19061. this._scene = scene;
  19062. scene._actionManagers.push(this);
  19063. }
  19064. Object.defineProperty(ActionManager, "NothingTrigger", {
  19065. get: function () {
  19066. return ActionManager._NothingTrigger;
  19067. },
  19068. enumerable: true,
  19069. configurable: true
  19070. });
  19071. Object.defineProperty(ActionManager, "OnPickTrigger", {
  19072. get: function () {
  19073. return ActionManager._OnPickTrigger;
  19074. },
  19075. enumerable: true,
  19076. configurable: true
  19077. });
  19078. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  19079. get: function () {
  19080. return ActionManager._OnLeftPickTrigger;
  19081. },
  19082. enumerable: true,
  19083. configurable: true
  19084. });
  19085. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  19086. get: function () {
  19087. return ActionManager._OnRightPickTrigger;
  19088. },
  19089. enumerable: true,
  19090. configurable: true
  19091. });
  19092. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  19093. get: function () {
  19094. return ActionManager._OnCenterPickTrigger;
  19095. },
  19096. enumerable: true,
  19097. configurable: true
  19098. });
  19099. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  19100. get: function () {
  19101. return ActionManager._OnPointerOverTrigger;
  19102. },
  19103. enumerable: true,
  19104. configurable: true
  19105. });
  19106. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  19107. get: function () {
  19108. return ActionManager._OnPointerOutTrigger;
  19109. },
  19110. enumerable: true,
  19111. configurable: true
  19112. });
  19113. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  19114. get: function () {
  19115. return ActionManager._OnEveryFrameTrigger;
  19116. },
  19117. enumerable: true,
  19118. configurable: true
  19119. });
  19120. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  19121. get: function () {
  19122. return ActionManager._OnIntersectionEnterTrigger;
  19123. },
  19124. enumerable: true,
  19125. configurable: true
  19126. });
  19127. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  19128. get: function () {
  19129. return ActionManager._OnIntersectionExitTrigger;
  19130. },
  19131. enumerable: true,
  19132. configurable: true
  19133. });
  19134. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  19135. get: function () {
  19136. return ActionManager._OnKeyDownTrigger;
  19137. },
  19138. enumerable: true,
  19139. configurable: true
  19140. });
  19141. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  19142. get: function () {
  19143. return ActionManager._OnKeyUpTrigger;
  19144. },
  19145. enumerable: true,
  19146. configurable: true
  19147. });
  19148. ActionManager.prototype.dispose = function () {
  19149. var index = this._scene._actionManagers.indexOf(this);
  19150. if (index > -1) {
  19151. this._scene._actionManagers.splice(index, 1);
  19152. }
  19153. };
  19154. ActionManager.prototype.getScene = function () {
  19155. return this._scene;
  19156. };
  19157. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  19158. for (var index = 0; index < this.actions.length; index++) {
  19159. var action = this.actions[index];
  19160. if (triggers.indexOf(action.trigger) > -1) {
  19161. return true;
  19162. }
  19163. }
  19164. return false;
  19165. };
  19166. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  19167. get: function () {
  19168. for (var index = 0; index < this.actions.length; index++) {
  19169. var action = this.actions[index];
  19170. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  19171. return true;
  19172. }
  19173. }
  19174. return false;
  19175. },
  19176. enumerable: true,
  19177. configurable: true
  19178. });
  19179. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  19180. get: function () {
  19181. for (var index = 0; index < this.actions.length; index++) {
  19182. var action = this.actions[index];
  19183. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  19184. return true;
  19185. }
  19186. }
  19187. return false;
  19188. },
  19189. enumerable: true,
  19190. configurable: true
  19191. });
  19192. ActionManager.prototype.registerAction = function (action) {
  19193. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  19194. if (this.getScene().actionManager !== this) {
  19195. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  19196. return null;
  19197. }
  19198. }
  19199. this.actions.push(action);
  19200. action._actionManager = this;
  19201. action._prepare();
  19202. return action;
  19203. };
  19204. ActionManager.prototype.processTrigger = function (trigger, evt) {
  19205. for (var index = 0; index < this.actions.length; index++) {
  19206. var action = this.actions[index];
  19207. if (action.trigger === trigger) {
  19208. if (trigger == ActionManager.OnKeyUpTrigger || trigger == ActionManager.OnKeyDownTrigger) {
  19209. var parameter = action.getTriggerParameter();
  19210. if (parameter) {
  19211. if (evt.sourceEvent.key !== parameter) {
  19212. continue;
  19213. }
  19214. }
  19215. }
  19216. action._executeCurrent(evt);
  19217. }
  19218. }
  19219. };
  19220. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  19221. var properties = propertyPath.split(".");
  19222. for (var index = 0; index < properties.length - 1; index++) {
  19223. target = target[properties[index]];
  19224. }
  19225. return target;
  19226. };
  19227. ActionManager.prototype._getProperty = function (propertyPath) {
  19228. var properties = propertyPath.split(".");
  19229. return properties[properties.length - 1];
  19230. };
  19231. ActionManager._NothingTrigger = 0;
  19232. ActionManager._OnPickTrigger = 1;
  19233. ActionManager._OnLeftPickTrigger = 2;
  19234. ActionManager._OnRightPickTrigger = 3;
  19235. ActionManager._OnCenterPickTrigger = 4;
  19236. ActionManager._OnPointerOverTrigger = 5;
  19237. ActionManager._OnPointerOutTrigger = 6;
  19238. ActionManager._OnEveryFrameTrigger = 7;
  19239. ActionManager._OnIntersectionEnterTrigger = 8;
  19240. ActionManager._OnIntersectionExitTrigger = 9;
  19241. ActionManager._OnKeyDownTrigger = 10;
  19242. ActionManager._OnKeyUpTrigger = 11;
  19243. return ActionManager;
  19244. })();
  19245. BABYLON.ActionManager = ActionManager;
  19246. })(BABYLON || (BABYLON = {}));
  19247. var __extends = this.__extends || function (d, b) {
  19248. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19249. function __() { this.constructor = d; }
  19250. __.prototype = b.prototype;
  19251. d.prototype = new __();
  19252. };
  19253. var BABYLON;
  19254. (function (BABYLON) {
  19255. var InterpolateValueAction = (function (_super) {
  19256. __extends(InterpolateValueAction, _super);
  19257. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  19258. if (typeof duration === "undefined") { duration = 1000; }
  19259. _super.call(this, triggerOptions, condition);
  19260. this.propertyPath = propertyPath;
  19261. this.value = value;
  19262. this.duration = duration;
  19263. this.stopOtherAnimations = stopOtherAnimations;
  19264. this._target = target;
  19265. }
  19266. InterpolateValueAction.prototype._prepare = function () {
  19267. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19268. this._property = this._getProperty(this.propertyPath);
  19269. };
  19270. InterpolateValueAction.prototype.execute = function () {
  19271. var scene = this._actionManager.getScene();
  19272. var keys = [
  19273. {
  19274. frame: 0,
  19275. value: this._target[this._property]
  19276. }, {
  19277. frame: 100,
  19278. value: this.value
  19279. }
  19280. ];
  19281. var dataType;
  19282. if (typeof this.value === "number") {
  19283. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  19284. } else if (this.value instanceof BABYLON.Color3) {
  19285. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  19286. } else if (this.value instanceof BABYLON.Vector3) {
  19287. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  19288. } else if (this.value instanceof BABYLON.Matrix) {
  19289. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  19290. } else if (this.value instanceof BABYLON.Quaternion) {
  19291. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  19292. } else {
  19293. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  19294. return;
  19295. }
  19296. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  19297. animation.setKeys(keys);
  19298. if (this.stopOtherAnimations) {
  19299. scene.stopAnimation(this._target);
  19300. }
  19301. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  19302. };
  19303. return InterpolateValueAction;
  19304. })(BABYLON.Action);
  19305. BABYLON.InterpolateValueAction = InterpolateValueAction;
  19306. })(BABYLON || (BABYLON = {}));
  19307. var __extends = this.__extends || function (d, b) {
  19308. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19309. function __() { this.constructor = d; }
  19310. __.prototype = b.prototype;
  19311. d.prototype = new __();
  19312. };
  19313. var BABYLON;
  19314. (function (BABYLON) {
  19315. var SwitchBooleanAction = (function (_super) {
  19316. __extends(SwitchBooleanAction, _super);
  19317. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  19318. _super.call(this, triggerOptions, condition);
  19319. this.propertyPath = propertyPath;
  19320. this._target = target;
  19321. }
  19322. SwitchBooleanAction.prototype._prepare = function () {
  19323. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19324. this._property = this._getProperty(this.propertyPath);
  19325. };
  19326. SwitchBooleanAction.prototype.execute = function () {
  19327. this._target[this._property] = !this._target[this._property];
  19328. };
  19329. return SwitchBooleanAction;
  19330. })(BABYLON.Action);
  19331. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  19332. var SetStateAction = (function (_super) {
  19333. __extends(SetStateAction, _super);
  19334. function SetStateAction(triggerOptions, target, value, condition) {
  19335. _super.call(this, triggerOptions, condition);
  19336. this.value = value;
  19337. this._target = target;
  19338. }
  19339. SetStateAction.prototype.execute = function () {
  19340. this._target.state = this.value;
  19341. };
  19342. return SetStateAction;
  19343. })(BABYLON.Action);
  19344. BABYLON.SetStateAction = SetStateAction;
  19345. var SetValueAction = (function (_super) {
  19346. __extends(SetValueAction, _super);
  19347. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  19348. _super.call(this, triggerOptions, condition);
  19349. this.propertyPath = propertyPath;
  19350. this.value = value;
  19351. this._target = target;
  19352. }
  19353. SetValueAction.prototype._prepare = function () {
  19354. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19355. this._property = this._getProperty(this.propertyPath);
  19356. };
  19357. SetValueAction.prototype.execute = function () {
  19358. this._target[this._property] = this.value;
  19359. };
  19360. return SetValueAction;
  19361. })(BABYLON.Action);
  19362. BABYLON.SetValueAction = SetValueAction;
  19363. var IncrementValueAction = (function (_super) {
  19364. __extends(IncrementValueAction, _super);
  19365. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  19366. _super.call(this, triggerOptions, condition);
  19367. this.propertyPath = propertyPath;
  19368. this.value = value;
  19369. this._target = target;
  19370. }
  19371. IncrementValueAction.prototype._prepare = function () {
  19372. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19373. this._property = this._getProperty(this.propertyPath);
  19374. if (typeof this._target[this._property] !== "number") {
  19375. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  19376. }
  19377. };
  19378. IncrementValueAction.prototype.execute = function () {
  19379. this._target[this._property] += this.value;
  19380. };
  19381. return IncrementValueAction;
  19382. })(BABYLON.Action);
  19383. BABYLON.IncrementValueAction = IncrementValueAction;
  19384. var PlayAnimationAction = (function (_super) {
  19385. __extends(PlayAnimationAction, _super);
  19386. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  19387. _super.call(this, triggerOptions, condition);
  19388. this.from = from;
  19389. this.to = to;
  19390. this.loop = loop;
  19391. this._target = target;
  19392. }
  19393. PlayAnimationAction.prototype._prepare = function () {
  19394. };
  19395. PlayAnimationAction.prototype.execute = function () {
  19396. var scene = this._actionManager.getScene();
  19397. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  19398. };
  19399. return PlayAnimationAction;
  19400. })(BABYLON.Action);
  19401. BABYLON.PlayAnimationAction = PlayAnimationAction;
  19402. var StopAnimationAction = (function (_super) {
  19403. __extends(StopAnimationAction, _super);
  19404. function StopAnimationAction(triggerOptions, target, condition) {
  19405. _super.call(this, triggerOptions, condition);
  19406. this._target = target;
  19407. }
  19408. StopAnimationAction.prototype._prepare = function () {
  19409. };
  19410. StopAnimationAction.prototype.execute = function () {
  19411. var scene = this._actionManager.getScene();
  19412. scene.stopAnimation(this._target);
  19413. };
  19414. return StopAnimationAction;
  19415. })(BABYLON.Action);
  19416. BABYLON.StopAnimationAction = StopAnimationAction;
  19417. var DoNothingAction = (function (_super) {
  19418. __extends(DoNothingAction, _super);
  19419. function DoNothingAction(triggerOptions, condition) {
  19420. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  19421. _super.call(this, triggerOptions, condition);
  19422. }
  19423. DoNothingAction.prototype.execute = function () {
  19424. };
  19425. return DoNothingAction;
  19426. })(BABYLON.Action);
  19427. BABYLON.DoNothingAction = DoNothingAction;
  19428. var CombineAction = (function (_super) {
  19429. __extends(CombineAction, _super);
  19430. function CombineAction(triggerOptions, children, condition) {
  19431. _super.call(this, triggerOptions, condition);
  19432. this.children = children;
  19433. }
  19434. CombineAction.prototype._prepare = function () {
  19435. for (var index = 0; index < this.children.length; index++) {
  19436. this.children[index]._actionManager = this._actionManager;
  19437. this.children[index]._prepare();
  19438. }
  19439. };
  19440. CombineAction.prototype.execute = function (evt) {
  19441. for (var index = 0; index < this.children.length; index++) {
  19442. this.children[index].execute(evt);
  19443. }
  19444. };
  19445. return CombineAction;
  19446. })(BABYLON.Action);
  19447. BABYLON.CombineAction = CombineAction;
  19448. var ExecuteCodeAction = (function (_super) {
  19449. __extends(ExecuteCodeAction, _super);
  19450. function ExecuteCodeAction(triggerOptions, func, condition) {
  19451. _super.call(this, triggerOptions, condition);
  19452. this.func = func;
  19453. }
  19454. ExecuteCodeAction.prototype.execute = function (evt) {
  19455. this.func(evt);
  19456. };
  19457. return ExecuteCodeAction;
  19458. })(BABYLON.Action);
  19459. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  19460. var SetParentAction = (function (_super) {
  19461. __extends(SetParentAction, _super);
  19462. function SetParentAction(triggerOptions, target, parent, condition) {
  19463. _super.call(this, triggerOptions, condition);
  19464. this._target = target;
  19465. this._parent = parent;
  19466. }
  19467. SetParentAction.prototype._prepare = function () {
  19468. };
  19469. SetParentAction.prototype.execute = function () {
  19470. if (this._target.parent === this._parent) {
  19471. return;
  19472. }
  19473. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  19474. invertParentWorldMatrix.invert();
  19475. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  19476. this._target.parent = this._parent;
  19477. };
  19478. return SetParentAction;
  19479. })(BABYLON.Action);
  19480. BABYLON.SetParentAction = SetParentAction;
  19481. })(BABYLON || (BABYLON = {}));
  19482. var __extends = this.__extends || function (d, b) {
  19483. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19484. function __() { this.constructor = d; }
  19485. __.prototype = b.prototype;
  19486. d.prototype = new __();
  19487. };
  19488. var BABYLON;
  19489. (function (BABYLON) {
  19490. var Geometry = (function () {
  19491. function Geometry(id, scene, vertexData, updatable, mesh) {
  19492. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19493. this._totalVertices = 0;
  19494. this._indices = [];
  19495. this.id = id;
  19496. this._engine = scene.getEngine();
  19497. this._meshes = [];
  19498. this._scene = scene;
  19499. if (vertexData) {
  19500. this.setAllVerticesData(vertexData, updatable);
  19501. } else {
  19502. this._totalVertices = 0;
  19503. this._indices = [];
  19504. }
  19505. if (mesh) {
  19506. this.applyToMesh(mesh);
  19507. }
  19508. }
  19509. Geometry.prototype.getScene = function () {
  19510. return this._scene;
  19511. };
  19512. Geometry.prototype.getEngine = function () {
  19513. return this._engine;
  19514. };
  19515. Geometry.prototype.isReady = function () {
  19516. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  19517. };
  19518. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  19519. vertexData.applyToGeometry(this, updatable);
  19520. };
  19521. Geometry.prototype.setVerticesData = function (kind, data, updatable) {
  19522. this._vertexBuffers = this._vertexBuffers || {};
  19523. if (this._vertexBuffers[kind]) {
  19524. this._vertexBuffers[kind].dispose();
  19525. }
  19526. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0);
  19527. if (kind === BABYLON.VertexBuffer.PositionKind) {
  19528. var stride = this._vertexBuffers[kind].getStrideSize();
  19529. this._totalVertices = data.length / stride;
  19530. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  19531. var meshes = this._meshes;
  19532. var numOfMeshes = meshes.length;
  19533. for (var index = 0; index < numOfMeshes; index++) {
  19534. var mesh = meshes[index];
  19535. mesh._resetPointsArrayCache();
  19536. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19537. mesh._createGlobalSubMesh();
  19538. mesh.computeWorldMatrix(true);
  19539. }
  19540. }
  19541. };
  19542. Geometry.prototype.updateVerticesDataDirectly = function (kind, data) {
  19543. var vertexBuffer = this.getVertexBuffer(kind);
  19544. if (!vertexBuffer) {
  19545. return;
  19546. }
  19547. vertexBuffer.updateDirectly(data);
  19548. };
  19549. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  19550. var vertexBuffer = this.getVertexBuffer(kind);
  19551. if (!vertexBuffer) {
  19552. return;
  19553. }
  19554. vertexBuffer.update(data);
  19555. if (kind === BABYLON.VertexBuffer.PositionKind) {
  19556. var extend;
  19557. if (updateExtends) {
  19558. var stride = vertexBuffer.getStrideSize();
  19559. this._totalVertices = data.length / stride;
  19560. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  19561. }
  19562. var meshes = this._meshes;
  19563. var numOfMeshes = meshes.length;
  19564. for (var index = 0; index < numOfMeshes; index++) {
  19565. var mesh = meshes[index];
  19566. mesh._resetPointsArrayCache();
  19567. if (updateExtends) {
  19568. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19569. }
  19570. }
  19571. }
  19572. };
  19573. Geometry.prototype.getTotalVertices = function () {
  19574. if (!this.isReady()) {
  19575. return 0;
  19576. }
  19577. return this._totalVertices;
  19578. };
  19579. Geometry.prototype.getVerticesData = function (kind) {
  19580. var vertexBuffer = this.getVertexBuffer(kind);
  19581. if (!vertexBuffer) {
  19582. return null;
  19583. }
  19584. return vertexBuffer.getData();
  19585. };
  19586. Geometry.prototype.getVertexBuffer = function (kind) {
  19587. if (!this.isReady()) {
  19588. return null;
  19589. }
  19590. return this._vertexBuffers[kind];
  19591. };
  19592. Geometry.prototype.getVertexBuffers = function () {
  19593. if (!this.isReady()) {
  19594. return null;
  19595. }
  19596. return this._vertexBuffers;
  19597. };
  19598. Geometry.prototype.isVerticesDataPresent = function (kind) {
  19599. if (!this._vertexBuffers) {
  19600. if (this._delayInfo) {
  19601. return this._delayInfo.indexOf(kind) !== -1;
  19602. }
  19603. return false;
  19604. }
  19605. return this._vertexBuffers[kind] !== undefined;
  19606. };
  19607. Geometry.prototype.getVerticesDataKinds = function () {
  19608. var result = [];
  19609. if (!this._vertexBuffers && this._delayInfo) {
  19610. for (var kind in this._delayInfo) {
  19611. result.push(kind);
  19612. }
  19613. } else {
  19614. for (kind in this._vertexBuffers) {
  19615. result.push(kind);
  19616. }
  19617. }
  19618. return result;
  19619. };
  19620. Geometry.prototype.setIndices = function (indices) {
  19621. if (this._indexBuffer) {
  19622. this._engine._releaseBuffer(this._indexBuffer);
  19623. }
  19624. this._indices = indices;
  19625. if (this._meshes.length !== 0 && this._indices) {
  19626. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  19627. }
  19628. var meshes = this._meshes;
  19629. var numOfMeshes = meshes.length;
  19630. for (var index = 0; index < numOfMeshes; index++) {
  19631. meshes[index]._createGlobalSubMesh();
  19632. }
  19633. };
  19634. Geometry.prototype.getTotalIndices = function () {
  19635. if (!this.isReady()) {
  19636. return 0;
  19637. }
  19638. return this._indices.length;
  19639. };
  19640. Geometry.prototype.getIndices = function () {
  19641. if (!this.isReady()) {
  19642. return null;
  19643. }
  19644. return this._indices;
  19645. };
  19646. Geometry.prototype.getIndexBuffer = function () {
  19647. if (!this.isReady()) {
  19648. return null;
  19649. }
  19650. return this._indexBuffer;
  19651. };
  19652. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  19653. var meshes = this._meshes;
  19654. var index = meshes.indexOf(mesh);
  19655. if (index === -1) {
  19656. return;
  19657. }
  19658. for (var kind in this._vertexBuffers) {
  19659. this._vertexBuffers[kind].dispose();
  19660. }
  19661. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  19662. this._indexBuffer = null;
  19663. }
  19664. meshes.splice(index, 1);
  19665. mesh._geometry = null;
  19666. if (meshes.length == 0 && shouldDispose) {
  19667. this.dispose();
  19668. }
  19669. };
  19670. Geometry.prototype.applyToMesh = function (mesh) {
  19671. if (mesh._geometry === this) {
  19672. return;
  19673. }
  19674. var previousGeometry = mesh._geometry;
  19675. if (previousGeometry) {
  19676. previousGeometry.releaseForMesh(mesh);
  19677. }
  19678. var meshes = this._meshes;
  19679. mesh._geometry = this;
  19680. this._scene.pushGeometry(this);
  19681. meshes.push(mesh);
  19682. if (this.isReady()) {
  19683. this._applyToMesh(mesh);
  19684. } else {
  19685. mesh._boundingInfo = this._boundingInfo;
  19686. }
  19687. };
  19688. Geometry.prototype._applyToMesh = function (mesh) {
  19689. var numOfMeshes = this._meshes.length;
  19690. for (var kind in this._vertexBuffers) {
  19691. if (numOfMeshes === 1) {
  19692. this._vertexBuffers[kind].create();
  19693. }
  19694. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  19695. if (kind === BABYLON.VertexBuffer.PositionKind) {
  19696. mesh._resetPointsArrayCache();
  19697. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  19698. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19699. mesh._createGlobalSubMesh();
  19700. }
  19701. }
  19702. if (numOfMeshes === 1 && this._indices) {
  19703. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  19704. }
  19705. if (this._indexBuffer) {
  19706. this._indexBuffer.references = numOfMeshes;
  19707. }
  19708. };
  19709. Geometry.prototype.load = function (scene, onLoaded) {
  19710. var _this = this;
  19711. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19712. return;
  19713. }
  19714. if (this.isReady()) {
  19715. if (onLoaded) {
  19716. onLoaded();
  19717. }
  19718. return;
  19719. }
  19720. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19721. scene._addPendingData(this);
  19722. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19723. _this._delayLoadingFunction(JSON.parse(data), _this);
  19724. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19725. _this._delayInfo = [];
  19726. scene._removePendingData(_this);
  19727. var meshes = _this._meshes;
  19728. var numOfMeshes = meshes.length;
  19729. for (var index = 0; index < numOfMeshes; index++) {
  19730. _this._applyToMesh(meshes[index]);
  19731. }
  19732. if (onLoaded) {
  19733. onLoaded();
  19734. }
  19735. }, function () {
  19736. }, scene.database);
  19737. };
  19738. Geometry.prototype.dispose = function () {
  19739. var meshes = this._meshes;
  19740. var numOfMeshes = meshes.length;
  19741. for (var index = 0; index < numOfMeshes; index++) {
  19742. this.releaseForMesh(meshes[index]);
  19743. }
  19744. this._meshes = [];
  19745. for (var kind in this._vertexBuffers) {
  19746. this._vertexBuffers[kind].dispose();
  19747. }
  19748. this._vertexBuffers = [];
  19749. this._totalVertices = 0;
  19750. if (this._indexBuffer) {
  19751. this._engine._releaseBuffer(this._indexBuffer);
  19752. }
  19753. this._indexBuffer = null;
  19754. this._indices = [];
  19755. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19756. this.delayLoadingFile = null;
  19757. this._delayLoadingFunction = null;
  19758. this._delayInfo = [];
  19759. this._boundingInfo = null;
  19760. var geometries = this._scene.getGeometries();
  19761. index = geometries.indexOf(this);
  19762. if (index > -1) {
  19763. geometries.splice(index, 1);
  19764. }
  19765. };
  19766. Geometry.prototype.copy = function (id) {
  19767. var vertexData = new BABYLON.VertexData();
  19768. vertexData.indices = [];
  19769. var indices = this.getIndices();
  19770. for (var index = 0; index < indices.length; index++) {
  19771. vertexData.indices.push(indices[index]);
  19772. }
  19773. var updatable = false;
  19774. var stopChecking = false;
  19775. for (var kind in this._vertexBuffers) {
  19776. vertexData.set(this.getVerticesData(kind), kind);
  19777. if (!stopChecking) {
  19778. updatable = this.getVertexBuffer(kind).isUpdatable();
  19779. stopChecking = !updatable;
  19780. }
  19781. }
  19782. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  19783. geometry.delayLoadState = this.delayLoadState;
  19784. geometry.delayLoadingFile = this.delayLoadingFile;
  19785. geometry._delayLoadingFunction = this._delayLoadingFunction;
  19786. for (kind in this._delayInfo) {
  19787. geometry._delayInfo = geometry._delayInfo || [];
  19788. geometry._delayInfo.push(kind);
  19789. }
  19790. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  19791. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19792. return geometry;
  19793. };
  19794. Geometry.ExtractFromMesh = function (mesh, id) {
  19795. var geometry = mesh._geometry;
  19796. if (!geometry) {
  19797. return null;
  19798. }
  19799. return geometry.copy(id);
  19800. };
  19801. Geometry.RandomId = function () {
  19802. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  19803. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  19804. return v.toString(16);
  19805. });
  19806. };
  19807. return Geometry;
  19808. })();
  19809. BABYLON.Geometry = Geometry;
  19810. (function (Geometry) {
  19811. (function (Primitives) {
  19812. var _Primitive = (function (_super) {
  19813. __extends(_Primitive, _super);
  19814. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  19815. this._beingRegenerated = true;
  19816. this._canBeRegenerated = canBeRegenerated;
  19817. _super.call(this, id, scene, vertexData, false, mesh);
  19818. this._beingRegenerated = false;
  19819. }
  19820. _Primitive.prototype.canBeRegenerated = function () {
  19821. return this._canBeRegenerated;
  19822. };
  19823. _Primitive.prototype.regenerate = function () {
  19824. if (!this._canBeRegenerated) {
  19825. return;
  19826. }
  19827. this._beingRegenerated = true;
  19828. this.setAllVerticesData(this._regenerateVertexData(), false);
  19829. this._beingRegenerated = false;
  19830. };
  19831. _Primitive.prototype.asNewGeometry = function (id) {
  19832. return _super.prototype.copy.call(this, id);
  19833. };
  19834. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  19835. if (!this._beingRegenerated) {
  19836. return;
  19837. }
  19838. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  19839. };
  19840. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  19841. if (!this._beingRegenerated) {
  19842. return;
  19843. }
  19844. _super.prototype.setVerticesData.call(this, kind, data, false);
  19845. };
  19846. _Primitive.prototype._regenerateVertexData = function () {
  19847. throw new Error("Abstract method");
  19848. };
  19849. _Primitive.prototype.copy = function (id) {
  19850. throw new Error("Must be overriden in sub-classes.");
  19851. };
  19852. return _Primitive;
  19853. })(Geometry);
  19854. Primitives._Primitive = _Primitive;
  19855. var Box = (function (_super) {
  19856. __extends(Box, _super);
  19857. function Box(id, scene, size, canBeRegenerated, mesh) {
  19858. this.size = size;
  19859. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19860. }
  19861. Box.prototype._regenerateVertexData = function () {
  19862. return BABYLON.VertexData.CreateBox(this.size);
  19863. };
  19864. Box.prototype.copy = function (id) {
  19865. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19866. };
  19867. return Box;
  19868. })(_Primitive);
  19869. Primitives.Box = Box;
  19870. var Sphere = (function (_super) {
  19871. __extends(Sphere, _super);
  19872. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  19873. this.segments = segments;
  19874. this.diameter = diameter;
  19875. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19876. }
  19877. Sphere.prototype._regenerateVertexData = function () {
  19878. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  19879. };
  19880. Sphere.prototype.copy = function (id) {
  19881. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  19882. };
  19883. return Sphere;
  19884. })(_Primitive);
  19885. Primitives.Sphere = Sphere;
  19886. var Cylinder = (function (_super) {
  19887. __extends(Cylinder, _super);
  19888. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  19889. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  19890. this.height = height;
  19891. this.diameterTop = diameterTop;
  19892. this.diameterBottom = diameterBottom;
  19893. this.tessellation = tessellation;
  19894. this.subdivisions = subdivisions;
  19895. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19896. }
  19897. Cylinder.prototype._regenerateVertexData = function () {
  19898. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  19899. };
  19900. Cylinder.prototype.copy = function (id) {
  19901. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  19902. };
  19903. return Cylinder;
  19904. })(_Primitive);
  19905. Primitives.Cylinder = Cylinder;
  19906. var Torus = (function (_super) {
  19907. __extends(Torus, _super);
  19908. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  19909. this.diameter = diameter;
  19910. this.thickness = thickness;
  19911. this.tessellation = tessellation;
  19912. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19913. }
  19914. Torus.prototype._regenerateVertexData = function () {
  19915. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  19916. };
  19917. Torus.prototype.copy = function (id) {
  19918. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  19919. };
  19920. return Torus;
  19921. })(_Primitive);
  19922. Primitives.Torus = Torus;
  19923. var Ground = (function (_super) {
  19924. __extends(Ground, _super);
  19925. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  19926. this.width = width;
  19927. this.height = height;
  19928. this.subdivisions = subdivisions;
  19929. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19930. }
  19931. Ground.prototype._regenerateVertexData = function () {
  19932. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  19933. };
  19934. Ground.prototype.copy = function (id) {
  19935. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  19936. };
  19937. return Ground;
  19938. })(_Primitive);
  19939. Primitives.Ground = Ground;
  19940. var TiledGround = (function (_super) {
  19941. __extends(TiledGround, _super);
  19942. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  19943. this.xmin = xmin;
  19944. this.zmin = zmin;
  19945. this.xmax = xmax;
  19946. this.zmax = zmax;
  19947. this.subdivisions = subdivisions;
  19948. this.precision = precision;
  19949. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19950. }
  19951. TiledGround.prototype._regenerateVertexData = function () {
  19952. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  19953. };
  19954. TiledGround.prototype.copy = function (id) {
  19955. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  19956. };
  19957. return TiledGround;
  19958. })(_Primitive);
  19959. Primitives.TiledGround = TiledGround;
  19960. var Plane = (function (_super) {
  19961. __extends(Plane, _super);
  19962. function Plane(id, scene, size, canBeRegenerated, mesh) {
  19963. this.size = size;
  19964. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19965. }
  19966. Plane.prototype._regenerateVertexData = function () {
  19967. return BABYLON.VertexData.CreatePlane(this.size);
  19968. };
  19969. Plane.prototype.copy = function (id) {
  19970. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  19971. };
  19972. return Plane;
  19973. })(_Primitive);
  19974. Primitives.Plane = Plane;
  19975. var TorusKnot = (function (_super) {
  19976. __extends(TorusKnot, _super);
  19977. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  19978. this.radius = radius;
  19979. this.tube = tube;
  19980. this.radialSegments = radialSegments;
  19981. this.tubularSegments = tubularSegments;
  19982. this.p = p;
  19983. this.q = q;
  19984. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  19985. }
  19986. TorusKnot.prototype._regenerateVertexData = function () {
  19987. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  19988. };
  19989. TorusKnot.prototype.copy = function (id) {
  19990. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  19991. };
  19992. return TorusKnot;
  19993. })(_Primitive);
  19994. Primitives.TorusKnot = TorusKnot;
  19995. })(Geometry.Primitives || (Geometry.Primitives = {}));
  19996. var Primitives = Geometry.Primitives;
  19997. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  19998. var Geometry = BABYLON.Geometry;
  19999. })(BABYLON || (BABYLON = {}));
  20000. var __extends = this.__extends || function (d, b) {
  20001. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20002. function __() { this.constructor = d; }
  20003. __.prototype = b.prototype;
  20004. d.prototype = new __();
  20005. };
  20006. var BABYLON;
  20007. (function (BABYLON) {
  20008. var Gamepads = (function () {
  20009. function Gamepads(ongamedpadconnected) {
  20010. var _this = this;
  20011. this.babylonGamepads = [];
  20012. this.oneGamepadConnected = false;
  20013. this.isMonitoring = false;
  20014. this.gamepadEventSupported = 'GamepadEvent' in window;
  20015. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  20016. 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=";
  20017. this._callbackGamepadConnected = ongamedpadconnected;
  20018. if (this.gamepadSupportAvailable) {
  20019. if (this.gamepadEventSupported) {
  20020. window.addEventListener('gamepadconnected', function (evt) {
  20021. _this._onGamepadConnected(evt);
  20022. }, false);
  20023. window.addEventListener('gamepaddisconnected', function (evt) {
  20024. _this._onGamepadDisconnected(evt);
  20025. }, false);
  20026. } else {
  20027. this._startMonitoringGamepads();
  20028. }
  20029. if (!this.oneGamepadConnected) {
  20030. this._insertGamepadDOMInstructions();
  20031. }
  20032. } else {
  20033. this._insertGamepadDOMNotSupported();
  20034. }
  20035. }
  20036. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  20037. Gamepads.gamepadDOMInfo = document.createElement("div");
  20038. var buttonAImage = document.createElement("img");
  20039. buttonAImage.src = this.buttonADataURL;
  20040. var spanMessage = document.createElement("span");
  20041. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  20042. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  20043. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  20044. Gamepads.gamepadDOMInfo.style.position = "absolute";
  20045. Gamepads.gamepadDOMInfo.style.width = "100%";
  20046. Gamepads.gamepadDOMInfo.style.height = "48px";
  20047. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  20048. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  20049. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  20050. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  20051. buttonAImage.style.position = "relative";
  20052. buttonAImage.style.bottom = "8px";
  20053. spanMessage.style.position = "relative";
  20054. spanMessage.style.fontSize = "32px";
  20055. spanMessage.style.bottom = "32px";
  20056. spanMessage.style.color = "green";
  20057. document.body.appendChild(Gamepads.gamepadDOMInfo);
  20058. };
  20059. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  20060. Gamepads.gamepadDOMInfo = document.createElement("div");
  20061. var spanMessage = document.createElement("span");
  20062. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  20063. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  20064. Gamepads.gamepadDOMInfo.style.position = "absolute";
  20065. Gamepads.gamepadDOMInfo.style.width = "100%";
  20066. Gamepads.gamepadDOMInfo.style.height = "40px";
  20067. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  20068. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  20069. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  20070. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  20071. spanMessage.style.position = "relative";
  20072. spanMessage.style.fontSize = "32px";
  20073. spanMessage.style.color = "red";
  20074. document.body.appendChild(Gamepads.gamepadDOMInfo);
  20075. };
  20076. Gamepads.prototype.dispose = function () {
  20077. document.body.removeChild(Gamepads.gamepadDOMInfo);
  20078. };
  20079. Gamepads.prototype._onGamepadConnected = function (evt) {
  20080. var newGamepad = this._addNewGamepad(evt.gamepad);
  20081. if (this._callbackGamepadConnected)
  20082. this._callbackGamepadConnected(newGamepad);
  20083. this._startMonitoringGamepads();
  20084. };
  20085. Gamepads.prototype._addNewGamepad = function (gamepad) {
  20086. if (!this.oneGamepadConnected) {
  20087. this.oneGamepadConnected = true;
  20088. if (Gamepads.gamepadDOMInfo) {
  20089. document.body.removeChild(Gamepads.gamepadDOMInfo);
  20090. Gamepads.gamepadDOMInfo = null;
  20091. }
  20092. }
  20093. var newGamepad;
  20094. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  20095. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  20096. } else {
  20097. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  20098. }
  20099. this.babylonGamepads.push(newGamepad);
  20100. return newGamepad;
  20101. };
  20102. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  20103. for (var i in this.babylonGamepads) {
  20104. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  20105. this.babylonGamepads.splice(i, 1);
  20106. break;
  20107. }
  20108. }
  20109. if (this.babylonGamepads.length == 0) {
  20110. this._stopMonitoringGamepads();
  20111. }
  20112. };
  20113. Gamepads.prototype._startMonitoringGamepads = function () {
  20114. if (!this.isMonitoring) {
  20115. this.isMonitoring = true;
  20116. this._checkGamepadsStatus();
  20117. }
  20118. };
  20119. Gamepads.prototype._stopMonitoringGamepads = function () {
  20120. this.isMonitoring = false;
  20121. };
  20122. Gamepads.prototype._checkGamepadsStatus = function () {
  20123. var _this = this;
  20124. this._updateGamepadObjects();
  20125. for (var i in this.babylonGamepads) {
  20126. this.babylonGamepads[i].update();
  20127. }
  20128. if (this.isMonitoring) {
  20129. if (window.requestAnimationFrame) {
  20130. window.requestAnimationFrame(function () {
  20131. _this._checkGamepadsStatus();
  20132. });
  20133. } else if (window.mozRequestAnimationFrame) {
  20134. window.mozRequestAnimationFrame(function () {
  20135. _this._checkGamepadsStatus();
  20136. });
  20137. } else if (window.webkitRequestAnimationFrame) {
  20138. window.webkitRequestAnimationFrame(function () {
  20139. _this._checkGamepadsStatus();
  20140. });
  20141. }
  20142. }
  20143. };
  20144. Gamepads.prototype._updateGamepadObjects = function () {
  20145. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  20146. for (var i = 0; i < gamepads.length; i++) {
  20147. if (gamepads[i]) {
  20148. if (!(gamepads[i].index in this.babylonGamepads)) {
  20149. var newGamepad = this._addNewGamepad(gamepads[i]);
  20150. if (this._callbackGamepadConnected) {
  20151. this._callbackGamepadConnected(newGamepad);
  20152. }
  20153. } else {
  20154. this.babylonGamepads[i].browserGamepad = gamepads[i];
  20155. }
  20156. }
  20157. }
  20158. };
  20159. return Gamepads;
  20160. })();
  20161. BABYLON.Gamepads = Gamepads;
  20162. var StickValues = (function () {
  20163. function StickValues(x, y) {
  20164. this.x = x;
  20165. this.y = y;
  20166. }
  20167. return StickValues;
  20168. })();
  20169. BABYLON.StickValues = StickValues;
  20170. var Gamepad = (function () {
  20171. function Gamepad(id, index, browserGamepad) {
  20172. this.id = id;
  20173. this.index = index;
  20174. this.browserGamepad = browserGamepad;
  20175. if (this.browserGamepad.axes.length >= 2) {
  20176. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  20177. }
  20178. if (this.browserGamepad.axes.length >= 4) {
  20179. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  20180. }
  20181. }
  20182. Gamepad.prototype.onleftstickchanged = function (callback) {
  20183. this._onleftstickchanged = callback;
  20184. };
  20185. Gamepad.prototype.onrightstickchanged = function (callback) {
  20186. this._onrightstickchanged = callback;
  20187. };
  20188. Object.defineProperty(Gamepad.prototype, "leftStick", {
  20189. get: function () {
  20190. return this._leftStick;
  20191. },
  20192. set: function (newValues) {
  20193. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  20194. this._onleftstickchanged(newValues);
  20195. }
  20196. this._leftStick = newValues;
  20197. },
  20198. enumerable: true,
  20199. configurable: true
  20200. });
  20201. Object.defineProperty(Gamepad.prototype, "rightStick", {
  20202. get: function () {
  20203. return this._rightStick;
  20204. },
  20205. set: function (newValues) {
  20206. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  20207. this._onrightstickchanged(newValues);
  20208. }
  20209. this._rightStick = newValues;
  20210. },
  20211. enumerable: true,
  20212. configurable: true
  20213. });
  20214. Gamepad.prototype.update = function () {
  20215. if (this._leftStick) {
  20216. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  20217. }
  20218. if (this._rightStick) {
  20219. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  20220. }
  20221. };
  20222. return Gamepad;
  20223. })();
  20224. BABYLON.Gamepad = Gamepad;
  20225. var GenericPad = (function (_super) {
  20226. __extends(GenericPad, _super);
  20227. function GenericPad(id, index, gamepad) {
  20228. _super.call(this, id, index, gamepad);
  20229. this.id = id;
  20230. this.index = index;
  20231. this.gamepad = gamepad;
  20232. this._buttons = new Array(gamepad.buttons.length);
  20233. }
  20234. GenericPad.prototype.onbuttondown = function (callback) {
  20235. this._onbuttondown = callback;
  20236. };
  20237. GenericPad.prototype.onbuttonup = function (callback) {
  20238. this._onbuttonup = callback;
  20239. };
  20240. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  20241. if (newValue !== currentValue) {
  20242. if (this._onbuttondown && newValue === 1) {
  20243. this._onbuttondown(buttonIndex);
  20244. }
  20245. if (this._onbuttonup && newValue === 0) {
  20246. this._onbuttonup(buttonIndex);
  20247. }
  20248. }
  20249. return newValue;
  20250. };
  20251. GenericPad.prototype.update = function () {
  20252. _super.prototype.update.call(this);
  20253. for (var index = 0; index < this._buttons.length; index++) {
  20254. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  20255. }
  20256. };
  20257. return GenericPad;
  20258. })(Gamepad);
  20259. BABYLON.GenericPad = GenericPad;
  20260. (function (Xbox360Button) {
  20261. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  20262. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  20263. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  20264. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  20265. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  20266. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  20267. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  20268. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  20269. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  20270. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  20271. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  20272. var Xbox360Button = BABYLON.Xbox360Button;
  20273. (function (Xbox360Dpad) {
  20274. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  20275. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  20276. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  20277. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  20278. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  20279. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  20280. var Xbox360Pad = (function (_super) {
  20281. __extends(Xbox360Pad, _super);
  20282. function Xbox360Pad() {
  20283. _super.apply(this, arguments);
  20284. this._leftTrigger = 0;
  20285. this._rightTrigger = 0;
  20286. this._buttonA = 0;
  20287. this._buttonB = 0;
  20288. this._buttonX = 0;
  20289. this._buttonY = 0;
  20290. this._buttonBack = 0;
  20291. this._buttonStart = 0;
  20292. this._buttonLB = 0;
  20293. this._buttonRB = 0;
  20294. this._buttonLeftStick = 0;
  20295. this._buttonRightStick = 0;
  20296. this._dPadUp = 0;
  20297. this._dPadDown = 0;
  20298. this._dPadLeft = 0;
  20299. this._dPadRight = 0;
  20300. }
  20301. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  20302. this._onlefttriggerchanged = callback;
  20303. };
  20304. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  20305. this._onrighttriggerchanged = callback;
  20306. };
  20307. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  20308. get: function () {
  20309. return this._leftTrigger;
  20310. },
  20311. set: function (newValue) {
  20312. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  20313. this._onlefttriggerchanged(newValue);
  20314. }
  20315. this._leftTrigger = newValue;
  20316. },
  20317. enumerable: true,
  20318. configurable: true
  20319. });
  20320. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  20321. get: function () {
  20322. return this._rightTrigger;
  20323. },
  20324. set: function (newValue) {
  20325. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  20326. this._onrighttriggerchanged(newValue);
  20327. }
  20328. this._rightTrigger = newValue;
  20329. },
  20330. enumerable: true,
  20331. configurable: true
  20332. });
  20333. Xbox360Pad.prototype.onbuttondown = function (callback) {
  20334. this._onbuttondown = callback;
  20335. };
  20336. Xbox360Pad.prototype.onbuttonup = function (callback) {
  20337. this._onbuttonup = callback;
  20338. };
  20339. Xbox360Pad.prototype.ondpaddown = function (callback) {
  20340. this._ondpaddown = callback;
  20341. };
  20342. Xbox360Pad.prototype.ondpadup = function (callback) {
  20343. this._ondpadup = callback;
  20344. };
  20345. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  20346. if (newValue !== currentValue) {
  20347. if (this._onbuttondown && newValue === 1) {
  20348. this._onbuttondown(buttonType);
  20349. }
  20350. if (this._onbuttonup && newValue === 0) {
  20351. this._onbuttonup(buttonType);
  20352. }
  20353. }
  20354. return newValue;
  20355. };
  20356. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  20357. if (newValue !== currentValue) {
  20358. if (this._ondpaddown && newValue === 1) {
  20359. this._ondpaddown(buttonType);
  20360. }
  20361. if (this._ondpadup && newValue === 0) {
  20362. this._ondpadup(buttonType);
  20363. }
  20364. }
  20365. return newValue;
  20366. };
  20367. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  20368. get: function () {
  20369. return this._buttonA;
  20370. },
  20371. set: function (value) {
  20372. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  20373. },
  20374. enumerable: true,
  20375. configurable: true
  20376. });
  20377. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  20378. get: function () {
  20379. return this._buttonB;
  20380. },
  20381. set: function (value) {
  20382. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  20383. },
  20384. enumerable: true,
  20385. configurable: true
  20386. });
  20387. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  20388. get: function () {
  20389. return this._buttonX;
  20390. },
  20391. set: function (value) {
  20392. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  20393. },
  20394. enumerable: true,
  20395. configurable: true
  20396. });
  20397. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  20398. get: function () {
  20399. return this._buttonY;
  20400. },
  20401. set: function (value) {
  20402. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  20403. },
  20404. enumerable: true,
  20405. configurable: true
  20406. });
  20407. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  20408. get: function () {
  20409. return this._buttonStart;
  20410. },
  20411. set: function (value) {
  20412. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  20413. },
  20414. enumerable: true,
  20415. configurable: true
  20416. });
  20417. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  20418. get: function () {
  20419. return this._buttonBack;
  20420. },
  20421. set: function (value) {
  20422. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  20423. },
  20424. enumerable: true,
  20425. configurable: true
  20426. });
  20427. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  20428. get: function () {
  20429. return this._buttonLB;
  20430. },
  20431. set: function (value) {
  20432. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  20433. },
  20434. enumerable: true,
  20435. configurable: true
  20436. });
  20437. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  20438. get: function () {
  20439. return this._buttonRB;
  20440. },
  20441. set: function (value) {
  20442. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  20443. },
  20444. enumerable: true,
  20445. configurable: true
  20446. });
  20447. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  20448. get: function () {
  20449. return this._buttonLeftStick;
  20450. },
  20451. set: function (value) {
  20452. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  20453. },
  20454. enumerable: true,
  20455. configurable: true
  20456. });
  20457. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  20458. get: function () {
  20459. return this._buttonRightStick;
  20460. },
  20461. set: function (value) {
  20462. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  20463. },
  20464. enumerable: true,
  20465. configurable: true
  20466. });
  20467. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  20468. get: function () {
  20469. return this._dPadUp;
  20470. },
  20471. set: function (value) {
  20472. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  20473. },
  20474. enumerable: true,
  20475. configurable: true
  20476. });
  20477. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  20478. get: function () {
  20479. return this._dPadDown;
  20480. },
  20481. set: function (value) {
  20482. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  20483. },
  20484. enumerable: true,
  20485. configurable: true
  20486. });
  20487. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  20488. get: function () {
  20489. return this._dPadLeft;
  20490. },
  20491. set: function (value) {
  20492. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  20493. },
  20494. enumerable: true,
  20495. configurable: true
  20496. });
  20497. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  20498. get: function () {
  20499. return this._dPadRight;
  20500. },
  20501. set: function (value) {
  20502. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  20503. },
  20504. enumerable: true,
  20505. configurable: true
  20506. });
  20507. Xbox360Pad.prototype.update = function () {
  20508. _super.prototype.update.call(this);
  20509. this.buttonA = this.browserGamepad.buttons[0].value;
  20510. this.buttonB = this.browserGamepad.buttons[1].value;
  20511. this.buttonX = this.browserGamepad.buttons[2].value;
  20512. this.buttonY = this.browserGamepad.buttons[3].value;
  20513. this.buttonLB = this.browserGamepad.buttons[4].value;
  20514. this.buttonRB = this.browserGamepad.buttons[5].value;
  20515. this.leftTrigger = this.browserGamepad.buttons[6].value;
  20516. this.rightTrigger = this.browserGamepad.buttons[7].value;
  20517. this.buttonBack = this.browserGamepad.buttons[8].value;
  20518. this.buttonStart = this.browserGamepad.buttons[9].value;
  20519. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  20520. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  20521. this.dPadUp = this.browserGamepad.buttons[12].value;
  20522. this.dPadDown = this.browserGamepad.buttons[13].value;
  20523. this.dPadLeft = this.browserGamepad.buttons[14].value;
  20524. this.dPadRight = this.browserGamepad.buttons[15].value;
  20525. };
  20526. return Xbox360Pad;
  20527. })(Gamepad);
  20528. BABYLON.Xbox360Pad = Xbox360Pad;
  20529. })(BABYLON || (BABYLON = {}));
  20530. var __extends = this.__extends || function (d, b) {
  20531. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20532. function __() { this.constructor = d; }
  20533. __.prototype = b.prototype;
  20534. d.prototype = new __();
  20535. };
  20536. var BABYLON;
  20537. (function (BABYLON) {
  20538. var GamepadCamera = (function (_super) {
  20539. __extends(GamepadCamera, _super);
  20540. function GamepadCamera(name, position, scene) {
  20541. var _this = this;
  20542. _super.call(this, name, position, scene);
  20543. this.angularSensibility = 200;
  20544. this.moveSensibility = 75;
  20545. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  20546. _this._onNewGameConnected(gamepad);
  20547. });
  20548. }
  20549. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  20550. if (gamepad.index === 0) {
  20551. this._gamepad = gamepad;
  20552. }
  20553. };
  20554. GamepadCamera.prototype._checkInputs = function () {
  20555. if (!this._gamepad) {
  20556. return;
  20557. }
  20558. var LSValues = this._gamepad.leftStick;
  20559. var normalizedLX = LSValues.x / this.moveSensibility;
  20560. var normalizedLY = LSValues.y / this.moveSensibility;
  20561. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  20562. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  20563. var RSValues = this._gamepad.rightStick;
  20564. var normalizedRX = RSValues.x / this.angularSensibility;
  20565. var normalizedRY = RSValues.y / this.angularSensibility;
  20566. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  20567. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  20568. ;
  20569. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20570. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  20571. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20572. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  20573. };
  20574. GamepadCamera.prototype.dispose = function () {
  20575. this._gamepads.dispose();
  20576. _super.prototype.dispose.call(this);
  20577. };
  20578. return GamepadCamera;
  20579. })(BABYLON.FreeCamera);
  20580. BABYLON.GamepadCamera = GamepadCamera;
  20581. })(BABYLON || (BABYLON = {}));
  20582. var __extends = this.__extends || function (d, b) {
  20583. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20584. function __() { this.constructor = d; }
  20585. __.prototype = b.prototype;
  20586. d.prototype = new __();
  20587. };
  20588. var BABYLON;
  20589. (function (BABYLON) {
  20590. var LinesMesh = (function (_super) {
  20591. __extends(LinesMesh, _super);
  20592. function LinesMesh(name, scene, updatable) {
  20593. if (typeof updatable === "undefined") { updatable = false; }
  20594. _super.call(this, name, scene);
  20595. this.color = new BABYLON.Color3(1, 1, 1);
  20596. this.alpha = 1;
  20597. this._indices = new Array();
  20598. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  20599. attributes: ["position"],
  20600. uniforms: ["worldViewProjection", "color"],
  20601. needAlphaBlending: true
  20602. });
  20603. }
  20604. Object.defineProperty(LinesMesh.prototype, "material", {
  20605. get: function () {
  20606. return this._colorShader;
  20607. },
  20608. enumerable: true,
  20609. configurable: true
  20610. });
  20611. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  20612. get: function () {
  20613. return false;
  20614. },
  20615. enumerable: true,
  20616. configurable: true
  20617. });
  20618. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  20619. get: function () {
  20620. return false;
  20621. },
  20622. enumerable: true,
  20623. configurable: true
  20624. });
  20625. LinesMesh.prototype._bind = function (subMesh, effect, wireframe) {
  20626. var engine = this.getScene().getEngine();
  20627. var indexToBind = this._geometry.getIndexBuffer();
  20628. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  20629. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  20630. };
  20631. LinesMesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  20632. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20633. return;
  20634. }
  20635. var engine = this.getScene().getEngine();
  20636. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  20637. };
  20638. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  20639. return null;
  20640. };
  20641. LinesMesh.prototype.dispose = function (doNotRecurse) {
  20642. this._colorShader.dispose();
  20643. _super.prototype.dispose.call(this, doNotRecurse);
  20644. };
  20645. return LinesMesh;
  20646. })(BABYLON.Mesh);
  20647. BABYLON.LinesMesh = LinesMesh;
  20648. })(BABYLON || (BABYLON = {}));
  20649. var BABYLON;
  20650. (function (BABYLON) {
  20651. var OutlineRenderer = (function () {
  20652. function OutlineRenderer(scene) {
  20653. this._scene = scene;
  20654. }
  20655. OutlineRenderer.prototype.render = function (subMesh, batch) {
  20656. var scene = this._scene;
  20657. var engine = this._scene.getEngine();
  20658. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  20659. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  20660. return;
  20661. }
  20662. var mesh = subMesh.getRenderingMesh();
  20663. var material = subMesh.getMaterial();
  20664. engine.enableEffect(this._effect);
  20665. this._effect.setFloat("offset", mesh.outlineWidth);
  20666. this._effect.setColor3("color", mesh.outlineColor);
  20667. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  20668. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  20669. if (useBones) {
  20670. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  20671. }
  20672. mesh._bind(subMesh, this._effect, false);
  20673. if (material && material.needAlphaTesting()) {
  20674. var alphaTexture = material.getAlphaTestTexture();
  20675. this._effect.setTexture("diffuseSampler", alphaTexture);
  20676. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  20677. }
  20678. if (hardwareInstancedRendering) {
  20679. mesh._renderWithInstances(subMesh, false, batch, this._effect, engine);
  20680. } else {
  20681. if (batch.renderSelf[subMesh._id]) {
  20682. this._effect.setMatrix("world", mesh.getWorldMatrix());
  20683. mesh._draw(subMesh, true);
  20684. }
  20685. if (batch.visibleInstances[subMesh._id]) {
  20686. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20687. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20688. this._effect.setMatrix("world", instance.getWorldMatrix());
  20689. mesh._draw(subMesh, true);
  20690. }
  20691. }
  20692. }
  20693. };
  20694. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  20695. var defines = [];
  20696. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  20697. var mesh = subMesh.getMesh();
  20698. var material = subMesh.getMaterial();
  20699. if (material && material.needAlphaTesting()) {
  20700. defines.push("#define ALPHATEST");
  20701. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20702. attribs.push(BABYLON.VertexBuffer.UVKind);
  20703. defines.push("#define UV1");
  20704. }
  20705. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20706. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  20707. defines.push("#define UV2");
  20708. }
  20709. }
  20710. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20711. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20712. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20713. defines.push("#define BONES");
  20714. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  20715. }
  20716. if (useInstances) {
  20717. defines.push("#define INSTANCES");
  20718. attribs.push("world0");
  20719. attribs.push("world1");
  20720. attribs.push("world2");
  20721. attribs.push("world3");
  20722. }
  20723. var join = defines.join("\n");
  20724. if (this._cachedDefines != join) {
  20725. this._cachedDefines = join;
  20726. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  20727. }
  20728. return this._effect.isReady();
  20729. };
  20730. return OutlineRenderer;
  20731. })();
  20732. BABYLON.OutlineRenderer = OutlineRenderer;
  20733. })(BABYLON || (BABYLON = {}));
  20734. var BABYLON;
  20735. (function (BABYLON) {
  20736. var MeshAssetTask = (function () {
  20737. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  20738. this.name = name;
  20739. this.meshesNames = meshesNames;
  20740. this.rootUrl = rootUrl;
  20741. this.sceneFilename = sceneFilename;
  20742. this.isCompleted = false;
  20743. }
  20744. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20745. var _this = this;
  20746. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  20747. _this.loadedMeshes = meshes;
  20748. _this.loadedParticleSystems = particleSystems;
  20749. _this.loadedSkeletons = skeletons;
  20750. _this.isCompleted = true;
  20751. if (_this.onSuccess) {
  20752. _this.onSuccess(_this);
  20753. }
  20754. onSuccess();
  20755. }, null, function () {
  20756. if (_this.onError) {
  20757. _this.onError(_this);
  20758. }
  20759. onError();
  20760. });
  20761. };
  20762. return MeshAssetTask;
  20763. })();
  20764. BABYLON.MeshAssetTask = MeshAssetTask;
  20765. var TextFileAssetTask = (function () {
  20766. function TextFileAssetTask(name, url) {
  20767. this.name = name;
  20768. this.url = url;
  20769. this.isCompleted = false;
  20770. }
  20771. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20772. var _this = this;
  20773. BABYLON.Tools.LoadFile(this.url, function (data) {
  20774. _this.text = data;
  20775. _this.isCompleted = true;
  20776. if (_this.onSuccess) {
  20777. _this.onSuccess(_this);
  20778. }
  20779. onSuccess();
  20780. }, null, scene.database, false, function () {
  20781. if (_this.onError) {
  20782. _this.onError(_this);
  20783. }
  20784. onError();
  20785. });
  20786. };
  20787. return TextFileAssetTask;
  20788. })();
  20789. BABYLON.TextFileAssetTask = TextFileAssetTask;
  20790. var BinaryFileAssetTask = (function () {
  20791. function BinaryFileAssetTask(name, url) {
  20792. this.name = name;
  20793. this.url = url;
  20794. this.isCompleted = false;
  20795. }
  20796. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20797. var _this = this;
  20798. BABYLON.Tools.LoadFile(this.url, function (data) {
  20799. _this.data = data;
  20800. _this.isCompleted = true;
  20801. if (_this.onSuccess) {
  20802. _this.onSuccess(_this);
  20803. }
  20804. onSuccess();
  20805. }, null, scene.database, true, function () {
  20806. if (_this.onError) {
  20807. _this.onError(_this);
  20808. }
  20809. onError();
  20810. });
  20811. };
  20812. return BinaryFileAssetTask;
  20813. })();
  20814. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  20815. var ImageAssetTask = (function () {
  20816. function ImageAssetTask(name, url) {
  20817. this.name = name;
  20818. this.url = url;
  20819. this.isCompleted = false;
  20820. }
  20821. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20822. var _this = this;
  20823. var img = new Image();
  20824. img.onload = function () {
  20825. _this.image = img;
  20826. _this.isCompleted = true;
  20827. if (_this.onSuccess) {
  20828. _this.onSuccess(_this);
  20829. }
  20830. onSuccess();
  20831. };
  20832. img.onerror = function () {
  20833. if (_this.onError) {
  20834. _this.onError(_this);
  20835. }
  20836. onError();
  20837. };
  20838. img.src = this.url;
  20839. };
  20840. return ImageAssetTask;
  20841. })();
  20842. BABYLON.ImageAssetTask = ImageAssetTask;
  20843. var TextureAssetTask = (function () {
  20844. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  20845. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20846. this.name = name;
  20847. this.url = url;
  20848. this.noMipmap = noMipmap;
  20849. this.invertY = invertY;
  20850. this.samplingMode = samplingMode;
  20851. this.isCompleted = false;
  20852. }
  20853. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20854. var _this = this;
  20855. var onload = function () {
  20856. _this.isCompleted = true;
  20857. if (_this.onSuccess) {
  20858. _this.onSuccess(_this);
  20859. }
  20860. onSuccess();
  20861. };
  20862. var onerror = function () {
  20863. if (_this.onError) {
  20864. _this.onError(_this);
  20865. }
  20866. onError();
  20867. };
  20868. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  20869. };
  20870. return TextureAssetTask;
  20871. })();
  20872. BABYLON.TextureAssetTask = TextureAssetTask;
  20873. var AssetsManager = (function () {
  20874. function AssetsManager(scene) {
  20875. this._tasks = new Array();
  20876. this._waitingTasksCount = 0;
  20877. this.useDefaultLoadingScreen = true;
  20878. this._scene = scene;
  20879. }
  20880. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  20881. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  20882. this._tasks.push(task);
  20883. return task;
  20884. };
  20885. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  20886. var task = new TextFileAssetTask(taskName, url);
  20887. this._tasks.push(task);
  20888. return task;
  20889. };
  20890. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  20891. var task = new BinaryFileAssetTask(taskName, url);
  20892. this._tasks.push(task);
  20893. return task;
  20894. };
  20895. AssetsManager.prototype.addImageTask = function (taskName, url) {
  20896. var task = new ImageAssetTask(taskName, url);
  20897. this._tasks.push(task);
  20898. return task;
  20899. };
  20900. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  20901. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20902. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  20903. this._tasks.push(task);
  20904. return task;
  20905. };
  20906. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  20907. this._waitingTasksCount--;
  20908. if (this._waitingTasksCount === 0) {
  20909. if (this.onFinish) {
  20910. this.onFinish(this._tasks);
  20911. }
  20912. this._scene.getEngine().hideLoadingUI();
  20913. }
  20914. };
  20915. AssetsManager.prototype._runTask = function (task) {
  20916. var _this = this;
  20917. task.run(this._scene, function () {
  20918. if (_this.onTaskSuccess) {
  20919. _this.onTaskSuccess(task);
  20920. }
  20921. _this._decreaseWaitingTasksCount();
  20922. }, function () {
  20923. if (_this.onTaskError) {
  20924. _this.onTaskError(task);
  20925. }
  20926. _this._decreaseWaitingTasksCount();
  20927. });
  20928. };
  20929. AssetsManager.prototype.reset = function () {
  20930. this._tasks = new Array();
  20931. return this;
  20932. };
  20933. AssetsManager.prototype.load = function () {
  20934. this._waitingTasksCount = this._tasks.length;
  20935. if (this._waitingTasksCount === 0) {
  20936. if (this.onFinish) {
  20937. this.onFinish(this._tasks);
  20938. }
  20939. return this;
  20940. }
  20941. if (this.useDefaultLoadingScreen) {
  20942. this._scene.getEngine().displayLoadingUI();
  20943. }
  20944. for (var index = 0; index < this._tasks.length; index++) {
  20945. var task = this._tasks[index];
  20946. this._runTask(task);
  20947. }
  20948. return this;
  20949. };
  20950. return AssetsManager;
  20951. })();
  20952. BABYLON.AssetsManager = AssetsManager;
  20953. })(BABYLON || (BABYLON = {}));
  20954. var __extends = this.__extends || function (d, b) {
  20955. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20956. function __() { this.constructor = d; }
  20957. __.prototype = b.prototype;
  20958. d.prototype = new __();
  20959. };
  20960. var BABYLON;
  20961. (function (BABYLON) {
  20962. var VRDeviceOrientationCamera = (function (_super) {
  20963. __extends(VRDeviceOrientationCamera, _super);
  20964. function VRDeviceOrientationCamera(name, position, scene) {
  20965. _super.call(this, name, position, scene);
  20966. this._alpha = 0;
  20967. this._beta = 0;
  20968. this._gamma = 0;
  20969. }
  20970. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  20971. this._alpha = +evt.alpha | 0;
  20972. this._beta = +evt.beta | 0;
  20973. this._gamma = +evt.gamma | 0;
  20974. if (this._gamma < 0) {
  20975. this._gamma = 90 + this._gamma;
  20976. } else {
  20977. this._gamma = 270 - this._gamma;
  20978. }
  20979. this.rotation.x = this._gamma / 180.0 * Math.PI;
  20980. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  20981. this.rotation.z = this._beta / 180.0 * Math.PI;
  20982. };
  20983. return VRDeviceOrientationCamera;
  20984. })(BABYLON.OculusCamera);
  20985. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  20986. })(BABYLON || (BABYLON = {}));
  20987. var __extends = this.__extends || function (d, b) {
  20988. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20989. function __() { this.constructor = d; }
  20990. __.prototype = b.prototype;
  20991. d.prototype = new __();
  20992. };
  20993. var BABYLON;
  20994. (function (BABYLON) {
  20995. var WebVRCamera = (function (_super) {
  20996. __extends(WebVRCamera, _super);
  20997. function WebVRCamera(name, position, scene) {
  20998. _super.call(this, name, position, scene);
  20999. this._hmdDevice = null;
  21000. this._sensorDevice = null;
  21001. this._cacheState = null;
  21002. this._cacheQuaternion = new BABYLON.Quaternion();
  21003. this._cacheRotation = BABYLON.Vector3.Zero();
  21004. this._vrEnabled = false;
  21005. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  21006. }
  21007. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  21008. var size = devices.length;
  21009. var i = 0;
  21010. this._sensorDevice = null;
  21011. this._hmdDevice = null;
  21012. while (i < size && this._hmdDevice === null) {
  21013. if (devices[i] instanceof HMDVRDevice) {
  21014. this._hmdDevice = devices[i];
  21015. }
  21016. i++;
  21017. }
  21018. i = 0;
  21019. while (i < size && this._sensorDevice === null) {
  21020. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  21021. this._sensorDevice = devices[i];
  21022. }
  21023. i++;
  21024. }
  21025. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  21026. };
  21027. WebVRCamera.prototype._update = function () {
  21028. if (this._vrEnabled) {
  21029. this._cacheState = this._sensorDevice.getState();
  21030. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  21031. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  21032. this.rotation.x = -this._cacheRotation.z;
  21033. this.rotation.y = -this._cacheRotation.y;
  21034. this.rotation.z = this._cacheRotation.x;
  21035. }
  21036. _super.prototype._update.call(this);
  21037. };
  21038. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  21039. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21040. if (navigator.getVRDevices) {
  21041. navigator.getVRDevices().then(this._getWebVRDevices);
  21042. } else if (navigator.mozGetVRDevices) {
  21043. navigator.mozGetVRDevices(this._getWebVRDevices);
  21044. }
  21045. };
  21046. WebVRCamera.prototype.detachControl = function (element) {
  21047. _super.prototype.detachControl.call(this, element);
  21048. this._vrEnabled = false;
  21049. };
  21050. return WebVRCamera;
  21051. })(BABYLON.OculusCamera);
  21052. BABYLON.WebVRCamera = WebVRCamera;
  21053. })(BABYLON || (BABYLON = {}));