babylon.2.0-alpha.debug.js 1.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121
  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.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  659. var matrix = world.multiply(transform);
  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.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  671. var matrix = world.multiply(view).multiply(projection);
  672. matrix.invert();
  673. source.x = source.x / viewportWidth * 2 - 1;
  674. source.y = -(source.y / viewportHeight * 2 - 1);
  675. var vector = BABYLON.Vector3.TransformCoordinates(source, matrix);
  676. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  677. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  678. vector = vector.scale(1.0 / num);
  679. }
  680. return vector;
  681. };
  682. Vector3.Minimize = function (left, right) {
  683. var min = left.clone();
  684. min.MinimizeInPlace(right);
  685. return min;
  686. };
  687. Vector3.Maximize = function (left, right) {
  688. var max = left.clone();
  689. max.MaximizeInPlace(right);
  690. return max;
  691. };
  692. Vector3.Distance = function (value1, value2) {
  693. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  694. };
  695. Vector3.DistanceSquared = function (value1, value2) {
  696. var x = value1.x - value2.x;
  697. var y = value1.y - value2.y;
  698. var z = value1.z - value2.z;
  699. return (x * x) + (y * y) + (z * z);
  700. };
  701. Vector3.Center = function (value1, value2) {
  702. var center = value1.add(value2);
  703. center.scaleInPlace(0.5);
  704. return center;
  705. };
  706. return Vector3;
  707. })();
  708. BABYLON.Vector3 = Vector3;
  709. var Vector4 = (function () {
  710. function Vector4(x, y, z, w) {
  711. this.x = x;
  712. this.y = y;
  713. this.z = z;
  714. this.w = w;
  715. }
  716. Vector4.prototype.toString = function () {
  717. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  718. };
  719. Vector4.prototype.asArray = function () {
  720. var result = [];
  721. this.toArray(result, 0);
  722. return result;
  723. };
  724. Vector4.prototype.toArray = function (array, index) {
  725. if (index === undefined) {
  726. index = 0;
  727. }
  728. array[index] = this.x;
  729. array[index + 1] = this.y;
  730. array[index + 2] = this.z;
  731. array[index + 3] = this.w;
  732. };
  733. Vector4.prototype.addInPlace = function (otherVector) {
  734. this.x += otherVector.x;
  735. this.y += otherVector.y;
  736. this.z += otherVector.z;
  737. this.w += otherVector.w;
  738. };
  739. Vector4.prototype.add = function (otherVector) {
  740. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  741. };
  742. Vector4.prototype.addToRef = function (otherVector, result) {
  743. result.x = this.x + otherVector.x;
  744. result.y = this.y + otherVector.y;
  745. result.z = this.z + otherVector.z;
  746. result.w = this.w + otherVector.w;
  747. };
  748. Vector4.prototype.subtractInPlace = function (otherVector) {
  749. this.x -= otherVector.x;
  750. this.y -= otherVector.y;
  751. this.z -= otherVector.z;
  752. this.w -= otherVector.w;
  753. };
  754. Vector4.prototype.subtract = function (otherVector) {
  755. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  756. };
  757. Vector4.prototype.subtractToRef = function (otherVector, result) {
  758. result.x = this.x - otherVector.x;
  759. result.y = this.y - otherVector.y;
  760. result.z = this.z - otherVector.z;
  761. result.w = this.w - otherVector.w;
  762. };
  763. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  764. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  765. };
  766. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  767. result.x = this.x - x;
  768. result.y = this.y - y;
  769. result.z = this.z - z;
  770. result.w = this.w - w;
  771. };
  772. Vector4.prototype.negate = function () {
  773. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  774. };
  775. Vector4.prototype.scaleInPlace = function (scale) {
  776. this.x *= scale;
  777. this.y *= scale;
  778. this.z *= scale;
  779. this.w *= scale;
  780. return this;
  781. };
  782. Vector4.prototype.scale = function (scale) {
  783. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  784. };
  785. Vector4.prototype.scaleToRef = function (scale, result) {
  786. result.x = this.x * scale;
  787. result.y = this.y * scale;
  788. result.z = this.z * scale;
  789. result.w = this.w * scale;
  790. };
  791. Vector4.prototype.equals = function (otherVector) {
  792. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  793. };
  794. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  795. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  796. };
  797. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  798. return this.x === x && this.y === y && this.z === z && this.w === w;
  799. };
  800. Vector4.prototype.multiplyInPlace = function (otherVector) {
  801. this.x *= otherVector.x;
  802. this.y *= otherVector.y;
  803. this.z *= otherVector.z;
  804. this.w *= otherVector.w;
  805. };
  806. Vector4.prototype.multiply = function (otherVector) {
  807. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  808. };
  809. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  810. result.x = this.x * otherVector.x;
  811. result.y = this.y * otherVector.y;
  812. result.z = this.z * otherVector.z;
  813. result.w = this.w * otherVector.w;
  814. };
  815. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  816. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  817. };
  818. Vector4.prototype.divide = function (otherVector) {
  819. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  820. };
  821. Vector4.prototype.divideToRef = function (otherVector, result) {
  822. result.x = this.x / otherVector.x;
  823. result.y = this.y / otherVector.y;
  824. result.z = this.z / otherVector.z;
  825. result.w = this.w / otherVector.w;
  826. };
  827. Vector4.prototype.MinimizeInPlace = function (other) {
  828. if (other.x < this.x)
  829. this.x = other.x;
  830. if (other.y < this.y)
  831. this.y = other.y;
  832. if (other.z < this.z)
  833. this.z = other.z;
  834. if (other.w < this.w)
  835. this.w = other.w;
  836. };
  837. Vector4.prototype.MaximizeInPlace = function (other) {
  838. if (other.x > this.x)
  839. this.x = other.x;
  840. if (other.y > this.y)
  841. this.y = other.y;
  842. if (other.z > this.z)
  843. this.z = other.z;
  844. if (other.w > this.w)
  845. this.w = other.w;
  846. };
  847. Vector4.prototype.length = function () {
  848. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  849. };
  850. Vector4.prototype.lengthSquared = function () {
  851. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  852. };
  853. Vector4.prototype.normalize = function () {
  854. var len = this.length();
  855. if (len === 0)
  856. return this;
  857. var num = 1.0 / len;
  858. this.x *= num;
  859. this.y *= num;
  860. this.z *= num;
  861. this.w *= num;
  862. return this;
  863. };
  864. Vector4.prototype.clone = function () {
  865. return new Vector4(this.x, this.y, this.z, this.w);
  866. };
  867. Vector4.prototype.copyFrom = function (source) {
  868. this.x = source.x;
  869. this.y = source.y;
  870. this.z = source.z;
  871. this.w = source.w;
  872. };
  873. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  874. this.x = x;
  875. this.y = y;
  876. this.z = z;
  877. this.w = w;
  878. };
  879. Vector4.FromArray = function (array, offset) {
  880. if (!offset) {
  881. offset = 0;
  882. }
  883. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  884. };
  885. Vector4.FromArrayToRef = function (array, offset, result) {
  886. result.x = array[offset];
  887. result.y = array[offset + 1];
  888. result.z = array[offset + 2];
  889. result.w = array[offset + 3];
  890. };
  891. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  892. result.x = array[offset];
  893. result.y = array[offset + 1];
  894. result.z = array[offset + 2];
  895. result.w = array[offset + 3];
  896. };
  897. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  898. result.x = x;
  899. result.y = y;
  900. result.z = z;
  901. result.w = w;
  902. };
  903. Vector4.Zero = function () {
  904. return new Vector4(0, 0, 0, 0);
  905. };
  906. Vector4.Normalize = function (vector) {
  907. var result = Vector4.Zero();
  908. Vector4.NormalizeToRef(vector, result);
  909. return result;
  910. };
  911. Vector4.NormalizeToRef = function (vector, result) {
  912. result.copyFrom(vector);
  913. result.normalize();
  914. };
  915. Vector4.Minimize = function (left, right) {
  916. var min = left.clone();
  917. min.MinimizeInPlace(right);
  918. return min;
  919. };
  920. Vector4.Maximize = function (left, right) {
  921. var max = left.clone();
  922. max.MaximizeInPlace(right);
  923. return max;
  924. };
  925. Vector4.Distance = function (value1, value2) {
  926. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  927. };
  928. Vector4.DistanceSquared = function (value1, value2) {
  929. var x = value1.x - value2.x;
  930. var y = value1.y - value2.y;
  931. var z = value1.z - value2.z;
  932. var w = value1.w - value2.w;
  933. return (x * x) + (y * y) + (z * z) + (w * w);
  934. };
  935. Vector4.Center = function (value1, value2) {
  936. var center = value1.add(value2);
  937. center.scaleInPlace(0.5);
  938. return center;
  939. };
  940. return Vector4;
  941. })();
  942. BABYLON.Vector4 = Vector4;
  943. var Quaternion = (function () {
  944. function Quaternion(x, y, z, w) {
  945. if (typeof x === "undefined") { x = 0; }
  946. if (typeof y === "undefined") { y = 0; }
  947. if (typeof z === "undefined") { z = 0; }
  948. if (typeof w === "undefined") { w = 1; }
  949. this.x = x;
  950. this.y = y;
  951. this.z = z;
  952. this.w = w;
  953. }
  954. Quaternion.prototype.toString = function () {
  955. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  956. };
  957. Quaternion.prototype.asArray = function () {
  958. return [this.x, this.y, this.z, this.w];
  959. };
  960. Quaternion.prototype.equals = function (otherQuaternion) {
  961. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  962. };
  963. Quaternion.prototype.clone = function () {
  964. return new Quaternion(this.x, this.y, this.z, this.w);
  965. };
  966. Quaternion.prototype.copyFrom = function (other) {
  967. this.x = other.x;
  968. this.y = other.y;
  969. this.z = other.z;
  970. this.w = other.w;
  971. };
  972. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  973. this.x = x;
  974. this.y = y;
  975. this.z = z;
  976. this.w = w;
  977. };
  978. Quaternion.prototype.add = function (other) {
  979. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  980. };
  981. Quaternion.prototype.subtract = function (other) {
  982. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  983. };
  984. Quaternion.prototype.scale = function (value) {
  985. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  986. };
  987. Quaternion.prototype.multiply = function (q1) {
  988. var result = new Quaternion(0, 0, 0, 1.0);
  989. this.multiplyToRef(q1, result);
  990. return result;
  991. };
  992. Quaternion.prototype.multiplyToRef = function (q1, result) {
  993. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  994. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  995. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  996. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  997. };
  998. Quaternion.prototype.length = function () {
  999. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1000. };
  1001. Quaternion.prototype.normalize = function () {
  1002. var length = 1.0 / this.length();
  1003. this.x *= length;
  1004. this.y *= length;
  1005. this.z *= length;
  1006. this.w *= length;
  1007. };
  1008. Quaternion.prototype.toEulerAngles = function () {
  1009. var result = Vector3.Zero();
  1010. this.toEulerAnglesToRef(result);
  1011. return result;
  1012. };
  1013. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1014. var qx = this.x;
  1015. var qy = this.y;
  1016. var qz = this.z;
  1017. var qw = this.w;
  1018. var qxy = qx * qy;
  1019. var qxz = qx * qz;
  1020. var qwy = qw * qy;
  1021. var qwz = qw * qz;
  1022. var qwx = qw * qx;
  1023. var qyz = qy * qz;
  1024. var sqx = qx * qx;
  1025. var sqy = qy * qy;
  1026. var determinant = sqx + sqy;
  1027. if (determinant != 0.000 && determinant != 1.000) {
  1028. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1029. result.y = Math.acos(1 - 2 * determinant);
  1030. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1031. } else {
  1032. if (determinant == 0.000) {
  1033. result.x = 0.0;
  1034. result.y = 0.0;
  1035. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz);
  1036. } else {
  1037. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz);
  1038. result.y = Math.PI;
  1039. result.z = 0.0;
  1040. }
  1041. }
  1042. };
  1043. Quaternion.prototype.toRotationMatrix = function (result) {
  1044. var xx = this.x * this.x;
  1045. var yy = this.y * this.y;
  1046. var zz = this.z * this.z;
  1047. var xy = this.x * this.y;
  1048. var zw = this.z * this.w;
  1049. var zx = this.z * this.x;
  1050. var yw = this.y * this.w;
  1051. var yz = this.y * this.z;
  1052. var xw = this.x * this.w;
  1053. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1054. result.m[1] = 2.0 * (xy + zw);
  1055. result.m[2] = 2.0 * (zx - yw);
  1056. result.m[3] = 0;
  1057. result.m[4] = 2.0 * (xy - zw);
  1058. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1059. result.m[6] = 2.0 * (yz + xw);
  1060. result.m[7] = 0;
  1061. result.m[8] = 2.0 * (zx + yw);
  1062. result.m[9] = 2.0 * (yz - xw);
  1063. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1064. result.m[11] = 0;
  1065. result.m[12] = 0;
  1066. result.m[13] = 0;
  1067. result.m[14] = 0;
  1068. result.m[15] = 1.0;
  1069. };
  1070. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1071. var data = matrix.m;
  1072. var m11 = data[0], m12 = data[4], m13 = data[8];
  1073. var m21 = data[1], m22 = data[5], m23 = data[9];
  1074. var m31 = data[2], m32 = data[6], m33 = data[10];
  1075. var trace = m11 + m22 + m33;
  1076. var s;
  1077. if (trace > 0) {
  1078. s = 0.5 / Math.sqrt(trace + 1.0);
  1079. this.w = 0.25 / s;
  1080. this.x = (m32 - m23) * s;
  1081. this.y = (m13 - m31) * s;
  1082. this.z = (m21 - m12) * s;
  1083. return;
  1084. }
  1085. if (m11 > m22 && m11 > m33) {
  1086. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1087. this.w = (m32 - m23) / s;
  1088. this.x = 0.25 * s;
  1089. this.y = (m12 + m21) / s;
  1090. this.z = (m13 + m31) / s;
  1091. return;
  1092. }
  1093. if (m22 > m33) {
  1094. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1095. this.w = (m13 - m31) / s;
  1096. this.x = (m12 + m21) / s;
  1097. this.y = 0.25 * s;
  1098. this.z = (m23 + m32) / s;
  1099. return;
  1100. }
  1101. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1102. this.w = (m21 - m12) / s;
  1103. this.x = (m13 + m31) / s;
  1104. this.y = (m23 + m32) / s;
  1105. this.z = 0.25 * s;
  1106. };
  1107. Quaternion.Inverse = function (q) {
  1108. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1109. };
  1110. Quaternion.RotationAxis = function (axis, angle) {
  1111. var result = new Quaternion();
  1112. var sin = Math.sin(angle / 2);
  1113. result.w = Math.cos(angle / 2);
  1114. result.x = axis.x * sin;
  1115. result.y = axis.y * sin;
  1116. result.z = axis.z * sin;
  1117. return result;
  1118. };
  1119. Quaternion.FromArray = function (array, offset) {
  1120. if (!offset) {
  1121. offset = 0;
  1122. }
  1123. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1124. };
  1125. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1126. var result = new Quaternion();
  1127. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1128. return result;
  1129. };
  1130. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1131. var halfRoll = roll * 0.5;
  1132. var halfPitch = pitch * 0.5;
  1133. var halfYaw = yaw * 0.5;
  1134. var sinRoll = Math.sin(halfRoll);
  1135. var cosRoll = Math.cos(halfRoll);
  1136. var sinPitch = Math.sin(halfPitch);
  1137. var cosPitch = Math.cos(halfPitch);
  1138. var sinYaw = Math.sin(halfYaw);
  1139. var cosYaw = Math.cos(halfYaw);
  1140. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1141. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1142. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1143. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1144. };
  1145. Quaternion.Slerp = function (left, right, amount) {
  1146. var num2;
  1147. var num3;
  1148. var num = amount;
  1149. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1150. var flag = false;
  1151. if (num4 < 0) {
  1152. flag = true;
  1153. num4 = -num4;
  1154. }
  1155. if (num4 > 0.999999) {
  1156. num3 = 1 - num;
  1157. num2 = flag ? -num : num;
  1158. } else {
  1159. var num5 = Math.acos(num4);
  1160. var num6 = (1.0 / Math.sin(num5));
  1161. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1162. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1163. }
  1164. 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));
  1165. };
  1166. return Quaternion;
  1167. })();
  1168. BABYLON.Quaternion = Quaternion;
  1169. var Matrix = (function () {
  1170. function Matrix() {
  1171. this.m = new Float32Array(16);
  1172. }
  1173. Matrix.prototype.isIdentity = function () {
  1174. if (this.m[0] != 1.0 || this.m[5] != 1.0 || this.m[10] != 1.0 || this.m[15] != 1.0)
  1175. return false;
  1176. 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)
  1177. return false;
  1178. return true;
  1179. };
  1180. Matrix.prototype.determinant = function () {
  1181. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1182. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1183. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1184. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1185. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1186. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1187. 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))));
  1188. };
  1189. Matrix.prototype.toArray = function () {
  1190. return this.m;
  1191. };
  1192. Matrix.prototype.asArray = function () {
  1193. return this.toArray();
  1194. };
  1195. Matrix.prototype.invert = function () {
  1196. this.invertToRef(this);
  1197. };
  1198. Matrix.prototype.invertToRef = function (other) {
  1199. var l1 = this.m[0];
  1200. var l2 = this.m[1];
  1201. var l3 = this.m[2];
  1202. var l4 = this.m[3];
  1203. var l5 = this.m[4];
  1204. var l6 = this.m[5];
  1205. var l7 = this.m[6];
  1206. var l8 = this.m[7];
  1207. var l9 = this.m[8];
  1208. var l10 = this.m[9];
  1209. var l11 = this.m[10];
  1210. var l12 = this.m[11];
  1211. var l13 = this.m[12];
  1212. var l14 = this.m[13];
  1213. var l15 = this.m[14];
  1214. var l16 = this.m[15];
  1215. var l17 = (l11 * l16) - (l12 * l15);
  1216. var l18 = (l10 * l16) - (l12 * l14);
  1217. var l19 = (l10 * l15) - (l11 * l14);
  1218. var l20 = (l9 * l16) - (l12 * l13);
  1219. var l21 = (l9 * l15) - (l11 * l13);
  1220. var l22 = (l9 * l14) - (l10 * l13);
  1221. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1222. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1223. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1224. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1225. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1226. var l28 = (l7 * l16) - (l8 * l15);
  1227. var l29 = (l6 * l16) - (l8 * l14);
  1228. var l30 = (l6 * l15) - (l7 * l14);
  1229. var l31 = (l5 * l16) - (l8 * l13);
  1230. var l32 = (l5 * l15) - (l7 * l13);
  1231. var l33 = (l5 * l14) - (l6 * l13);
  1232. var l34 = (l7 * l12) - (l8 * l11);
  1233. var l35 = (l6 * l12) - (l8 * l10);
  1234. var l36 = (l6 * l11) - (l7 * l10);
  1235. var l37 = (l5 * l12) - (l8 * l9);
  1236. var l38 = (l5 * l11) - (l7 * l9);
  1237. var l39 = (l5 * l10) - (l6 * l9);
  1238. other.m[0] = l23 * l27;
  1239. other.m[4] = l24 * l27;
  1240. other.m[8] = l25 * l27;
  1241. other.m[12] = l26 * l27;
  1242. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1243. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1244. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1245. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1246. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1247. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1248. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1249. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1250. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1251. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1252. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1253. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1254. };
  1255. Matrix.prototype.setTranslation = function (vector3) {
  1256. this.m[12] = vector3.x;
  1257. this.m[13] = vector3.y;
  1258. this.m[14] = vector3.z;
  1259. };
  1260. Matrix.prototype.multiply = function (other) {
  1261. var result = new Matrix();
  1262. this.multiplyToRef(other, result);
  1263. return result;
  1264. };
  1265. Matrix.prototype.copyFrom = function (other) {
  1266. for (var index = 0; index < 16; index++) {
  1267. this.m[index] = other.m[index];
  1268. }
  1269. };
  1270. Matrix.prototype.copyToArray = function (array, offset) {
  1271. if (typeof offset === "undefined") { offset = 0; }
  1272. for (var index = 0; index < 16; index++) {
  1273. array[offset + index] = this.m[index];
  1274. }
  1275. };
  1276. Matrix.prototype.multiplyToRef = function (other, result) {
  1277. this.multiplyToArray(other, result.m, 0);
  1278. };
  1279. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1280. var tm0 = this.m[0];
  1281. var tm1 = this.m[1];
  1282. var tm2 = this.m[2];
  1283. var tm3 = this.m[3];
  1284. var tm4 = this.m[4];
  1285. var tm5 = this.m[5];
  1286. var tm6 = this.m[6];
  1287. var tm7 = this.m[7];
  1288. var tm8 = this.m[8];
  1289. var tm9 = this.m[9];
  1290. var tm10 = this.m[10];
  1291. var tm11 = this.m[11];
  1292. var tm12 = this.m[12];
  1293. var tm13 = this.m[13];
  1294. var tm14 = this.m[14];
  1295. var tm15 = this.m[15];
  1296. var om0 = other.m[0];
  1297. var om1 = other.m[1];
  1298. var om2 = other.m[2];
  1299. var om3 = other.m[3];
  1300. var om4 = other.m[4];
  1301. var om5 = other.m[5];
  1302. var om6 = other.m[6];
  1303. var om7 = other.m[7];
  1304. var om8 = other.m[8];
  1305. var om9 = other.m[9];
  1306. var om10 = other.m[10];
  1307. var om11 = other.m[11];
  1308. var om12 = other.m[12];
  1309. var om13 = other.m[13];
  1310. var om14 = other.m[14];
  1311. var om15 = other.m[15];
  1312. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1313. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1314. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1315. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1316. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1317. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1318. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1319. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1320. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1321. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1322. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1323. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1324. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1325. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1326. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1327. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1328. };
  1329. Matrix.prototype.equals = function (value) {
  1330. 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]);
  1331. };
  1332. Matrix.prototype.clone = function () {
  1333. 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]);
  1334. };
  1335. Matrix.FromArray = function (array, offset) {
  1336. var result = new Matrix();
  1337. if (!offset) {
  1338. offset = 0;
  1339. }
  1340. Matrix.FromArrayToRef(array, offset, result);
  1341. return result;
  1342. };
  1343. Matrix.FromArrayToRef = function (array, offset, result) {
  1344. for (var index = 0; index < 16; index++) {
  1345. result.m[index] = array[index + offset];
  1346. }
  1347. };
  1348. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1349. result.m[0] = initialM11;
  1350. result.m[1] = initialM12;
  1351. result.m[2] = initialM13;
  1352. result.m[3] = initialM14;
  1353. result.m[4] = initialM21;
  1354. result.m[5] = initialM22;
  1355. result.m[6] = initialM23;
  1356. result.m[7] = initialM24;
  1357. result.m[8] = initialM31;
  1358. result.m[9] = initialM32;
  1359. result.m[10] = initialM33;
  1360. result.m[11] = initialM34;
  1361. result.m[12] = initialM41;
  1362. result.m[13] = initialM42;
  1363. result.m[14] = initialM43;
  1364. result.m[15] = initialM44;
  1365. };
  1366. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1367. var result = new Matrix();
  1368. result.m[0] = initialM11;
  1369. result.m[1] = initialM12;
  1370. result.m[2] = initialM13;
  1371. result.m[3] = initialM14;
  1372. result.m[4] = initialM21;
  1373. result.m[5] = initialM22;
  1374. result.m[6] = initialM23;
  1375. result.m[7] = initialM24;
  1376. result.m[8] = initialM31;
  1377. result.m[9] = initialM32;
  1378. result.m[10] = initialM33;
  1379. result.m[11] = initialM34;
  1380. result.m[12] = initialM41;
  1381. result.m[13] = initialM42;
  1382. result.m[14] = initialM43;
  1383. result.m[15] = initialM44;
  1384. return result;
  1385. };
  1386. Matrix.Identity = function () {
  1387. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1388. };
  1389. Matrix.IdentityToRef = function (result) {
  1390. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1391. };
  1392. Matrix.Zero = function () {
  1393. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1394. };
  1395. Matrix.RotationX = function (angle) {
  1396. var result = new Matrix();
  1397. Matrix.RotationXToRef(angle, result);
  1398. return result;
  1399. };
  1400. Matrix.Invert = function (source) {
  1401. var result = new Matrix();
  1402. source.invertToRef(result);
  1403. return result;
  1404. };
  1405. Matrix.RotationXToRef = function (angle, result) {
  1406. var s = Math.sin(angle);
  1407. var c = Math.cos(angle);
  1408. result.m[0] = 1.0;
  1409. result.m[15] = 1.0;
  1410. result.m[5] = c;
  1411. result.m[10] = c;
  1412. result.m[9] = -s;
  1413. result.m[6] = s;
  1414. result.m[1] = 0;
  1415. result.m[2] = 0;
  1416. result.m[3] = 0;
  1417. result.m[4] = 0;
  1418. result.m[7] = 0;
  1419. result.m[8] = 0;
  1420. result.m[11] = 0;
  1421. result.m[12] = 0;
  1422. result.m[13] = 0;
  1423. result.m[14] = 0;
  1424. };
  1425. Matrix.RotationY = function (angle) {
  1426. var result = new Matrix();
  1427. Matrix.RotationYToRef(angle, result);
  1428. return result;
  1429. };
  1430. Matrix.RotationYToRef = function (angle, result) {
  1431. var s = Math.sin(angle);
  1432. var c = Math.cos(angle);
  1433. result.m[5] = 1.0;
  1434. result.m[15] = 1.0;
  1435. result.m[0] = c;
  1436. result.m[2] = -s;
  1437. result.m[8] = s;
  1438. result.m[10] = c;
  1439. result.m[1] = 0;
  1440. result.m[3] = 0;
  1441. result.m[4] = 0;
  1442. result.m[6] = 0;
  1443. result.m[7] = 0;
  1444. result.m[9] = 0;
  1445. result.m[11] = 0;
  1446. result.m[12] = 0;
  1447. result.m[13] = 0;
  1448. result.m[14] = 0;
  1449. };
  1450. Matrix.RotationZ = function (angle) {
  1451. var result = new Matrix();
  1452. Matrix.RotationZToRef(angle, result);
  1453. return result;
  1454. };
  1455. Matrix.RotationZToRef = function (angle, result) {
  1456. var s = Math.sin(angle);
  1457. var c = Math.cos(angle);
  1458. result.m[10] = 1.0;
  1459. result.m[15] = 1.0;
  1460. result.m[0] = c;
  1461. result.m[1] = s;
  1462. result.m[4] = -s;
  1463. result.m[5] = c;
  1464. result.m[2] = 0;
  1465. result.m[3] = 0;
  1466. result.m[6] = 0;
  1467. result.m[7] = 0;
  1468. result.m[8] = 0;
  1469. result.m[9] = 0;
  1470. result.m[11] = 0;
  1471. result.m[12] = 0;
  1472. result.m[13] = 0;
  1473. result.m[14] = 0;
  1474. };
  1475. Matrix.RotationAxis = function (axis, angle) {
  1476. var s = Math.sin(-angle);
  1477. var c = Math.cos(-angle);
  1478. var c1 = 1 - c;
  1479. axis.normalize();
  1480. var result = Matrix.Zero();
  1481. result.m[0] = (axis.x * axis.x) * c1 + c;
  1482. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1483. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1484. result.m[3] = 0.0;
  1485. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1486. result.m[5] = (axis.y * axis.y) * c1 + c;
  1487. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1488. result.m[7] = 0.0;
  1489. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1490. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1491. result.m[10] = (axis.z * axis.z) * c1 + c;
  1492. result.m[11] = 0.0;
  1493. result.m[15] = 1.0;
  1494. return result;
  1495. };
  1496. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1497. var result = new Matrix();
  1498. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1499. return result;
  1500. };
  1501. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1502. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1503. this._tempQuaternion.toRotationMatrix(result);
  1504. };
  1505. Matrix.Scaling = function (x, y, z) {
  1506. var result = Matrix.Zero();
  1507. Matrix.ScalingToRef(x, y, z, result);
  1508. return result;
  1509. };
  1510. Matrix.ScalingToRef = function (x, y, z, result) {
  1511. result.m[0] = x;
  1512. result.m[1] = 0;
  1513. result.m[2] = 0;
  1514. result.m[3] = 0;
  1515. result.m[4] = 0;
  1516. result.m[5] = y;
  1517. result.m[6] = 0;
  1518. result.m[7] = 0;
  1519. result.m[8] = 0;
  1520. result.m[9] = 0;
  1521. result.m[10] = z;
  1522. result.m[11] = 0;
  1523. result.m[12] = 0;
  1524. result.m[13] = 0;
  1525. result.m[14] = 0;
  1526. result.m[15] = 1.0;
  1527. };
  1528. Matrix.Translation = function (x, y, z) {
  1529. var result = Matrix.Identity();
  1530. Matrix.TranslationToRef(x, y, z, result);
  1531. return result;
  1532. };
  1533. Matrix.TranslationToRef = function (x, y, z, result) {
  1534. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1535. };
  1536. Matrix.LookAtLH = function (eye, target, up) {
  1537. var result = Matrix.Zero();
  1538. Matrix.LookAtLHToRef(eye, target, up, result);
  1539. return result;
  1540. };
  1541. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1542. target.subtractToRef(eye, this._zAxis);
  1543. this._zAxis.normalize();
  1544. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1545. this._xAxis.normalize();
  1546. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1547. this._yAxis.normalize();
  1548. var ex = -Vector3.Dot(this._xAxis, eye);
  1549. var ey = -Vector3.Dot(this._yAxis, eye);
  1550. var ez = -Vector3.Dot(this._zAxis, eye);
  1551. 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);
  1552. };
  1553. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1554. var hw = 2.0 / width;
  1555. var hh = 2.0 / height;
  1556. var id = 1.0 / (zfar - znear);
  1557. var nid = znear / (znear - zfar);
  1558. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1559. };
  1560. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1561. var matrix = Matrix.Zero();
  1562. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1563. return matrix;
  1564. };
  1565. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1566. result.m[0] = 2.0 / (right - left);
  1567. result.m[1] = result.m[2] = result.m[3] = 0;
  1568. result.m[5] = 2.0 / (top - bottom);
  1569. result.m[4] = result.m[6] = result.m[7] = 0;
  1570. result.m[10] = -1.0 / (znear - zfar);
  1571. result.m[8] = result.m[9] = result.m[11] = 0;
  1572. result.m[12] = (left + right) / (left - right);
  1573. result.m[13] = (top + bottom) / (bottom - top);
  1574. result.m[14] = znear / (znear - zfar);
  1575. result.m[15] = 1.0;
  1576. };
  1577. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1578. var matrix = Matrix.Zero();
  1579. matrix.m[0] = (2.0 * znear) / width;
  1580. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1581. matrix.m[5] = (2.0 * znear) / height;
  1582. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1583. matrix.m[10] = -zfar / (znear - zfar);
  1584. matrix.m[8] = matrix.m[9] = 0.0;
  1585. matrix.m[11] = 1.0;
  1586. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1587. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1588. return matrix;
  1589. };
  1590. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1591. var matrix = Matrix.Zero();
  1592. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1593. return matrix;
  1594. };
  1595. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1596. var tan = 1.0 / (Math.tan(fov * 0.5));
  1597. result.m[0] = tan / aspect;
  1598. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1599. result.m[5] = tan;
  1600. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1601. result.m[8] = result.m[9] = 0.0;
  1602. result.m[10] = -zfar / (znear - zfar);
  1603. result.m[11] = 1.0;
  1604. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1605. result.m[14] = (znear * zfar) / (znear - zfar);
  1606. };
  1607. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1608. var cw = viewport.width;
  1609. var ch = viewport.height;
  1610. var cx = viewport.x;
  1611. var cy = viewport.y;
  1612. 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);
  1613. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1614. };
  1615. Matrix.Transpose = function (matrix) {
  1616. var result = new Matrix();
  1617. result.m[0] = matrix.m[0];
  1618. result.m[1] = matrix.m[4];
  1619. result.m[2] = matrix.m[8];
  1620. result.m[3] = matrix.m[12];
  1621. result.m[4] = matrix.m[1];
  1622. result.m[5] = matrix.m[5];
  1623. result.m[6] = matrix.m[9];
  1624. result.m[7] = matrix.m[13];
  1625. result.m[8] = matrix.m[2];
  1626. result.m[9] = matrix.m[6];
  1627. result.m[10] = matrix.m[10];
  1628. result.m[11] = matrix.m[14];
  1629. result.m[12] = matrix.m[3];
  1630. result.m[13] = matrix.m[7];
  1631. result.m[14] = matrix.m[11];
  1632. result.m[15] = matrix.m[15];
  1633. return result;
  1634. };
  1635. Matrix.Reflection = function (plane) {
  1636. var matrix = new Matrix();
  1637. Matrix.ReflectionToRef(plane, matrix);
  1638. return matrix;
  1639. };
  1640. Matrix.ReflectionToRef = function (plane, result) {
  1641. plane.normalize();
  1642. var x = plane.normal.x;
  1643. var y = plane.normal.y;
  1644. var z = plane.normal.z;
  1645. var temp = -2 * x;
  1646. var temp2 = -2 * y;
  1647. var temp3 = -2 * z;
  1648. result.m[0] = (temp * x) + 1;
  1649. result.m[1] = temp2 * x;
  1650. result.m[2] = temp3 * x;
  1651. result.m[3] = 0.0;
  1652. result.m[4] = temp * y;
  1653. result.m[5] = (temp2 * y) + 1;
  1654. result.m[6] = temp3 * y;
  1655. result.m[7] = 0.0;
  1656. result.m[8] = temp * z;
  1657. result.m[9] = temp2 * z;
  1658. result.m[10] = (temp3 * z) + 1;
  1659. result.m[11] = 0.0;
  1660. result.m[12] = temp * plane.d;
  1661. result.m[13] = temp2 * plane.d;
  1662. result.m[14] = temp3 * plane.d;
  1663. result.m[15] = 1.0;
  1664. };
  1665. Matrix._tempQuaternion = new Quaternion();
  1666. Matrix._xAxis = Vector3.Zero();
  1667. Matrix._yAxis = Vector3.Zero();
  1668. Matrix._zAxis = Vector3.Zero();
  1669. return Matrix;
  1670. })();
  1671. BABYLON.Matrix = Matrix;
  1672. var Plane = (function () {
  1673. function Plane(a, b, c, d) {
  1674. this.normal = new Vector3(a, b, c);
  1675. this.d = d;
  1676. }
  1677. Plane.prototype.asArray = function () {
  1678. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1679. };
  1680. Plane.prototype.clone = function () {
  1681. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1682. };
  1683. Plane.prototype.normalize = function () {
  1684. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1685. var magnitude = 0;
  1686. if (norm != 0) {
  1687. magnitude = 1.0 / norm;
  1688. }
  1689. this.normal.x *= magnitude;
  1690. this.normal.y *= magnitude;
  1691. this.normal.z *= magnitude;
  1692. this.d *= magnitude;
  1693. };
  1694. Plane.prototype.transform = function (transformation) {
  1695. var transposedMatrix = BABYLON.Matrix.Transpose(transformation);
  1696. var x = this.normal.x;
  1697. var y = this.normal.y;
  1698. var z = this.normal.z;
  1699. var d = this.d;
  1700. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1701. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1702. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1703. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1704. return new BABYLON.Plane(normalX, normalY, normalZ, finalD);
  1705. };
  1706. Plane.prototype.dotCoordinate = function (point) {
  1707. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1708. };
  1709. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1710. var x1 = point2.x - point1.x;
  1711. var y1 = point2.y - point1.y;
  1712. var z1 = point2.z - point1.z;
  1713. var x2 = point3.x - point1.x;
  1714. var y2 = point3.y - point1.y;
  1715. var z2 = point3.z - point1.z;
  1716. var yz = (y1 * z2) - (z1 * y2);
  1717. var xz = (z1 * x2) - (x1 * z2);
  1718. var xy = (x1 * y2) - (y1 * x2);
  1719. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1720. var invPyth;
  1721. if (pyth != 0) {
  1722. invPyth = 1.0 / pyth;
  1723. } else {
  1724. invPyth = 0;
  1725. }
  1726. this.normal.x = yz * invPyth;
  1727. this.normal.y = xz * invPyth;
  1728. this.normal.z = xy * invPyth;
  1729. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1730. };
  1731. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1732. var dot = Vector3.Dot(this.normal, direction);
  1733. return (dot <= epsilon);
  1734. };
  1735. Plane.prototype.signedDistanceTo = function (point) {
  1736. return Vector3.Dot(point, this.normal) + this.d;
  1737. };
  1738. Plane.FromArray = function (array) {
  1739. return new BABYLON.Plane(array[0], array[1], array[2], array[3]);
  1740. };
  1741. Plane.FromPoints = function (point1, point2, point3) {
  1742. var result = new BABYLON.Plane(0, 0, 0, 0);
  1743. result.copyFromPoints(point1, point2, point3);
  1744. return result;
  1745. };
  1746. Plane.FromPositionAndNormal = function (origin, normal) {
  1747. var result = new BABYLON.Plane(0, 0, 0, 0);
  1748. normal.normalize();
  1749. result.normal = normal;
  1750. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1751. return result;
  1752. };
  1753. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1754. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1755. return Vector3.Dot(point, normal) + d;
  1756. };
  1757. return Plane;
  1758. })();
  1759. BABYLON.Plane = Plane;
  1760. var Viewport = (function () {
  1761. function Viewport(x, y, width, height) {
  1762. this.x = x;
  1763. this.y = y;
  1764. this.width = width;
  1765. this.height = height;
  1766. }
  1767. Viewport.prototype.toGlobal = function (engine) {
  1768. var width = engine.getRenderWidth();
  1769. var height = engine.getRenderHeight();
  1770. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1771. };
  1772. return Viewport;
  1773. })();
  1774. BABYLON.Viewport = Viewport;
  1775. var Frustum = (function () {
  1776. function Frustum() {
  1777. }
  1778. Frustum.GetPlanes = function (transform) {
  1779. var frustumPlanes = [];
  1780. for (var index = 0; index < 6; index++) {
  1781. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1782. }
  1783. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1784. return frustumPlanes;
  1785. };
  1786. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1787. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1788. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1789. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1790. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1791. frustumPlanes[0].normalize();
  1792. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1793. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1794. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1795. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1796. frustumPlanes[1].normalize();
  1797. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1798. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1799. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1800. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1801. frustumPlanes[2].normalize();
  1802. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1803. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1804. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1805. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1806. frustumPlanes[3].normalize();
  1807. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1808. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1809. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1810. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1811. frustumPlanes[4].normalize();
  1812. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1813. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1814. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1815. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1816. frustumPlanes[5].normalize();
  1817. };
  1818. return Frustum;
  1819. })();
  1820. BABYLON.Frustum = Frustum;
  1821. var Ray = (function () {
  1822. function Ray(origin, direction, length) {
  1823. if (typeof length === "undefined") { length = Number.MAX_VALUE; }
  1824. this.origin = origin;
  1825. this.direction = direction;
  1826. this.length = length;
  1827. }
  1828. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1829. var d = 0.0;
  1830. var maxValue = Number.MAX_VALUE;
  1831. if (Math.abs(this.direction.x) < 0.0000001) {
  1832. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1833. return false;
  1834. }
  1835. } else {
  1836. var inv = 1.0 / this.direction.x;
  1837. var min = (minimum.x - this.origin.x) * inv;
  1838. var max = (maximum.x - this.origin.x) * inv;
  1839. if (max == -Infinity) {
  1840. max = Infinity;
  1841. }
  1842. if (min > max) {
  1843. var temp = min;
  1844. min = max;
  1845. max = temp;
  1846. }
  1847. d = Math.max(min, d);
  1848. maxValue = Math.min(max, maxValue);
  1849. if (d > maxValue) {
  1850. return false;
  1851. }
  1852. }
  1853. if (Math.abs(this.direction.y) < 0.0000001) {
  1854. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1855. return false;
  1856. }
  1857. } else {
  1858. inv = 1.0 / this.direction.y;
  1859. min = (minimum.y - this.origin.y) * inv;
  1860. max = (maximum.y - this.origin.y) * inv;
  1861. if (max == -Infinity) {
  1862. max = Infinity;
  1863. }
  1864. if (min > max) {
  1865. temp = min;
  1866. min = max;
  1867. max = temp;
  1868. }
  1869. d = Math.max(min, d);
  1870. maxValue = Math.min(max, maxValue);
  1871. if (d > maxValue) {
  1872. return false;
  1873. }
  1874. }
  1875. if (Math.abs(this.direction.z) < 0.0000001) {
  1876. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1877. return false;
  1878. }
  1879. } else {
  1880. inv = 1.0 / this.direction.z;
  1881. min = (minimum.z - this.origin.z) * inv;
  1882. max = (maximum.z - this.origin.z) * inv;
  1883. if (max == -Infinity) {
  1884. max = Infinity;
  1885. }
  1886. if (min > max) {
  1887. temp = min;
  1888. min = max;
  1889. max = temp;
  1890. }
  1891. d = Math.max(min, d);
  1892. maxValue = Math.min(max, maxValue);
  1893. if (d > maxValue) {
  1894. return false;
  1895. }
  1896. }
  1897. return true;
  1898. };
  1899. Ray.prototype.intersectsBox = function (box) {
  1900. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1901. };
  1902. Ray.prototype.intersectsSphere = function (sphere) {
  1903. var x = sphere.center.x - this.origin.x;
  1904. var y = sphere.center.y - this.origin.y;
  1905. var z = sphere.center.z - this.origin.z;
  1906. var pyth = (x * x) + (y * y) + (z * z);
  1907. var rr = sphere.radius * sphere.radius;
  1908. if (pyth <= rr) {
  1909. return true;
  1910. }
  1911. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1912. if (dot < 0.0) {
  1913. return false;
  1914. }
  1915. var temp = pyth - (dot * dot);
  1916. return temp <= rr;
  1917. };
  1918. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1919. if (!this._edge1) {
  1920. this._edge1 = BABYLON.Vector3.Zero();
  1921. this._edge2 = BABYLON.Vector3.Zero();
  1922. this._pvec = BABYLON.Vector3.Zero();
  1923. this._tvec = BABYLON.Vector3.Zero();
  1924. this._qvec = BABYLON.Vector3.Zero();
  1925. }
  1926. vertex1.subtractToRef(vertex0, this._edge1);
  1927. vertex2.subtractToRef(vertex0, this._edge2);
  1928. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1929. var det = Vector3.Dot(this._edge1, this._pvec);
  1930. if (det === 0) {
  1931. return null;
  1932. }
  1933. var invdet = 1 / det;
  1934. this.origin.subtractToRef(vertex0, this._tvec);
  1935. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1936. if (bu < 0 || bu > 1.0) {
  1937. return null;
  1938. }
  1939. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1940. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1941. if (bv < 0 || bu + bv > 1.0) {
  1942. return null;
  1943. }
  1944. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  1945. if (distance > this.length) {
  1946. return null;
  1947. }
  1948. return new BABYLON.IntersectionInfo(bu, bv, distance);
  1949. };
  1950. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1951. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1952. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1953. var direction = end.subtract(start);
  1954. direction.normalize();
  1955. return new Ray(start, direction);
  1956. };
  1957. /**
  1958. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  1959. * transformed to the given world matrix.
  1960. * @param origin The origin point
  1961. * @param end The end point
  1962. * @param world a matrix to transform the ray to. Default is the identity matrix.
  1963. */
  1964. Ray.CreateNewFromTo = function (origin, end, world) {
  1965. if (typeof world === "undefined") { world = BABYLON.Matrix.Identity(); }
  1966. var direction = end.subtract(origin);
  1967. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  1968. direction.normalize();
  1969. return Ray.Transform(new Ray(origin, direction, length), world);
  1970. };
  1971. Ray.Transform = function (ray, matrix) {
  1972. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  1973. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  1974. return new Ray(newOrigin, newDirection, ray.length);
  1975. };
  1976. return Ray;
  1977. })();
  1978. BABYLON.Ray = Ray;
  1979. (function (Space) {
  1980. Space[Space["LOCAL"] = 0] = "LOCAL";
  1981. Space[Space["WORLD"] = 1] = "WORLD";
  1982. })(BABYLON.Space || (BABYLON.Space = {}));
  1983. var Space = BABYLON.Space;
  1984. var Axis = (function () {
  1985. function Axis() {
  1986. }
  1987. Axis.X = new BABYLON.Vector3(1, 0, 0);
  1988. Axis.Y = new BABYLON.Vector3(0, 1, 0);
  1989. Axis.Z = new BABYLON.Vector3(0, 0, 1);
  1990. return Axis;
  1991. })();
  1992. BABYLON.Axis = Axis;
  1993. ;
  1994. var BezierCurve = (function () {
  1995. function BezierCurve() {
  1996. }
  1997. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  1998. var f0 = 1 - 3 * x2 + 3 * x1;
  1999. var f1 = 3 * x2 - 6 * x1;
  2000. var f2 = 3 * x1;
  2001. var refinedT = t;
  2002. for (var i = 0; i < 5; i++) {
  2003. var refinedT2 = refinedT * refinedT;
  2004. var refinedT3 = refinedT2 * refinedT;
  2005. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2006. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2007. refinedT -= (x - t) * slope;
  2008. refinedT = Math.min(1, Math.max(0, refinedT));
  2009. }
  2010. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2011. };
  2012. return BezierCurve;
  2013. })();
  2014. BABYLON.BezierCurve = BezierCurve;
  2015. })(BABYLON || (BABYLON = {}));
  2016. var BABYLON;
  2017. (function (BABYLON) {
  2018. var screenshotCanvas;
  2019. var fpsRange = 60;
  2020. var previousFramesDuration = [];
  2021. var fps = 60;
  2022. var deltaTime = 0;
  2023. var cloneValue = function (source, destinationObject) {
  2024. if (!source)
  2025. return null;
  2026. if (source instanceof BABYLON.Mesh) {
  2027. return null;
  2028. }
  2029. if (source instanceof BABYLON.SubMesh) {
  2030. return source.clone(destinationObject);
  2031. } else if (source.clone) {
  2032. return source.clone();
  2033. }
  2034. return null;
  2035. };
  2036. var Tools = (function () {
  2037. function Tools() {
  2038. }
  2039. Tools.GetFilename = function (path) {
  2040. var index = path.lastIndexOf("/");
  2041. if (index < 0)
  2042. return path;
  2043. return path.substring(index + 1);
  2044. };
  2045. Tools.GetDOMTextContent = function (element) {
  2046. var result = "";
  2047. var child = element.firstChild;
  2048. while (child) {
  2049. if (child.nodeType == 3) {
  2050. result += child.textContent;
  2051. }
  2052. child = child.nextSibling;
  2053. }
  2054. return result;
  2055. };
  2056. Tools.ToDegrees = function (angle) {
  2057. return angle * 180 / Math.PI;
  2058. };
  2059. Tools.ToRadians = function (angle) {
  2060. return angle * Math.PI / 180;
  2061. };
  2062. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2063. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2064. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2065. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2066. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2067. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2068. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2069. }
  2070. return {
  2071. minimum: minimum,
  2072. maximum: maximum
  2073. };
  2074. };
  2075. Tools.ExtractMinAndMax = function (positions, start, count) {
  2076. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2077. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2078. for (var index = start; index < start + count; index++) {
  2079. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2080. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2081. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2082. }
  2083. return {
  2084. minimum: minimum,
  2085. maximum: maximum
  2086. };
  2087. };
  2088. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2089. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2090. return undefined;
  2091. return Array.isArray(obj) ? obj : [obj];
  2092. };
  2093. Tools.GetPointerPrefix = function () {
  2094. var eventPrefix = "pointer";
  2095. if (!navigator.pointerEnabled) {
  2096. eventPrefix = "mouse";
  2097. }
  2098. return eventPrefix;
  2099. };
  2100. Tools.QueueNewFrame = function (func) {
  2101. if (window.requestAnimationFrame)
  2102. window.requestAnimationFrame(func);
  2103. else if (window.msRequestAnimationFrame)
  2104. window.msRequestAnimationFrame(func);
  2105. else if (window.webkitRequestAnimationFrame)
  2106. window.webkitRequestAnimationFrame(func);
  2107. else if (window.mozRequestAnimationFrame)
  2108. window.mozRequestAnimationFrame(func);
  2109. else if (window.oRequestAnimationFrame)
  2110. window.oRequestAnimationFrame(func);
  2111. else {
  2112. window.setTimeout(func, 16);
  2113. }
  2114. };
  2115. Tools.RequestFullscreen = function (element) {
  2116. if (element.requestFullscreen)
  2117. element.requestFullscreen();
  2118. else if (element.msRequestFullscreen)
  2119. element.msRequestFullscreen();
  2120. else if (element.webkitRequestFullscreen)
  2121. element.webkitRequestFullscreen();
  2122. else if (element.mozRequestFullScreen)
  2123. element.mozRequestFullScreen();
  2124. };
  2125. Tools.ExitFullscreen = function () {
  2126. if (document.exitFullscreen) {
  2127. document.exitFullscreen();
  2128. } else if (document.mozCancelFullScreen) {
  2129. document.mozCancelFullScreen();
  2130. } else if (document.webkitCancelFullScreen) {
  2131. document.webkitCancelFullScreen();
  2132. } else if (document.msCancelFullScreen) {
  2133. document.msCancelFullScreen();
  2134. }
  2135. };
  2136. Tools.CleanUrl = function (url) {
  2137. url = url.replace(/#/mg, "%23");
  2138. return url;
  2139. };
  2140. Tools.LoadImage = function (url, onload, onerror, database) {
  2141. url = Tools.CleanUrl(url);
  2142. var img = new Image();
  2143. if (url.substr(0, 5) != "data:")
  2144. img.crossOrigin = 'anonymous';
  2145. img.onload = function () {
  2146. onload(img);
  2147. };
  2148. img.onerror = function (err) {
  2149. onerror(img, err);
  2150. };
  2151. var noIndexedDB = function () {
  2152. img.src = url;
  2153. };
  2154. var loadFromIndexedDB = function () {
  2155. database.loadImageFromDB(url, img);
  2156. };
  2157. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2158. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2159. } else {
  2160. if (url.indexOf("file:") === -1) {
  2161. noIndexedDB();
  2162. } else {
  2163. try {
  2164. var textureName = url.substring(5);
  2165. var blobURL;
  2166. try {
  2167. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2168. } catch (ex) {
  2169. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2170. }
  2171. img.src = blobURL;
  2172. } catch (e) {
  2173. Tools.Log("Error while trying to load texture: " + textureName);
  2174. img.src = null;
  2175. }
  2176. }
  2177. }
  2178. return img;
  2179. };
  2180. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2181. url = Tools.CleanUrl(url);
  2182. var noIndexedDB = function () {
  2183. var request = new XMLHttpRequest();
  2184. var loadUrl = Tools.BaseUrl + url;
  2185. request.open('GET', loadUrl, true);
  2186. if (useArrayBuffer) {
  2187. request.responseType = "arraybuffer";
  2188. }
  2189. request.onprogress = progressCallBack;
  2190. request.onreadystatechange = function () {
  2191. if (request.readyState == 4) {
  2192. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2193. callback(!useArrayBuffer ? request.responseText : request.response);
  2194. } else {
  2195. if (onError) {
  2196. onError();
  2197. } else {
  2198. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2199. }
  2200. }
  2201. }
  2202. };
  2203. request.send(null);
  2204. };
  2205. var loadFromIndexedDB = function () {
  2206. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2207. };
  2208. if (url.indexOf("file:") !== -1) {
  2209. var fileName = url.substring(5);
  2210. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2211. } else {
  2212. if (database && database.enableSceneOffline) {
  2213. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2214. } else {
  2215. noIndexedDB();
  2216. }
  2217. }
  2218. };
  2219. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2220. var reader = new FileReader();
  2221. reader.onload = function (e) {
  2222. callback(e.target.result);
  2223. };
  2224. reader.onprogress = progressCallback;
  2225. reader.readAsDataURL(fileToLoad);
  2226. };
  2227. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2228. var reader = new FileReader();
  2229. reader.onload = function (e) {
  2230. callback(e.target.result);
  2231. };
  2232. reader.onprogress = progressCallBack;
  2233. if (!useArrayBuffer) {
  2234. reader.readAsText(fileToLoad);
  2235. } else {
  2236. reader.readAsArrayBuffer(fileToLoad);
  2237. }
  2238. };
  2239. Tools.Clamp = function (value, min, max) {
  2240. if (typeof min === "undefined") { min = 0; }
  2241. if (typeof max === "undefined") { max = 1; }
  2242. return Math.min(max, Math.max(min, value));
  2243. };
  2244. Tools.Format = function (value, decimals) {
  2245. if (typeof decimals === "undefined") { decimals = 2; }
  2246. return value.toFixed(decimals);
  2247. };
  2248. Tools.CheckExtends = function (v, min, max) {
  2249. if (v.x < min.x)
  2250. min.x = v.x;
  2251. if (v.y < min.y)
  2252. min.y = v.y;
  2253. if (v.z < min.z)
  2254. min.z = v.z;
  2255. if (v.x > max.x)
  2256. max.x = v.x;
  2257. if (v.y > max.y)
  2258. max.y = v.y;
  2259. if (v.z > max.z)
  2260. max.z = v.z;
  2261. };
  2262. Tools.WithinEpsilon = function (a, b) {
  2263. var num = a - b;
  2264. return -1.401298E-45 <= num && num <= 1.401298E-45;
  2265. };
  2266. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2267. for (var prop in source) {
  2268. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2269. continue;
  2270. }
  2271. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2272. continue;
  2273. }
  2274. var sourceValue = source[prop];
  2275. var typeOfSourceValue = typeof sourceValue;
  2276. if (typeOfSourceValue == "function") {
  2277. continue;
  2278. }
  2279. if (typeOfSourceValue == "object") {
  2280. if (sourceValue instanceof Array) {
  2281. destination[prop] = [];
  2282. if (sourceValue.length > 0) {
  2283. if (typeof sourceValue[0] == "object") {
  2284. for (var index = 0; index < sourceValue.length; index++) {
  2285. var clonedValue = cloneValue(sourceValue[index], destination);
  2286. if (destination[prop].indexOf(clonedValue) === -1) {
  2287. destination[prop].push(clonedValue);
  2288. }
  2289. }
  2290. } else {
  2291. destination[prop] = sourceValue.slice(0);
  2292. }
  2293. }
  2294. } else {
  2295. destination[prop] = cloneValue(sourceValue, destination);
  2296. }
  2297. } else {
  2298. destination[prop] = sourceValue;
  2299. }
  2300. }
  2301. };
  2302. Tools.IsEmpty = function (obj) {
  2303. for (var i in obj) {
  2304. return false;
  2305. }
  2306. return true;
  2307. };
  2308. Tools.RegisterTopRootEvents = function (events) {
  2309. for (var index = 0; index < events.length; index++) {
  2310. var event = events[index];
  2311. window.addEventListener(event.name, event.handler, false);
  2312. try {
  2313. if (window.parent) {
  2314. window.parent.addEventListener(event.name, event.handler, false);
  2315. }
  2316. } catch (e) {
  2317. }
  2318. }
  2319. };
  2320. Tools.UnregisterTopRootEvents = function (events) {
  2321. for (var index = 0; index < events.length; index++) {
  2322. var event = events[index];
  2323. window.removeEventListener(event.name, event.handler);
  2324. try {
  2325. if (window.parent) {
  2326. window.parent.removeEventListener(event.name, event.handler);
  2327. }
  2328. } catch (e) {
  2329. }
  2330. }
  2331. };
  2332. Tools.GetFps = function () {
  2333. return fps;
  2334. };
  2335. Tools.GetDeltaTime = function () {
  2336. return deltaTime;
  2337. };
  2338. Tools._MeasureFps = function () {
  2339. previousFramesDuration.push(Tools.Now);
  2340. var length = previousFramesDuration.length;
  2341. if (length >= 2) {
  2342. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  2343. }
  2344. if (length >= fpsRange) {
  2345. if (length > fpsRange) {
  2346. previousFramesDuration.splice(0, 1);
  2347. length = previousFramesDuration.length;
  2348. }
  2349. var sum = 0;
  2350. for (var id = 0; id < length - 1; id++) {
  2351. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  2352. }
  2353. fps = 1000.0 / (sum / (length - 1));
  2354. }
  2355. };
  2356. Tools.CreateScreenshot = function (engine, camera, size) {
  2357. var width;
  2358. var height;
  2359. var scene = camera.getScene();
  2360. var previousCamera = null;
  2361. if (scene.activeCamera !== camera) {
  2362. previousCamera = scene.activeCamera;
  2363. scene.activeCamera = camera;
  2364. }
  2365. if (size.precision) {
  2366. width = Math.round(engine.getRenderWidth() * size.precision);
  2367. height = Math.round(width / engine.getAspectRatio(camera));
  2368. size = { width: width, height: height };
  2369. } else if (size.width && size.height) {
  2370. width = size.width;
  2371. height = size.height;
  2372. } else if (size.width && !size.height) {
  2373. width = size.width;
  2374. height = Math.round(width / engine.getAspectRatio(camera));
  2375. size = { width: width, height: height };
  2376. } else if (size.height && !size.width) {
  2377. height = size.height;
  2378. width = Math.round(height * engine.getAspectRatio(camera));
  2379. size = { width: width, height: height };
  2380. } else if (!isNaN(size)) {
  2381. height = size;
  2382. width = size;
  2383. } else {
  2384. Tools.Error("Invalid 'size' parameter !");
  2385. return;
  2386. }
  2387. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2388. texture.renderList = engine.scenes[0].meshes;
  2389. texture.onAfterRender = function () {
  2390. var numberOfChannelsByLine = width * 4;
  2391. var halfHeight = height / 2;
  2392. var data = engine.readPixels(0, 0, width, height);
  2393. for (var i = 0; i < halfHeight; i++) {
  2394. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2395. var currentCell = j + i * numberOfChannelsByLine;
  2396. var targetLine = height - i - 1;
  2397. var targetCell = j + targetLine * numberOfChannelsByLine;
  2398. var temp = data[currentCell];
  2399. data[currentCell] = data[targetCell];
  2400. data[targetCell] = temp;
  2401. }
  2402. }
  2403. if (!screenshotCanvas) {
  2404. screenshotCanvas = document.createElement('canvas');
  2405. }
  2406. screenshotCanvas.width = width;
  2407. screenshotCanvas.height = height;
  2408. var context = screenshotCanvas.getContext('2d');
  2409. var imageData = context.createImageData(width, height);
  2410. imageData.data.set(data);
  2411. context.putImageData(imageData, 0, 0);
  2412. var base64Image = screenshotCanvas.toDataURL();
  2413. if (("download" in document.createElement("a"))) {
  2414. var a = window.document.createElement("a");
  2415. a.href = base64Image;
  2416. var date = new Date();
  2417. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2418. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2419. window.document.body.appendChild(a);
  2420. a.addEventListener("click", function () {
  2421. a.parentElement.removeChild(a);
  2422. });
  2423. a.click();
  2424. } else {
  2425. var newWindow = window.open("");
  2426. var img = newWindow.document.createElement("img");
  2427. img.src = base64Image;
  2428. newWindow.document.body.appendChild(img);
  2429. }
  2430. };
  2431. texture.render(true);
  2432. texture.dispose();
  2433. if (previousCamera) {
  2434. scene.activeCamera = previousCamera;
  2435. }
  2436. };
  2437. Tools.ValidateXHRData = function (xhr, dataType) {
  2438. if (typeof dataType === "undefined") { dataType = 7; }
  2439. try {
  2440. if (dataType & 1) {
  2441. if (xhr.responseText && xhr.responseText.length > 0) {
  2442. return true;
  2443. } else if (dataType === 1) {
  2444. return false;
  2445. }
  2446. }
  2447. if (dataType & 2) {
  2448. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2449. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2450. return true;
  2451. } else if (dataType === 2) {
  2452. return false;
  2453. }
  2454. }
  2455. if (dataType & 4) {
  2456. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2457. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2458. return true;
  2459. } else {
  2460. return false;
  2461. }
  2462. }
  2463. } catch (e) {
  2464. }
  2465. return false;
  2466. };
  2467. Object.defineProperty(Tools, "NoneLogLevel", {
  2468. get: function () {
  2469. return Tools._NoneLogLevel;
  2470. },
  2471. enumerable: true,
  2472. configurable: true
  2473. });
  2474. Object.defineProperty(Tools, "MessageLogLevel", {
  2475. get: function () {
  2476. return Tools._MessageLogLevel;
  2477. },
  2478. enumerable: true,
  2479. configurable: true
  2480. });
  2481. Object.defineProperty(Tools, "WarningLogLevel", {
  2482. get: function () {
  2483. return Tools._WarningLogLevel;
  2484. },
  2485. enumerable: true,
  2486. configurable: true
  2487. });
  2488. Object.defineProperty(Tools, "ErrorLogLevel", {
  2489. get: function () {
  2490. return Tools._ErrorLogLevel;
  2491. },
  2492. enumerable: true,
  2493. configurable: true
  2494. });
  2495. Object.defineProperty(Tools, "AllLogLevel", {
  2496. get: function () {
  2497. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2498. },
  2499. enumerable: true,
  2500. configurable: true
  2501. });
  2502. Tools._AddLogEntry = function (entry) {
  2503. Tools._LogCache = entry + Tools._LogCache;
  2504. if (Tools.OnNewCacheEntry) {
  2505. Tools.OnNewCacheEntry(entry);
  2506. }
  2507. };
  2508. Tools._FormatMessage = function (message) {
  2509. var padStr = function (i) {
  2510. return (i < 10) ? "0" + i : "" + i;
  2511. };
  2512. var date = new Date();
  2513. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2514. };
  2515. Tools._LogDisabled = function (message) {
  2516. };
  2517. Tools._LogEnabled = function (message) {
  2518. var formattedMessage = Tools._FormatMessage(message);
  2519. console.log("BJS - " + formattedMessage);
  2520. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2521. Tools._AddLogEntry(entry);
  2522. };
  2523. Tools._WarnDisabled = function (message) {
  2524. };
  2525. Tools._WarnEnabled = function (message) {
  2526. var formattedMessage = Tools._FormatMessage(message);
  2527. console.warn("BJS - " + formattedMessage);
  2528. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2529. Tools._AddLogEntry(entry);
  2530. };
  2531. Tools._ErrorDisabled = function (message) {
  2532. };
  2533. Tools._ErrorEnabled = function (message) {
  2534. var formattedMessage = Tools._FormatMessage(message);
  2535. console.error("BJS - " + formattedMessage);
  2536. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2537. Tools._AddLogEntry(entry);
  2538. };
  2539. Object.defineProperty(Tools, "LogCache", {
  2540. get: function () {
  2541. return Tools._LogCache;
  2542. },
  2543. enumerable: true,
  2544. configurable: true
  2545. });
  2546. Object.defineProperty(Tools, "LogLevels", {
  2547. set: function (level) {
  2548. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2549. Tools.Log = Tools._LogEnabled;
  2550. } else {
  2551. Tools.Log = Tools._LogDisabled;
  2552. }
  2553. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2554. Tools.Warn = Tools._WarnEnabled;
  2555. } else {
  2556. Tools.Warn = Tools._WarnDisabled;
  2557. }
  2558. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2559. Tools.Error = Tools._ErrorEnabled;
  2560. } else {
  2561. Tools.Error = Tools._ErrorDisabled;
  2562. }
  2563. },
  2564. enumerable: true,
  2565. configurable: true
  2566. });
  2567. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2568. get: function () {
  2569. return Tools._PerformanceNoneLogLevel;
  2570. },
  2571. enumerable: true,
  2572. configurable: true
  2573. });
  2574. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2575. get: function () {
  2576. return Tools._PerformanceUserMarkLogLevel;
  2577. },
  2578. enumerable: true,
  2579. configurable: true
  2580. });
  2581. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2582. get: function () {
  2583. return Tools._PerformanceConsoleLogLevel;
  2584. },
  2585. enumerable: true,
  2586. configurable: true
  2587. });
  2588. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2589. set: function (level) {
  2590. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2591. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2592. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2593. return;
  2594. }
  2595. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2596. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2597. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2598. return;
  2599. }
  2600. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2601. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2602. },
  2603. enumerable: true,
  2604. configurable: true
  2605. });
  2606. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2607. };
  2608. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2609. };
  2610. Tools._StartUserMark = function (counterName, condition) {
  2611. if (typeof condition === "undefined") { condition = true; }
  2612. if (!condition || !Tools._performance.mark) {
  2613. return;
  2614. }
  2615. Tools._performance.mark(counterName + "-Begin");
  2616. };
  2617. Tools._EndUserMark = function (counterName, condition) {
  2618. if (typeof condition === "undefined") { condition = true; }
  2619. if (!condition || !Tools._performance.mark) {
  2620. return;
  2621. }
  2622. Tools._performance.mark(counterName + "-End");
  2623. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2624. };
  2625. Tools._StartPerformanceConsole = function (counterName, condition) {
  2626. if (typeof condition === "undefined") { condition = true; }
  2627. if (!condition) {
  2628. return;
  2629. }
  2630. Tools._StartUserMark(counterName, condition);
  2631. if (console.time) {
  2632. console.time(counterName);
  2633. }
  2634. };
  2635. Tools._EndPerformanceConsole = function (counterName, condition) {
  2636. if (typeof condition === "undefined") { condition = true; }
  2637. if (!condition) {
  2638. return;
  2639. }
  2640. Tools._EndUserMark(counterName, condition);
  2641. if (console.time) {
  2642. console.timeEnd(counterName);
  2643. }
  2644. };
  2645. Object.defineProperty(Tools, "Now", {
  2646. get: function () {
  2647. if (window.performance && window.performance.now) {
  2648. return window.performance.now();
  2649. }
  2650. return new Date().getTime();
  2651. },
  2652. enumerable: true,
  2653. configurable: true
  2654. });
  2655. Tools.BaseUrl = "";
  2656. Tools.GetExponantOfTwo = function (value, max) {
  2657. var count = 1;
  2658. do {
  2659. count *= 2;
  2660. } while(count < value);
  2661. if (count > max)
  2662. count = max;
  2663. return count;
  2664. };
  2665. Tools._NoneLogLevel = 0;
  2666. Tools._MessageLogLevel = 1;
  2667. Tools._WarningLogLevel = 2;
  2668. Tools._ErrorLogLevel = 4;
  2669. Tools._LogCache = "";
  2670. Tools.Log = Tools._LogEnabled;
  2671. Tools.Warn = Tools._WarnEnabled;
  2672. Tools.Error = Tools._ErrorEnabled;
  2673. Tools._PerformanceNoneLogLevel = 0;
  2674. Tools._PerformanceUserMarkLogLevel = 1;
  2675. Tools._PerformanceConsoleLogLevel = 2;
  2676. Tools._performance = window.performance;
  2677. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2678. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2679. return Tools;
  2680. })();
  2681. BABYLON.Tools = Tools;
  2682. })(BABYLON || (BABYLON = {}));
  2683. var BABYLON;
  2684. (function (BABYLON) {
  2685. var _DepthCullingState = (function () {
  2686. function _DepthCullingState() {
  2687. this._isDepthTestDirty = false;
  2688. this._isDepthMaskDirty = false;
  2689. this._isDepthFuncDirty = false;
  2690. this._isCullFaceDirty = false;
  2691. this._isCullDirty = false;
  2692. }
  2693. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2694. get: function () {
  2695. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2696. },
  2697. enumerable: true,
  2698. configurable: true
  2699. });
  2700. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2701. get: function () {
  2702. return this._cullFace;
  2703. },
  2704. set: function (value) {
  2705. if (this._cullFace === value) {
  2706. return;
  2707. }
  2708. this._cullFace = value;
  2709. this._isCullFaceDirty = true;
  2710. },
  2711. enumerable: true,
  2712. configurable: true
  2713. });
  2714. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2715. get: function () {
  2716. return this._cull;
  2717. },
  2718. set: function (value) {
  2719. if (this._cull === value) {
  2720. return;
  2721. }
  2722. this._cull = value;
  2723. this._isCullDirty = true;
  2724. },
  2725. enumerable: true,
  2726. configurable: true
  2727. });
  2728. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2729. get: function () {
  2730. return this._depthFunc;
  2731. },
  2732. set: function (value) {
  2733. if (this._depthFunc === value) {
  2734. return;
  2735. }
  2736. this._depthFunc = value;
  2737. this._isDepthFuncDirty = true;
  2738. },
  2739. enumerable: true,
  2740. configurable: true
  2741. });
  2742. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2743. get: function () {
  2744. return this._depthMask;
  2745. },
  2746. set: function (value) {
  2747. if (this._depthMask === value) {
  2748. return;
  2749. }
  2750. this._depthMask = value;
  2751. this._isDepthMaskDirty = true;
  2752. },
  2753. enumerable: true,
  2754. configurable: true
  2755. });
  2756. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  2757. get: function () {
  2758. return this._depthTest;
  2759. },
  2760. set: function (value) {
  2761. if (this._depthTest === value) {
  2762. return;
  2763. }
  2764. this._depthTest = value;
  2765. this._isDepthTestDirty = true;
  2766. },
  2767. enumerable: true,
  2768. configurable: true
  2769. });
  2770. _DepthCullingState.prototype.reset = function () {
  2771. this._depthMask = true;
  2772. this._depthTest = true;
  2773. this._depthFunc = null;
  2774. this._cull = null;
  2775. this._cullFace = null;
  2776. this._isDepthTestDirty = true;
  2777. this._isDepthMaskDirty = true;
  2778. this._isDepthFuncDirty = false;
  2779. this._isCullFaceDirty = false;
  2780. this._isCullDirty = false;
  2781. };
  2782. _DepthCullingState.prototype.apply = function (gl) {
  2783. if (!this.isDirty) {
  2784. return;
  2785. }
  2786. if (this._isCullDirty) {
  2787. if (this.cull === true) {
  2788. gl.enable(gl.CULL_FACE);
  2789. } else if (this.cull === false) {
  2790. gl.disable(gl.CULL_FACE);
  2791. }
  2792. this._isCullDirty = false;
  2793. }
  2794. if (this._isCullFaceDirty) {
  2795. gl.cullFace(this.cullFace);
  2796. this._isCullFaceDirty = false;
  2797. }
  2798. if (this._isDepthMaskDirty) {
  2799. gl.depthMask(this.depthMask);
  2800. this._isDepthMaskDirty = false;
  2801. }
  2802. if (this._isDepthTestDirty) {
  2803. if (this.depthTest === true) {
  2804. gl.enable(gl.DEPTH_TEST);
  2805. } else if (this.depthTest === false) {
  2806. gl.disable(gl.DEPTH_TEST);
  2807. }
  2808. this._isDepthTestDirty = false;
  2809. }
  2810. if (this._isDepthFuncDirty) {
  2811. gl.depthFunc(this.depthFunc);
  2812. this._isDepthFuncDirty = false;
  2813. }
  2814. };
  2815. return _DepthCullingState;
  2816. })();
  2817. BABYLON._DepthCullingState = _DepthCullingState;
  2818. var _AlphaState = (function () {
  2819. function _AlphaState() {
  2820. this._isAlphaBlendDirty = false;
  2821. this._isBlendFunctionParametersDirty = false;
  2822. this._alphaBlend = false;
  2823. this._blendFunctionParameters = new Array(4);
  2824. }
  2825. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  2826. get: function () {
  2827. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  2828. },
  2829. enumerable: true,
  2830. configurable: true
  2831. });
  2832. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  2833. get: function () {
  2834. return this._alphaBlend;
  2835. },
  2836. set: function (value) {
  2837. if (this._alphaBlend === value) {
  2838. return;
  2839. }
  2840. this._alphaBlend = value;
  2841. this._isAlphaBlendDirty = true;
  2842. },
  2843. enumerable: true,
  2844. configurable: true
  2845. });
  2846. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  2847. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  2848. return;
  2849. }
  2850. this._blendFunctionParameters[0] = value0;
  2851. this._blendFunctionParameters[1] = value1;
  2852. this._blendFunctionParameters[2] = value2;
  2853. this._blendFunctionParameters[3] = value3;
  2854. this._isBlendFunctionParametersDirty = true;
  2855. };
  2856. _AlphaState.prototype.reset = function () {
  2857. this._alphaBlend = false;
  2858. this._blendFunctionParameters[0] = null;
  2859. this._blendFunctionParameters[1] = null;
  2860. this._blendFunctionParameters[2] = null;
  2861. this._blendFunctionParameters[3] = null;
  2862. this._isAlphaBlendDirty = true;
  2863. this._isBlendFunctionParametersDirty = false;
  2864. };
  2865. _AlphaState.prototype.apply = function (gl) {
  2866. if (!this.isDirty) {
  2867. return;
  2868. }
  2869. if (this._isAlphaBlendDirty) {
  2870. if (this._alphaBlend === true) {
  2871. gl.enable(gl.BLEND);
  2872. } else if (this._alphaBlend === false) {
  2873. gl.disable(gl.BLEND);
  2874. }
  2875. this._isAlphaBlendDirty = false;
  2876. }
  2877. if (this._isBlendFunctionParametersDirty) {
  2878. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  2879. this._isBlendFunctionParametersDirty = false;
  2880. }
  2881. };
  2882. return _AlphaState;
  2883. })();
  2884. BABYLON._AlphaState = _AlphaState;
  2885. var compileShader = function (gl, source, type, defines) {
  2886. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2887. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  2888. gl.compileShader(shader);
  2889. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2890. throw new Error(gl.getShaderInfoLog(shader));
  2891. }
  2892. return shader;
  2893. };
  2894. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  2895. var magFilter = gl.NEAREST;
  2896. var minFilter = gl.NEAREST;
  2897. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  2898. magFilter = gl.LINEAR;
  2899. if (generateMipMaps) {
  2900. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2901. } else {
  2902. minFilter = gl.LINEAR;
  2903. }
  2904. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  2905. magFilter = gl.LINEAR;
  2906. if (generateMipMaps) {
  2907. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2908. } else {
  2909. minFilter = gl.LINEAR;
  2910. }
  2911. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  2912. magFilter = gl.NEAREST;
  2913. if (generateMipMaps) {
  2914. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2915. } else {
  2916. minFilter = gl.NEAREST;
  2917. }
  2918. }
  2919. return {
  2920. min: minFilter,
  2921. mag: magFilter
  2922. };
  2923. };
  2924. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  2925. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  2926. var engine = scene.getEngine();
  2927. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  2928. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  2929. gl.bindTexture(gl.TEXTURE_2D, texture);
  2930. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2931. processFunction(potWidth, potHeight);
  2932. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  2933. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2934. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2935. if (!noMipmap && !isCompressed) {
  2936. gl.generateMipmap(gl.TEXTURE_2D);
  2937. }
  2938. gl.bindTexture(gl.TEXTURE_2D, null);
  2939. engine._activeTexturesCache = [];
  2940. texture._baseWidth = width;
  2941. texture._baseHeight = height;
  2942. texture._width = potWidth;
  2943. texture._height = potHeight;
  2944. texture.isReady = true;
  2945. scene._removePendingData(texture);
  2946. };
  2947. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  2948. var img;
  2949. var onload = function () {
  2950. loadedImages[index] = img;
  2951. loadedImages._internalCount++;
  2952. scene._removePendingData(img);
  2953. if (loadedImages._internalCount == 6) {
  2954. onfinish(loadedImages);
  2955. }
  2956. };
  2957. var onerror = function () {
  2958. scene._removePendingData(img);
  2959. };
  2960. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  2961. scene._addPendingData(img);
  2962. };
  2963. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  2964. var loadedImages = [];
  2965. loadedImages._internalCount = 0;
  2966. for (var index = 0; index < 6; index++) {
  2967. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  2968. }
  2969. };
  2970. var EngineCapabilities = (function () {
  2971. function EngineCapabilities() {
  2972. }
  2973. return EngineCapabilities;
  2974. })();
  2975. BABYLON.EngineCapabilities = EngineCapabilities;
  2976. var Engine = (function () {
  2977. function Engine(canvas, antialias, options) {
  2978. var _this = this;
  2979. this.isFullscreen = false;
  2980. this.isPointerLock = false;
  2981. this.cullBackFaces = true;
  2982. this.renderEvenInBackground = true;
  2983. this.scenes = new Array();
  2984. this._windowIsBackground = false;
  2985. this._runningLoop = false;
  2986. this._loadingDivBackgroundColor = "black";
  2987. this._drawCalls = 0;
  2988. this._depthCullingState = new _DepthCullingState();
  2989. this._alphaState = new _AlphaState();
  2990. this._alphaMode = Engine.ALPHA_DISABLE;
  2991. this._loadedTexturesCache = new Array();
  2992. this._activeTexturesCache = new Array();
  2993. this._compiledEffects = {};
  2994. this._uintIndicesCurrentlySet = false;
  2995. this._renderingCanvas = canvas;
  2996. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2997. options = options || {};
  2998. options.antialias = antialias;
  2999. try {
  3000. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3001. } catch (e) {
  3002. throw new Error("WebGL not supported");
  3003. }
  3004. if (!this._gl) {
  3005. throw new Error("WebGL not supported");
  3006. }
  3007. this._onBlur = function () {
  3008. _this._windowIsBackground = true;
  3009. };
  3010. this._onFocus = function () {
  3011. _this._windowIsBackground = false;
  3012. };
  3013. window.addEventListener("blur", this._onBlur);
  3014. window.addEventListener("focus", this._onFocus);
  3015. this._workingCanvas = document.createElement("canvas");
  3016. this._workingContext = this._workingCanvas.getContext("2d");
  3017. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3018. this.resize();
  3019. this._caps = new EngineCapabilities();
  3020. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3021. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3022. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3023. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3024. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3025. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3026. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3027. 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');
  3028. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3029. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3030. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3031. this.setDepthBuffer(true);
  3032. this.setDepthFunctionToLessOrEqual();
  3033. this.setDepthWrite(true);
  3034. this._onFullscreenChange = function () {
  3035. if (document.fullscreen !== undefined) {
  3036. _this.isFullscreen = document.fullscreen;
  3037. } else if (document.mozFullScreen !== undefined) {
  3038. _this.isFullscreen = document.mozFullScreen;
  3039. } else if (document.webkitIsFullScreen !== undefined) {
  3040. _this.isFullscreen = document.webkitIsFullScreen;
  3041. } else if (document.msIsFullScreen !== undefined) {
  3042. _this.isFullscreen = document.msIsFullScreen;
  3043. }
  3044. if (_this.isFullscreen && _this._pointerLockRequested) {
  3045. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3046. if (canvas.requestPointerLock) {
  3047. canvas.requestPointerLock();
  3048. }
  3049. }
  3050. };
  3051. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3052. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3053. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3054. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3055. this._onPointerLockChange = function () {
  3056. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3057. };
  3058. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3059. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3060. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3061. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3062. this._audioEngine = new BABYLON.AudioEngine();
  3063. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3064. }
  3065. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3066. get: function () {
  3067. return Engine._ALPHA_DISABLE;
  3068. },
  3069. enumerable: true,
  3070. configurable: true
  3071. });
  3072. Object.defineProperty(Engine, "ALPHA_ADD", {
  3073. get: function () {
  3074. return Engine._ALPHA_ADD;
  3075. },
  3076. enumerable: true,
  3077. configurable: true
  3078. });
  3079. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3080. get: function () {
  3081. return Engine._ALPHA_COMBINE;
  3082. },
  3083. enumerable: true,
  3084. configurable: true
  3085. });
  3086. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3087. get: function () {
  3088. return Engine._DELAYLOADSTATE_NONE;
  3089. },
  3090. enumerable: true,
  3091. configurable: true
  3092. });
  3093. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3094. get: function () {
  3095. return Engine._DELAYLOADSTATE_LOADED;
  3096. },
  3097. enumerable: true,
  3098. configurable: true
  3099. });
  3100. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3101. get: function () {
  3102. return Engine._DELAYLOADSTATE_LOADING;
  3103. },
  3104. enumerable: true,
  3105. configurable: true
  3106. });
  3107. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3108. get: function () {
  3109. return Engine._DELAYLOADSTATE_NOTLOADED;
  3110. },
  3111. enumerable: true,
  3112. configurable: true
  3113. });
  3114. Object.defineProperty(Engine, "Version", {
  3115. get: function () {
  3116. return "2.0.0";
  3117. },
  3118. enumerable: true,
  3119. configurable: true
  3120. });
  3121. Engine.prototype.getAudioEngine = function () {
  3122. return this._audioEngine;
  3123. };
  3124. Engine.prototype.getAspectRatio = function (camera) {
  3125. var viewport = camera.viewport;
  3126. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3127. };
  3128. Engine.prototype.getRenderWidth = function () {
  3129. if (this._currentRenderTarget) {
  3130. return this._currentRenderTarget._width;
  3131. }
  3132. return this._renderingCanvas.width;
  3133. };
  3134. Engine.prototype.getRenderHeight = function () {
  3135. if (this._currentRenderTarget) {
  3136. return this._currentRenderTarget._height;
  3137. }
  3138. return this._renderingCanvas.height;
  3139. };
  3140. Engine.prototype.getRenderingCanvas = function () {
  3141. return this._renderingCanvas;
  3142. };
  3143. Engine.prototype.getRenderingCanvasClientRect = function () {
  3144. return this._renderingCanvas.getBoundingClientRect();
  3145. };
  3146. Engine.prototype.setHardwareScalingLevel = function (level) {
  3147. this._hardwareScalingLevel = level;
  3148. this.resize();
  3149. };
  3150. Engine.prototype.getHardwareScalingLevel = function () {
  3151. return this._hardwareScalingLevel;
  3152. };
  3153. Engine.prototype.getLoadedTexturesCache = function () {
  3154. return this._loadedTexturesCache;
  3155. };
  3156. Engine.prototype.getCaps = function () {
  3157. return this._caps;
  3158. };
  3159. Object.defineProperty(Engine.prototype, "drawCalls", {
  3160. get: function () {
  3161. return this._drawCalls;
  3162. },
  3163. enumerable: true,
  3164. configurable: true
  3165. });
  3166. Engine.prototype.resetDrawCalls = function () {
  3167. this._drawCalls = 0;
  3168. };
  3169. Engine.prototype.setDepthFunctionToGreater = function () {
  3170. this._depthCullingState.depthFunc = this._gl.GREATER;
  3171. };
  3172. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3173. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3174. };
  3175. Engine.prototype.setDepthFunctionToLess = function () {
  3176. this._depthCullingState.depthFunc = this._gl.LESS;
  3177. };
  3178. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3179. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3180. };
  3181. Engine.prototype.stopRenderLoop = function () {
  3182. this._renderFunction = null;
  3183. this._runningLoop = false;
  3184. };
  3185. Engine.prototype._renderLoop = function () {
  3186. var _this = this;
  3187. var shouldRender = true;
  3188. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3189. shouldRender = false;
  3190. }
  3191. if (shouldRender) {
  3192. this.beginFrame();
  3193. if (this._renderFunction) {
  3194. this._renderFunction();
  3195. }
  3196. this.endFrame();
  3197. }
  3198. if (this._runningLoop) {
  3199. BABYLON.Tools.QueueNewFrame(function () {
  3200. _this._renderLoop();
  3201. });
  3202. }
  3203. };
  3204. Engine.prototype.runRenderLoop = function (renderFunction) {
  3205. var _this = this;
  3206. this._runningLoop = true;
  3207. this._renderFunction = renderFunction;
  3208. BABYLON.Tools.QueueNewFrame(function () {
  3209. _this._renderLoop();
  3210. });
  3211. };
  3212. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3213. if (this.isFullscreen) {
  3214. BABYLON.Tools.ExitFullscreen();
  3215. } else {
  3216. this._pointerLockRequested = requestPointerLock;
  3217. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3218. }
  3219. };
  3220. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3221. this.applyStates();
  3222. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3223. if (this._depthCullingState.depthMask) {
  3224. this._gl.clearDepth(1.0);
  3225. }
  3226. var mode = 0;
  3227. if (backBuffer)
  3228. mode |= this._gl.COLOR_BUFFER_BIT;
  3229. if (depthStencil && this._depthCullingState.depthMask)
  3230. mode |= this._gl.DEPTH_BUFFER_BIT;
  3231. this._gl.clear(mode);
  3232. };
  3233. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3234. var width = requiredWidth || this._renderingCanvas.width;
  3235. var height = requiredHeight || this._renderingCanvas.height;
  3236. var x = viewport.x || 0;
  3237. var y = viewport.y || 0;
  3238. this._cachedViewport = viewport;
  3239. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3240. };
  3241. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3242. this._cachedViewport = null;
  3243. this._gl.viewport(x, y, width, height);
  3244. };
  3245. Engine.prototype.beginFrame = function () {
  3246. BABYLON.Tools._MeasureFps();
  3247. };
  3248. Engine.prototype.endFrame = function () {
  3249. this.flushFramebuffer();
  3250. };
  3251. Engine.prototype.resize = function () {
  3252. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3253. };
  3254. Engine.prototype.setSize = function (width, height) {
  3255. this._renderingCanvas.width = width;
  3256. this._renderingCanvas.height = height;
  3257. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3258. };
  3259. Engine.prototype.bindFramebuffer = function (texture) {
  3260. this._currentRenderTarget = texture;
  3261. var gl = this._gl;
  3262. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3263. this._gl.viewport(0, 0, texture._width, texture._height);
  3264. this.wipeCaches();
  3265. };
  3266. Engine.prototype.unBindFramebuffer = function (texture) {
  3267. this._currentRenderTarget = null;
  3268. if (texture.generateMipMaps) {
  3269. var gl = this._gl;
  3270. gl.bindTexture(gl.TEXTURE_2D, texture);
  3271. gl.generateMipmap(gl.TEXTURE_2D);
  3272. gl.bindTexture(gl.TEXTURE_2D, null);
  3273. }
  3274. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3275. };
  3276. Engine.prototype.flushFramebuffer = function () {
  3277. };
  3278. Engine.prototype.restoreDefaultFramebuffer = function () {
  3279. this._currentRenderTarget = null;
  3280. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3281. this.setViewport(this._cachedViewport);
  3282. this.wipeCaches();
  3283. };
  3284. Engine.prototype._resetVertexBufferBinding = function () {
  3285. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3286. this._cachedVertexBuffers = null;
  3287. };
  3288. Engine.prototype.createVertexBuffer = function (vertices) {
  3289. var vbo = this._gl.createBuffer();
  3290. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3291. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3292. this._resetVertexBufferBinding();
  3293. vbo.references = 1;
  3294. return vbo;
  3295. };
  3296. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3297. var vbo = this._gl.createBuffer();
  3298. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3299. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3300. this._resetVertexBufferBinding();
  3301. vbo.references = 1;
  3302. return vbo;
  3303. };
  3304. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  3305. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3306. if (offset === undefined) {
  3307. offset = 0;
  3308. }
  3309. if (vertices instanceof Float32Array) {
  3310. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  3311. } else {
  3312. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  3313. }
  3314. this._resetVertexBufferBinding();
  3315. };
  3316. Engine.prototype._resetIndexBufferBinding = function () {
  3317. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3318. this._cachedIndexBuffer = null;
  3319. };
  3320. Engine.prototype.createIndexBuffer = function (indices) {
  3321. var vbo = this._gl.createBuffer();
  3322. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3323. var arrayBuffer;
  3324. var need32Bits = false;
  3325. if (this._caps.uintIndices) {
  3326. for (var index = 0; index < indices.length; index++) {
  3327. if (indices[index] > 65535) {
  3328. need32Bits = true;
  3329. break;
  3330. }
  3331. }
  3332. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  3333. } else {
  3334. arrayBuffer = new Uint16Array(indices);
  3335. }
  3336. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  3337. this._resetIndexBufferBinding();
  3338. vbo.references = 1;
  3339. vbo.is32Bits = need32Bits;
  3340. return vbo;
  3341. };
  3342. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3343. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3344. this._cachedVertexBuffers = vertexBuffer;
  3345. this._cachedEffectForVertexBuffers = effect;
  3346. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3347. var offset = 0;
  3348. for (var index = 0; index < vertexDeclaration.length; index++) {
  3349. var order = effect.getAttributeLocation(index);
  3350. if (order >= 0) {
  3351. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3352. }
  3353. offset += vertexDeclaration[index] * 4;
  3354. }
  3355. }
  3356. if (this._cachedIndexBuffer !== indexBuffer) {
  3357. this._cachedIndexBuffer = indexBuffer;
  3358. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3359. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3360. }
  3361. };
  3362. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3363. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3364. this._cachedVertexBuffers = vertexBuffers;
  3365. this._cachedEffectForVertexBuffers = effect;
  3366. var attributes = effect.getAttributesNames();
  3367. for (var index = 0; index < attributes.length; index++) {
  3368. var order = effect.getAttributeLocation(index);
  3369. if (order >= 0) {
  3370. var vertexBuffer = vertexBuffers[attributes[index]];
  3371. if (!vertexBuffer) {
  3372. continue;
  3373. }
  3374. var stride = vertexBuffer.getStrideSize();
  3375. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3376. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3377. }
  3378. }
  3379. }
  3380. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3381. this._cachedIndexBuffer = indexBuffer;
  3382. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3383. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3384. }
  3385. };
  3386. Engine.prototype._releaseBuffer = function (buffer) {
  3387. buffer.references--;
  3388. if (buffer.references === 0) {
  3389. this._gl.deleteBuffer(buffer);
  3390. return true;
  3391. }
  3392. return false;
  3393. };
  3394. Engine.prototype.createInstancesBuffer = function (capacity) {
  3395. var buffer = this._gl.createBuffer();
  3396. buffer.capacity = capacity;
  3397. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3398. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3399. return buffer;
  3400. };
  3401. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3402. this._gl.deleteBuffer(buffer);
  3403. };
  3404. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3405. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3406. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3407. for (var index = 0; index < 4; index++) {
  3408. var offsetLocation = offsetLocations[index];
  3409. this._gl.enableVertexAttribArray(offsetLocation);
  3410. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3411. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3412. }
  3413. };
  3414. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3415. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3416. for (var index = 0; index < 4; index++) {
  3417. var offsetLocation = offsetLocations[index];
  3418. this._gl.disableVertexAttribArray(offsetLocation);
  3419. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3420. }
  3421. };
  3422. Engine.prototype.applyStates = function () {
  3423. this._depthCullingState.apply(this._gl);
  3424. this._alphaState.apply(this._gl);
  3425. };
  3426. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  3427. this.applyStates();
  3428. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  3429. if (instancesCount) {
  3430. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  3431. return;
  3432. }
  3433. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  3434. this._drawCalls++;
  3435. };
  3436. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  3437. this.applyStates();
  3438. if (instancesCount) {
  3439. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  3440. return;
  3441. }
  3442. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  3443. this._drawCalls++;
  3444. };
  3445. Engine.prototype._releaseEffect = function (effect) {
  3446. if (this._compiledEffects[effect._key]) {
  3447. delete this._compiledEffects[effect._key];
  3448. if (effect.getProgram()) {
  3449. this._gl.deleteProgram(effect.getProgram());
  3450. }
  3451. }
  3452. };
  3453. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3454. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3455. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  3456. var name = vertex + "+" + fragment + "@" + defines;
  3457. if (this._compiledEffects[name]) {
  3458. return this._compiledEffects[name];
  3459. }
  3460. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  3461. effect._key = name;
  3462. this._compiledEffects[name] = effect;
  3463. return effect;
  3464. };
  3465. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3466. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  3467. if (typeof samplers === "undefined") { samplers = []; }
  3468. if (typeof defines === "undefined") { defines = ""; }
  3469. return this.createEffect({
  3470. vertex: "particles",
  3471. fragmentElement: fragmentName
  3472. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  3473. };
  3474. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  3475. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  3476. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  3477. var shaderProgram = this._gl.createProgram();
  3478. this._gl.attachShader(shaderProgram, vertexShader);
  3479. this._gl.attachShader(shaderProgram, fragmentShader);
  3480. this._gl.linkProgram(shaderProgram);
  3481. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  3482. if (!linked) {
  3483. var error = this._gl.getProgramInfoLog(shaderProgram);
  3484. if (error) {
  3485. throw new Error(error);
  3486. }
  3487. }
  3488. this._gl.deleteShader(vertexShader);
  3489. this._gl.deleteShader(fragmentShader);
  3490. return shaderProgram;
  3491. };
  3492. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3493. var results = [];
  3494. for (var index = 0; index < uniformsNames.length; index++) {
  3495. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3496. }
  3497. return results;
  3498. };
  3499. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3500. var results = [];
  3501. for (var index = 0; index < attributesNames.length; index++) {
  3502. try {
  3503. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3504. } catch (e) {
  3505. results.push(-1);
  3506. }
  3507. }
  3508. return results;
  3509. };
  3510. Engine.prototype.enableEffect = function (effect) {
  3511. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3512. if (effect && effect.onBind) {
  3513. effect.onBind(effect);
  3514. }
  3515. return;
  3516. }
  3517. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3518. this._gl.useProgram(effect.getProgram());
  3519. for (var i in this._vertexAttribArrays) {
  3520. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3521. continue;
  3522. }
  3523. this._vertexAttribArrays[i] = false;
  3524. this._gl.disableVertexAttribArray(i);
  3525. }
  3526. var attributesCount = effect.getAttributesCount();
  3527. for (var index = 0; index < attributesCount; index++) {
  3528. var order = effect.getAttributeLocation(index);
  3529. if (order >= 0) {
  3530. this._vertexAttribArrays[order] = true;
  3531. this._gl.enableVertexAttribArray(order);
  3532. }
  3533. }
  3534. this._currentEffect = effect;
  3535. if (effect.onBind) {
  3536. effect.onBind(effect);
  3537. }
  3538. };
  3539. Engine.prototype.setArray = function (uniform, array) {
  3540. if (!uniform)
  3541. return;
  3542. this._gl.uniform1fv(uniform, array);
  3543. };
  3544. Engine.prototype.setMatrices = function (uniform, matrices) {
  3545. if (!uniform)
  3546. return;
  3547. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3548. };
  3549. Engine.prototype.setMatrix = function (uniform, matrix) {
  3550. if (!uniform)
  3551. return;
  3552. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3553. };
  3554. Engine.prototype.setFloat = function (uniform, value) {
  3555. if (!uniform)
  3556. return;
  3557. this._gl.uniform1f(uniform, value);
  3558. };
  3559. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3560. if (!uniform)
  3561. return;
  3562. this._gl.uniform2f(uniform, x, y);
  3563. };
  3564. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3565. if (!uniform)
  3566. return;
  3567. this._gl.uniform3f(uniform, x, y, z);
  3568. };
  3569. Engine.prototype.setBool = function (uniform, bool) {
  3570. if (!uniform)
  3571. return;
  3572. this._gl.uniform1i(uniform, bool);
  3573. };
  3574. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3575. if (!uniform)
  3576. return;
  3577. this._gl.uniform4f(uniform, x, y, z, w);
  3578. };
  3579. Engine.prototype.setColor3 = function (uniform, color3) {
  3580. if (!uniform)
  3581. return;
  3582. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3583. };
  3584. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3585. if (!uniform)
  3586. return;
  3587. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3588. };
  3589. Engine.prototype.setState = function (culling, force) {
  3590. if (this._depthCullingState.cull !== culling || force) {
  3591. if (culling) {
  3592. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3593. this._depthCullingState.cull = true;
  3594. } else {
  3595. this._depthCullingState.cull = false;
  3596. }
  3597. }
  3598. };
  3599. Engine.prototype.setDepthBuffer = function (enable) {
  3600. this._depthCullingState.depthTest = enable;
  3601. };
  3602. Engine.prototype.getDepthWrite = function () {
  3603. return this._depthCullingState.depthMask;
  3604. };
  3605. Engine.prototype.setDepthWrite = function (enable) {
  3606. this._depthCullingState.depthMask = enable;
  3607. };
  3608. Engine.prototype.setColorWrite = function (enable) {
  3609. this._gl.colorMask(enable, enable, enable, enable);
  3610. };
  3611. Engine.prototype.setAlphaMode = function (mode) {
  3612. switch (mode) {
  3613. case BABYLON.Engine.ALPHA_DISABLE:
  3614. this.setDepthWrite(true);
  3615. this._alphaState.alphaBlend = false;
  3616. break;
  3617. case BABYLON.Engine.ALPHA_COMBINE:
  3618. this.setDepthWrite(false);
  3619. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3620. this._alphaState.alphaBlend = true;
  3621. break;
  3622. case BABYLON.Engine.ALPHA_ADD:
  3623. this.setDepthWrite(false);
  3624. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3625. this._alphaState.alphaBlend = true;
  3626. break;
  3627. }
  3628. this._alphaMode = mode;
  3629. };
  3630. Engine.prototype.getAlphaMode = function () {
  3631. return this._alphaMode;
  3632. };
  3633. Engine.prototype.setAlphaTesting = function (enable) {
  3634. this._alphaTest = enable;
  3635. };
  3636. Engine.prototype.getAlphaTesting = function () {
  3637. return this._alphaTest;
  3638. };
  3639. Engine.prototype.wipeCaches = function () {
  3640. this._activeTexturesCache = [];
  3641. this._currentEffect = null;
  3642. this._depthCullingState.reset();
  3643. this._alphaState.reset();
  3644. this._cachedVertexBuffers = null;
  3645. this._cachedIndexBuffer = null;
  3646. this._cachedEffectForVertexBuffers = null;
  3647. };
  3648. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3649. var gl = this._gl;
  3650. gl.bindTexture(gl.TEXTURE_2D, texture);
  3651. var magFilter = gl.NEAREST;
  3652. var minFilter = gl.NEAREST;
  3653. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3654. magFilter = gl.LINEAR;
  3655. minFilter = gl.LINEAR;
  3656. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3657. magFilter = gl.LINEAR;
  3658. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3659. }
  3660. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3661. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3662. gl.bindTexture(gl.TEXTURE_2D, null);
  3663. };
  3664. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  3665. var _this = this;
  3666. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3667. if (typeof onLoad === "undefined") { onLoad = null; }
  3668. if (typeof onError === "undefined") { onError = null; }
  3669. if (typeof buffer === "undefined") { buffer = null; }
  3670. var texture = this._gl.createTexture();
  3671. var extension;
  3672. var fromData = false;
  3673. if (url.substr(0, 5) === "data:") {
  3674. fromData = true;
  3675. }
  3676. if (!fromData)
  3677. extension = url.substr(url.length - 4, 4).toLowerCase();
  3678. else {
  3679. var oldUrl = url;
  3680. fromData = oldUrl.split(':');
  3681. url = oldUrl;
  3682. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  3683. }
  3684. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3685. var isTGA = (extension === ".tga");
  3686. scene._addPendingData(texture);
  3687. texture.url = url;
  3688. texture.noMipmap = noMipmap;
  3689. texture.references = 1;
  3690. this._loadedTexturesCache.push(texture);
  3691. var onerror = function () {
  3692. scene._removePendingData(texture);
  3693. if (onError) {
  3694. onError();
  3695. }
  3696. };
  3697. if (isTGA) {
  3698. var callback = function (arrayBuffer) {
  3699. var data = new Uint8Array(arrayBuffer);
  3700. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3701. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3702. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3703. if (onLoad) {
  3704. onLoad();
  3705. }
  3706. }, samplingMode);
  3707. };
  3708. if (!(fromData instanceof Array))
  3709. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3710. callback(arrayBuffer);
  3711. }, onerror, scene.database, true);
  3712. else
  3713. callback(buffer);
  3714. } else if (isDDS) {
  3715. callback = function (data) {
  3716. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3717. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3718. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3719. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3720. if (onLoad) {
  3721. onLoad();
  3722. }
  3723. }, samplingMode);
  3724. };
  3725. if (!(fromData instanceof Array))
  3726. BABYLON.Tools.LoadFile(url, function (data) {
  3727. callback(data);
  3728. }, onerror, scene.database, true);
  3729. else
  3730. callback(buffer);
  3731. } else {
  3732. var onload = function (img) {
  3733. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3734. var isPot = (img.width == potWidth && img.height == potHeight);
  3735. if (!isPot) {
  3736. _this._workingCanvas.width = potWidth;
  3737. _this._workingCanvas.height = potHeight;
  3738. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3739. }
  3740. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3741. if (onLoad) {
  3742. onLoad();
  3743. }
  3744. }, samplingMode);
  3745. };
  3746. if (!(fromData instanceof Array))
  3747. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3748. else
  3749. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  3750. }
  3751. return texture;
  3752. };
  3753. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  3754. var texture = this._gl.createTexture();
  3755. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  3756. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  3757. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3758. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3759. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3760. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3761. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3762. this._activeTexturesCache = [];
  3763. texture._baseWidth = width;
  3764. texture._baseHeight = height;
  3765. texture._width = width;
  3766. texture._height = height;
  3767. texture.isReady = false;
  3768. texture.generateMipMaps = generateMipMaps;
  3769. texture.references = 1;
  3770. this._loadedTexturesCache.push(texture);
  3771. return texture;
  3772. };
  3773. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  3774. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3775. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3776. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  3777. if (texture.generateMipMaps) {
  3778. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3779. }
  3780. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3781. this._activeTexturesCache = [];
  3782. texture.isReady = true;
  3783. };
  3784. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  3785. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3786. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1);
  3787. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  3788. if (!texture._workingCanvas) {
  3789. texture._workingCanvas = document.createElement("canvas");
  3790. texture._workingContext = texture._workingCanvas.getContext("2d");
  3791. texture._workingCanvas.width = texture._width;
  3792. texture._workingCanvas.height = texture._height;
  3793. }
  3794. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  3795. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3796. } else {
  3797. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3798. }
  3799. if (texture.generateMipMaps) {
  3800. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3801. }
  3802. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3803. this._activeTexturesCache = [];
  3804. texture.isReady = true;
  3805. };
  3806. Engine.prototype.createRenderTargetTexture = function (size, options) {
  3807. var generateMipMaps = false;
  3808. var generateDepthBuffer = true;
  3809. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3810. if (options !== undefined) {
  3811. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  3812. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3813. if (options.samplingMode !== undefined) {
  3814. samplingMode = options.samplingMode;
  3815. }
  3816. }
  3817. var gl = this._gl;
  3818. var texture = gl.createTexture();
  3819. gl.bindTexture(gl.TEXTURE_2D, texture);
  3820. var width = size.width || size;
  3821. var height = size.height || size;
  3822. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3823. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3824. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3825. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3826. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3827. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  3828. var depthBuffer;
  3829. if (generateDepthBuffer) {
  3830. depthBuffer = gl.createRenderbuffer();
  3831. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  3832. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3833. }
  3834. var framebuffer = gl.createFramebuffer();
  3835. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  3836. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3837. if (generateDepthBuffer) {
  3838. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  3839. }
  3840. gl.bindTexture(gl.TEXTURE_2D, null);
  3841. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3842. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3843. texture._framebuffer = framebuffer;
  3844. if (generateDepthBuffer) {
  3845. texture._depthBuffer = depthBuffer;
  3846. }
  3847. texture._width = width;
  3848. texture._height = height;
  3849. texture.isReady = true;
  3850. texture.generateMipMaps = generateMipMaps;
  3851. texture.references = 1;
  3852. this._activeTexturesCache = [];
  3853. this._loadedTexturesCache.push(texture);
  3854. return texture;
  3855. };
  3856. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  3857. var _this = this;
  3858. var gl = this._gl;
  3859. var texture = gl.createTexture();
  3860. texture.isCube = true;
  3861. texture.url = rootUrl;
  3862. texture.references = 1;
  3863. this._loadedTexturesCache.push(texture);
  3864. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  3865. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3866. if (isDDS) {
  3867. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  3868. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3869. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3870. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3871. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3872. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  3873. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  3874. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3875. }
  3876. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3877. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3878. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3879. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3880. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3881. _this._activeTexturesCache = [];
  3882. texture._width = info.width;
  3883. texture._height = info.height;
  3884. texture.isReady = true;
  3885. }, null, null, true);
  3886. } else {
  3887. cascadeLoad(rootUrl, scene, function (imgs) {
  3888. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  3889. var height = width;
  3890. _this._workingCanvas.width = width;
  3891. _this._workingCanvas.height = height;
  3892. var faces = [
  3893. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3894. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3895. ];
  3896. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3897. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3898. for (var index = 0; index < faces.length; index++) {
  3899. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3900. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  3901. }
  3902. if (!noMipmap) {
  3903. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3904. }
  3905. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3906. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  3907. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3908. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3909. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3910. _this._activeTexturesCache = [];
  3911. texture._width = width;
  3912. texture._height = height;
  3913. texture.isReady = true;
  3914. }, extensions);
  3915. }
  3916. return texture;
  3917. };
  3918. Engine.prototype._releaseTexture = function (texture) {
  3919. var gl = this._gl;
  3920. if (texture._framebuffer) {
  3921. gl.deleteFramebuffer(texture._framebuffer);
  3922. }
  3923. if (texture._depthBuffer) {
  3924. gl.deleteRenderbuffer(texture._depthBuffer);
  3925. }
  3926. gl.deleteTexture(texture);
  3927. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3928. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3929. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3930. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3931. this._activeTexturesCache[channel] = null;
  3932. }
  3933. var index = this._loadedTexturesCache.indexOf(texture);
  3934. if (index !== -1) {
  3935. this._loadedTexturesCache.splice(index, 1);
  3936. }
  3937. };
  3938. Engine.prototype.bindSamplers = function (effect) {
  3939. this._gl.useProgram(effect.getProgram());
  3940. var samplers = effect.getSamplers();
  3941. for (var index = 0; index < samplers.length; index++) {
  3942. var uniform = effect.getUniform(samplers[index]);
  3943. this._gl.uniform1i(uniform, index);
  3944. }
  3945. this._currentEffect = null;
  3946. };
  3947. Engine.prototype._bindTexture = function (channel, texture) {
  3948. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3949. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3950. this._activeTexturesCache[channel] = null;
  3951. };
  3952. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  3953. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3954. };
  3955. Engine.prototype.setTexture = function (channel, texture) {
  3956. if (channel < 0) {
  3957. return;
  3958. }
  3959. if (!texture || !texture.isReady()) {
  3960. if (this._activeTexturesCache[channel] != null) {
  3961. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3962. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3963. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3964. this._activeTexturesCache[channel] = null;
  3965. }
  3966. return;
  3967. }
  3968. if (texture instanceof BABYLON.VideoTexture) {
  3969. if (texture.update()) {
  3970. this._activeTexturesCache[channel] = null;
  3971. }
  3972. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  3973. texture.delayLoad();
  3974. return;
  3975. }
  3976. if (this._activeTexturesCache[channel] == texture) {
  3977. return;
  3978. }
  3979. this._activeTexturesCache[channel] = texture;
  3980. var internalTexture = texture.getInternalTexture();
  3981. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3982. if (internalTexture.isCube) {
  3983. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3984. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3985. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3986. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3987. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3988. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3989. }
  3990. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3991. } else {
  3992. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  3993. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3994. internalTexture._cachedWrapU = texture.wrapU;
  3995. switch (texture.wrapU) {
  3996. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3997. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3998. break;
  3999. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4000. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4001. break;
  4002. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4003. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4004. break;
  4005. }
  4006. }
  4007. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4008. internalTexture._cachedWrapV = texture.wrapV;
  4009. switch (texture.wrapV) {
  4010. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4011. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4012. break;
  4013. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4014. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4015. break;
  4016. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4017. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4018. break;
  4019. }
  4020. }
  4021. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4022. }
  4023. };
  4024. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4025. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4026. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4027. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4028. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4029. }
  4030. };
  4031. Engine.prototype.readPixels = function (x, y, width, height) {
  4032. var data = new Uint8Array(height * width * 4);
  4033. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4034. return data;
  4035. };
  4036. Engine.prototype.dispose = function () {
  4037. this.hideLoadingUI();
  4038. this.stopRenderLoop();
  4039. while (this.scenes.length) {
  4040. this.scenes[0].dispose();
  4041. }
  4042. for (var name in this._compiledEffects) {
  4043. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4044. }
  4045. for (var i in this._vertexAttribArrays) {
  4046. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4047. continue;
  4048. }
  4049. this._gl.disableVertexAttribArray(i);
  4050. }
  4051. window.removeEventListener("blur", this._onBlur);
  4052. window.removeEventListener("focus", this._onFocus);
  4053. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4054. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4055. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4056. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4057. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4058. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4059. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4060. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4061. };
  4062. Engine.prototype.displayLoadingUI = function () {
  4063. var _this = this;
  4064. this._loadingDiv = document.createElement("div");
  4065. this._loadingDiv.style.opacity = "0";
  4066. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4067. this._loadingTextDiv = document.createElement("div");
  4068. this._loadingTextDiv.style.position = "absolute";
  4069. this._loadingTextDiv.style.left = "0";
  4070. this._loadingTextDiv.style.top = "50%";
  4071. this._loadingTextDiv.style.marginTop = "80px";
  4072. this._loadingTextDiv.style.width = "100%";
  4073. this._loadingTextDiv.style.height = "20px";
  4074. this._loadingTextDiv.style.fontFamily = "Arial";
  4075. this._loadingTextDiv.style.fontSize = "14px";
  4076. this._loadingTextDiv.style.color = "white";
  4077. this._loadingTextDiv.style.textAlign = "center";
  4078. this._loadingTextDiv.innerHTML = "Loading";
  4079. this._loadingDiv.appendChild(this._loadingTextDiv);
  4080. var imgBack = new Image();
  4081. 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==";
  4082. imgBack.style.position = "absolute";
  4083. imgBack.style.left = "50%";
  4084. imgBack.style.top = "50%";
  4085. imgBack.style.marginLeft = "-50px";
  4086. imgBack.style.marginTop = "-50px";
  4087. imgBack.style.transition = "transform 1.0s ease";
  4088. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4089. var deg = 360;
  4090. var onTransitionEnd = function () {
  4091. deg += 360;
  4092. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4093. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4094. };
  4095. imgBack.addEventListener("transitionend", onTransitionEnd);
  4096. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4097. this._loadingDiv.appendChild(imgBack);
  4098. var imgFront = new Image();
  4099. 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=";
  4100. imgFront.style.position = "absolute";
  4101. imgFront.style.left = "50%";
  4102. imgFront.style.top = "50%";
  4103. imgFront.style.marginLeft = "-50px";
  4104. imgFront.style.marginTop = "-50px";
  4105. this._loadingDiv.appendChild(imgFront);
  4106. this._resizeLoadingUI = function () {
  4107. var canvasRect = _this.getRenderingCanvasClientRect();
  4108. _this._loadingDiv.style.position = "absolute";
  4109. _this._loadingDiv.style.left = canvasRect.left + "px";
  4110. _this._loadingDiv.style.top = canvasRect.top + "px";
  4111. _this._loadingDiv.style.width = canvasRect.width + "px";
  4112. _this._loadingDiv.style.height = canvasRect.height + "px";
  4113. };
  4114. this._resizeLoadingUI();
  4115. window.addEventListener("resize", this._resizeLoadingUI);
  4116. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4117. document.body.appendChild(this._loadingDiv);
  4118. setTimeout(function () {
  4119. _this._loadingDiv.style.opacity = "1";
  4120. imgBack.style.transform = "rotateZ(360deg)";
  4121. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4122. }, 0);
  4123. };
  4124. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4125. set: function (text) {
  4126. if (!this._loadingDiv) {
  4127. return;
  4128. }
  4129. this._loadingTextDiv.innerHTML = text;
  4130. },
  4131. enumerable: true,
  4132. configurable: true
  4133. });
  4134. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4135. get: function () {
  4136. return this._loadingDivBackgroundColor;
  4137. },
  4138. set: function (color) {
  4139. this._loadingDivBackgroundColor = color;
  4140. if (!this._loadingDiv) {
  4141. return;
  4142. }
  4143. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4144. },
  4145. enumerable: true,
  4146. configurable: true
  4147. });
  4148. Engine.prototype.hideLoadingUI = function () {
  4149. var _this = this;
  4150. if (!this._loadingDiv) {
  4151. return;
  4152. }
  4153. var onTransitionEnd = function () {
  4154. if (!_this._loadingDiv) {
  4155. return;
  4156. }
  4157. document.body.removeChild(_this._loadingDiv);
  4158. window.removeEventListener("resize", _this._resizeLoadingUI);
  4159. _this._loadingDiv = null;
  4160. };
  4161. this._loadingDiv.style.opacity = "0";
  4162. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4163. };
  4164. Engine.isSupported = function () {
  4165. try {
  4166. if (navigator.isCocoonJS) {
  4167. return true;
  4168. }
  4169. var tempcanvas = document.createElement("canvas");
  4170. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4171. return gl != null && !!window.WebGLRenderingContext;
  4172. } catch (e) {
  4173. return false;
  4174. }
  4175. };
  4176. Engine._ALPHA_DISABLE = 0;
  4177. Engine._ALPHA_ADD = 1;
  4178. Engine._ALPHA_COMBINE = 2;
  4179. Engine._DELAYLOADSTATE_NONE = 0;
  4180. Engine._DELAYLOADSTATE_LOADED = 1;
  4181. Engine._DELAYLOADSTATE_LOADING = 2;
  4182. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4183. Engine.Epsilon = 0.001;
  4184. Engine.CollisionsEpsilon = 0.001;
  4185. Engine.ShadersRepository = "Babylon/Shaders/";
  4186. return Engine;
  4187. })();
  4188. BABYLON.Engine = Engine;
  4189. })(BABYLON || (BABYLON = {}));
  4190. var BABYLON;
  4191. (function (BABYLON) {
  4192. var Node = (function () {
  4193. function Node(name, scene) {
  4194. this.state = "";
  4195. this.animations = new Array();
  4196. this._childrenFlag = -1;
  4197. this._isEnabled = true;
  4198. this._isReady = true;
  4199. this._currentRenderId = -1;
  4200. this.name = name;
  4201. this.id = name;
  4202. this._scene = scene;
  4203. this._initCache();
  4204. }
  4205. Node.prototype.getScene = function () {
  4206. return this._scene;
  4207. };
  4208. Node.prototype.getEngine = function () {
  4209. return this._scene.getEngine();
  4210. };
  4211. Node.prototype.getWorldMatrix = function () {
  4212. return BABYLON.Matrix.Identity();
  4213. };
  4214. Node.prototype._initCache = function () {
  4215. this._cache = {};
  4216. this._cache.parent = undefined;
  4217. };
  4218. Node.prototype.updateCache = function (force) {
  4219. if (!force && this.isSynchronized())
  4220. return;
  4221. this._cache.parent = this.parent;
  4222. this._updateCache();
  4223. };
  4224. Node.prototype._updateCache = function (ignoreParentClass) {
  4225. };
  4226. Node.prototype._isSynchronized = function () {
  4227. return true;
  4228. };
  4229. Node.prototype.isSynchronizedWithParent = function () {
  4230. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4231. };
  4232. Node.prototype.isSynchronized = function (updateCache) {
  4233. var check = this.hasNewParent();
  4234. check = check || !this.isSynchronizedWithParent();
  4235. check = check || !this._isSynchronized();
  4236. if (updateCache)
  4237. this.updateCache(true);
  4238. return !check;
  4239. };
  4240. Node.prototype.hasNewParent = function (update) {
  4241. if (this._cache.parent === this.parent)
  4242. return false;
  4243. if (update)
  4244. this._cache.parent = this.parent;
  4245. return true;
  4246. };
  4247. Node.prototype.isReady = function () {
  4248. return this._isReady;
  4249. };
  4250. Node.prototype.isEnabled = function () {
  4251. if (!this._isEnabled) {
  4252. return false;
  4253. }
  4254. if (this.parent) {
  4255. return this.parent.isEnabled();
  4256. }
  4257. return true;
  4258. };
  4259. Node.prototype.setEnabled = function (value) {
  4260. this._isEnabled = value;
  4261. };
  4262. Node.prototype.isDescendantOf = function (ancestor) {
  4263. if (this.parent) {
  4264. if (this.parent === ancestor) {
  4265. return true;
  4266. }
  4267. return this.parent.isDescendantOf(ancestor);
  4268. }
  4269. return false;
  4270. };
  4271. Node.prototype._getDescendants = function (list, results) {
  4272. for (var index = 0; index < list.length; index++) {
  4273. var item = list[index];
  4274. if (item.isDescendantOf(this)) {
  4275. results.push(item);
  4276. }
  4277. }
  4278. };
  4279. Node.prototype.getDescendants = function () {
  4280. var results = [];
  4281. this._getDescendants(this._scene.meshes, results);
  4282. this._getDescendants(this._scene.lights, results);
  4283. this._getDescendants(this._scene.cameras, results);
  4284. return results;
  4285. };
  4286. Node.prototype._setReady = function (state) {
  4287. if (state == this._isReady) {
  4288. return;
  4289. }
  4290. if (!state) {
  4291. this._isReady = false;
  4292. return;
  4293. }
  4294. this._isReady = true;
  4295. if (this.onReady) {
  4296. this.onReady(this);
  4297. }
  4298. };
  4299. return Node;
  4300. })();
  4301. BABYLON.Node = Node;
  4302. })(BABYLON || (BABYLON = {}));
  4303. var BABYLON;
  4304. (function (BABYLON) {
  4305. var BoundingSphere = (function () {
  4306. function BoundingSphere(minimum, maximum) {
  4307. this.minimum = minimum;
  4308. this.maximum = maximum;
  4309. this._tempRadiusVector = BABYLON.Vector3.Zero();
  4310. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  4311. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  4312. this.radius = distance * 0.5;
  4313. this.centerWorld = BABYLON.Vector3.Zero();
  4314. this._update(BABYLON.Matrix.Identity());
  4315. }
  4316. BoundingSphere.prototype._update = function (world) {
  4317. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  4318. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  4319. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  4320. };
  4321. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  4322. for (var i = 0; i < 6; i++) {
  4323. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  4324. return false;
  4325. }
  4326. return true;
  4327. };
  4328. BoundingSphere.prototype.intersectsPoint = function (point) {
  4329. var x = this.centerWorld.x - point.x;
  4330. var y = this.centerWorld.y - point.y;
  4331. var z = this.centerWorld.z - point.z;
  4332. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4333. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  4334. return false;
  4335. return true;
  4336. };
  4337. BoundingSphere.Intersects = function (sphere0, sphere1) {
  4338. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  4339. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  4340. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  4341. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4342. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  4343. return false;
  4344. return true;
  4345. };
  4346. return BoundingSphere;
  4347. })();
  4348. BABYLON.BoundingSphere = BoundingSphere;
  4349. })(BABYLON || (BABYLON = {}));
  4350. var BABYLON;
  4351. (function (BABYLON) {
  4352. var BoundingBox = (function () {
  4353. function BoundingBox(minimum, maximum) {
  4354. this.minimum = minimum;
  4355. this.maximum = maximum;
  4356. this.vectors = new Array();
  4357. this.vectorsWorld = new Array();
  4358. this.vectors.push(this.minimum.clone());
  4359. this.vectors.push(this.maximum.clone());
  4360. this.vectors.push(this.minimum.clone());
  4361. this.vectors[2].x = this.maximum.x;
  4362. this.vectors.push(this.minimum.clone());
  4363. this.vectors[3].y = this.maximum.y;
  4364. this.vectors.push(this.minimum.clone());
  4365. this.vectors[4].z = this.maximum.z;
  4366. this.vectors.push(this.maximum.clone());
  4367. this.vectors[5].z = this.minimum.z;
  4368. this.vectors.push(this.maximum.clone());
  4369. this.vectors[6].x = this.minimum.x;
  4370. this.vectors.push(this.maximum.clone());
  4371. this.vectors[7].y = this.minimum.y;
  4372. this.center = this.maximum.add(this.minimum).scale(0.5);
  4373. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  4374. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  4375. for (var index = 0; index < this.vectors.length; index++) {
  4376. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  4377. }
  4378. this.minimumWorld = BABYLON.Vector3.Zero();
  4379. this.maximumWorld = BABYLON.Vector3.Zero();
  4380. this._update(BABYLON.Matrix.Identity());
  4381. }
  4382. BoundingBox.prototype.getWorldMatrix = function () {
  4383. return this._worldMatrix;
  4384. };
  4385. BoundingBox.prototype._update = function (world) {
  4386. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  4387. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  4388. for (var index = 0; index < this.vectors.length; index++) {
  4389. var v = this.vectorsWorld[index];
  4390. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  4391. if (v.x < this.minimumWorld.x)
  4392. this.minimumWorld.x = v.x;
  4393. if (v.y < this.minimumWorld.y)
  4394. this.minimumWorld.y = v.y;
  4395. if (v.z < this.minimumWorld.z)
  4396. this.minimumWorld.z = v.z;
  4397. if (v.x > this.maximumWorld.x)
  4398. this.maximumWorld.x = v.x;
  4399. if (v.y > this.maximumWorld.y)
  4400. this.maximumWorld.y = v.y;
  4401. if (v.z > this.maximumWorld.z)
  4402. this.maximumWorld.z = v.z;
  4403. }
  4404. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  4405. this.center.scaleInPlace(0.5);
  4406. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  4407. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  4408. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  4409. this._worldMatrix = world;
  4410. };
  4411. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  4412. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  4413. };
  4414. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4415. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  4416. };
  4417. BoundingBox.prototype.intersectsPoint = function (point) {
  4418. var delta = BABYLON.Engine.Epsilon;
  4419. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  4420. return false;
  4421. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  4422. return false;
  4423. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  4424. return false;
  4425. return true;
  4426. };
  4427. BoundingBox.prototype.intersectsSphere = function (sphere) {
  4428. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  4429. };
  4430. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  4431. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  4432. return false;
  4433. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  4434. return false;
  4435. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  4436. return false;
  4437. return true;
  4438. };
  4439. BoundingBox.Intersects = function (box0, box1) {
  4440. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  4441. return false;
  4442. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  4443. return false;
  4444. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  4445. return false;
  4446. return true;
  4447. };
  4448. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  4449. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  4450. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  4451. return (num <= (sphereRadius * sphereRadius));
  4452. };
  4453. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  4454. for (var p = 0; p < 6; p++) {
  4455. for (var i = 0; i < 8; i++) {
  4456. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4457. return false;
  4458. }
  4459. }
  4460. }
  4461. return true;
  4462. };
  4463. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  4464. for (var p = 0; p < 6; p++) {
  4465. var inCount = 8;
  4466. for (var i = 0; i < 8; i++) {
  4467. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4468. --inCount;
  4469. } else {
  4470. break;
  4471. }
  4472. }
  4473. if (inCount == 0)
  4474. return false;
  4475. }
  4476. return true;
  4477. };
  4478. return BoundingBox;
  4479. })();
  4480. BABYLON.BoundingBox = BoundingBox;
  4481. })(BABYLON || (BABYLON = {}));
  4482. var BABYLON;
  4483. (function (BABYLON) {
  4484. var computeBoxExtents = function (axis, box) {
  4485. var p = BABYLON.Vector3.Dot(box.center, axis);
  4486. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  4487. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  4488. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  4489. var r = r0 + r1 + r2;
  4490. return {
  4491. min: p - r,
  4492. max: p + r
  4493. };
  4494. };
  4495. var extentsOverlap = function (min0, max0, min1, max1) {
  4496. return !(min0 > max1 || min1 > max0);
  4497. };
  4498. var axisOverlap = function (axis, box0, box1) {
  4499. var result0 = computeBoxExtents(axis, box0);
  4500. var result1 = computeBoxExtents(axis, box1);
  4501. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  4502. };
  4503. var BoundingInfo = (function () {
  4504. function BoundingInfo(minimum, maximum) {
  4505. this.minimum = minimum;
  4506. this.maximum = maximum;
  4507. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  4508. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  4509. }
  4510. BoundingInfo.prototype._update = function (world) {
  4511. this.boundingBox._update(world);
  4512. this.boundingSphere._update(world);
  4513. };
  4514. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  4515. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  4516. return false;
  4517. return this.boundingBox.isInFrustum(frustumPlanes);
  4518. };
  4519. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4520. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  4521. };
  4522. BoundingInfo.prototype._checkCollision = function (collider) {
  4523. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  4524. };
  4525. BoundingInfo.prototype.intersectsPoint = function (point) {
  4526. if (!this.boundingSphere.centerWorld) {
  4527. return false;
  4528. }
  4529. if (!this.boundingSphere.intersectsPoint(point)) {
  4530. return false;
  4531. }
  4532. if (!this.boundingBox.intersectsPoint(point)) {
  4533. return false;
  4534. }
  4535. return true;
  4536. };
  4537. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  4538. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  4539. return false;
  4540. }
  4541. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  4542. return false;
  4543. }
  4544. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  4545. return false;
  4546. }
  4547. if (!precise) {
  4548. return true;
  4549. }
  4550. var box0 = this.boundingBox;
  4551. var box1 = boundingInfo.boundingBox;
  4552. if (!axisOverlap(box0.directions[0], box0, box1))
  4553. return false;
  4554. if (!axisOverlap(box0.directions[1], box0, box1))
  4555. return false;
  4556. if (!axisOverlap(box0.directions[2], box0, box1))
  4557. return false;
  4558. if (!axisOverlap(box1.directions[0], box0, box1))
  4559. return false;
  4560. if (!axisOverlap(box1.directions[1], box0, box1))
  4561. return false;
  4562. if (!axisOverlap(box1.directions[2], box0, box1))
  4563. return false;
  4564. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  4565. return false;
  4566. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  4567. return false;
  4568. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  4569. return false;
  4570. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  4571. return false;
  4572. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  4573. return false;
  4574. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  4575. return false;
  4576. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  4577. return false;
  4578. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  4579. return false;
  4580. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  4581. return false;
  4582. return true;
  4583. };
  4584. return BoundingInfo;
  4585. })();
  4586. BABYLON.BoundingInfo = BoundingInfo;
  4587. })(BABYLON || (BABYLON = {}));
  4588. var __extends = this.__extends || function (d, b) {
  4589. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4590. function __() { this.constructor = d; }
  4591. __.prototype = b.prototype;
  4592. d.prototype = new __();
  4593. };
  4594. var BABYLON;
  4595. (function (BABYLON) {
  4596. var Light = (function (_super) {
  4597. __extends(Light, _super);
  4598. function Light(name, scene) {
  4599. _super.call(this, name, scene);
  4600. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  4601. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  4602. this.intensity = 1.0;
  4603. this.range = Number.MAX_VALUE;
  4604. this.includedOnlyMeshes = new Array();
  4605. this.excludedMeshes = new Array();
  4606. this._excludedMeshesIds = new Array();
  4607. this._includedOnlyMeshesIds = new Array();
  4608. scene.lights.push(this);
  4609. }
  4610. Light.prototype.getShadowGenerator = function () {
  4611. return this._shadowGenerator;
  4612. };
  4613. Light.prototype.getAbsolutePosition = function () {
  4614. return BABYLON.Vector3.Zero();
  4615. };
  4616. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4617. };
  4618. Light.prototype._getWorldMatrix = function () {
  4619. return BABYLON.Matrix.Identity();
  4620. };
  4621. Light.prototype.canAffectMesh = function (mesh) {
  4622. if (!mesh) {
  4623. return true;
  4624. }
  4625. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4626. return false;
  4627. }
  4628. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4629. return false;
  4630. }
  4631. return true;
  4632. };
  4633. Light.prototype.getWorldMatrix = function () {
  4634. this._currentRenderId = this.getScene().getRenderId();
  4635. var worldMatrix = this._getWorldMatrix();
  4636. if (this.parent && this.parent.getWorldMatrix) {
  4637. if (!this._parentedWorldMatrix) {
  4638. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4639. }
  4640. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4641. return this._parentedWorldMatrix;
  4642. }
  4643. return worldMatrix;
  4644. };
  4645. Light.prototype.dispose = function () {
  4646. if (this._shadowGenerator) {
  4647. this._shadowGenerator.dispose();
  4648. this._shadowGenerator = null;
  4649. }
  4650. var index = this.getScene().lights.indexOf(this);
  4651. this.getScene().lights.splice(index, 1);
  4652. };
  4653. return Light;
  4654. })(BABYLON.Node);
  4655. BABYLON.Light = Light;
  4656. })(BABYLON || (BABYLON = {}));
  4657. var __extends = this.__extends || function (d, b) {
  4658. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4659. function __() { this.constructor = d; }
  4660. __.prototype = b.prototype;
  4661. d.prototype = new __();
  4662. };
  4663. var BABYLON;
  4664. (function (BABYLON) {
  4665. var PointLight = (function (_super) {
  4666. __extends(PointLight, _super);
  4667. function PointLight(name, position, scene) {
  4668. _super.call(this, name, scene);
  4669. this.position = position;
  4670. }
  4671. PointLight.prototype.getAbsolutePosition = function () {
  4672. return this._transformedPosition ? this._transformedPosition : this.position;
  4673. };
  4674. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  4675. if (this.parent && this.parent.getWorldMatrix) {
  4676. if (!this._transformedPosition) {
  4677. this._transformedPosition = BABYLON.Vector3.Zero();
  4678. }
  4679. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4680. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  4681. return;
  4682. }
  4683. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  4684. };
  4685. PointLight.prototype.getShadowGenerator = function () {
  4686. return null;
  4687. };
  4688. PointLight.prototype._getWorldMatrix = function () {
  4689. if (!this._worldMatrix) {
  4690. this._worldMatrix = BABYLON.Matrix.Identity();
  4691. }
  4692. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4693. return this._worldMatrix;
  4694. };
  4695. return PointLight;
  4696. })(BABYLON.Light);
  4697. BABYLON.PointLight = PointLight;
  4698. })(BABYLON || (BABYLON = {}));
  4699. var __extends = this.__extends || function (d, b) {
  4700. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4701. function __() { this.constructor = d; }
  4702. __.prototype = b.prototype;
  4703. d.prototype = new __();
  4704. };
  4705. var BABYLON;
  4706. (function (BABYLON) {
  4707. var SpotLight = (function (_super) {
  4708. __extends(SpotLight, _super);
  4709. function SpotLight(name, position, direction, angle, exponent, scene) {
  4710. _super.call(this, name, scene);
  4711. this.position = position;
  4712. this.direction = direction;
  4713. this.angle = angle;
  4714. this.exponent = exponent;
  4715. }
  4716. SpotLight.prototype.getAbsolutePosition = function () {
  4717. return this._transformedPosition ? this._transformedPosition : this.position;
  4718. };
  4719. SpotLight.prototype.setDirectionToTarget = function (target) {
  4720. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4721. return this.direction;
  4722. };
  4723. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  4724. var normalizeDirection;
  4725. if (this.parent && this.parent.getWorldMatrix) {
  4726. if (!this._transformedDirection) {
  4727. this._transformedDirection = BABYLON.Vector3.Zero();
  4728. }
  4729. if (!this._transformedPosition) {
  4730. this._transformedPosition = BABYLON.Vector3.Zero();
  4731. }
  4732. var parentWorldMatrix = this.parent.getWorldMatrix();
  4733. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  4734. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  4735. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  4736. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  4737. } else {
  4738. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  4739. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4740. }
  4741. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  4742. };
  4743. SpotLight.prototype._getWorldMatrix = function () {
  4744. if (!this._worldMatrix) {
  4745. this._worldMatrix = BABYLON.Matrix.Identity();
  4746. }
  4747. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4748. return this._worldMatrix;
  4749. };
  4750. return SpotLight;
  4751. })(BABYLON.Light);
  4752. BABYLON.SpotLight = SpotLight;
  4753. })(BABYLON || (BABYLON = {}));
  4754. var __extends = this.__extends || function (d, b) {
  4755. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4756. function __() { this.constructor = d; }
  4757. __.prototype = b.prototype;
  4758. d.prototype = new __();
  4759. };
  4760. var BABYLON;
  4761. (function (BABYLON) {
  4762. var DirectionalLight = (function (_super) {
  4763. __extends(DirectionalLight, _super);
  4764. function DirectionalLight(name, direction, scene) {
  4765. _super.call(this, name, scene);
  4766. this.direction = direction;
  4767. this.position = direction.scale(-1);
  4768. }
  4769. DirectionalLight.prototype.getAbsolutePosition = function () {
  4770. return this._transformedPosition ? this._transformedPosition : this.position;
  4771. };
  4772. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  4773. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4774. return this.direction;
  4775. };
  4776. DirectionalLight.prototype._computeTransformedPosition = function () {
  4777. if (this.parent && this.parent.getWorldMatrix) {
  4778. if (!this._transformedPosition) {
  4779. this._transformedPosition = BABYLON.Vector3.Zero();
  4780. }
  4781. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4782. return true;
  4783. }
  4784. return false;
  4785. };
  4786. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  4787. if (this.parent && this.parent.getWorldMatrix) {
  4788. if (!this._transformedDirection) {
  4789. this._transformedDirection = BABYLON.Vector3.Zero();
  4790. }
  4791. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  4792. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  4793. return;
  4794. }
  4795. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  4796. };
  4797. DirectionalLight.prototype._getWorldMatrix = function () {
  4798. if (!this._worldMatrix) {
  4799. this._worldMatrix = BABYLON.Matrix.Identity();
  4800. }
  4801. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4802. return this._worldMatrix;
  4803. };
  4804. return DirectionalLight;
  4805. })(BABYLON.Light);
  4806. BABYLON.DirectionalLight = DirectionalLight;
  4807. })(BABYLON || (BABYLON = {}));
  4808. var BABYLON;
  4809. (function (BABYLON) {
  4810. var ShadowGenerator = (function () {
  4811. function ShadowGenerator(mapSize, light) {
  4812. var _this = this;
  4813. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4814. this._darkness = 0;
  4815. this._transparencyShadow = false;
  4816. this._viewMatrix = BABYLON.Matrix.Zero();
  4817. this._projectionMatrix = BABYLON.Matrix.Zero();
  4818. this._transformMatrix = BABYLON.Matrix.Zero();
  4819. this._worldViewProjection = BABYLON.Matrix.Zero();
  4820. this._light = light;
  4821. this._scene = light.getScene();
  4822. light._shadowGenerator = this;
  4823. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  4824. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4825. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4826. this._shadowMap.renderParticles = false;
  4827. var renderSubMesh = function (subMesh) {
  4828. var mesh = subMesh.getRenderingMesh();
  4829. var scene = _this._scene;
  4830. var engine = scene.getEngine();
  4831. engine.setState(subMesh.getMaterial().backFaceCulling);
  4832. var batch = mesh._getInstancesRenderList(subMesh._id);
  4833. if (batch.mustReturn) {
  4834. return;
  4835. }
  4836. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  4837. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  4838. engine.enableEffect(_this._effect);
  4839. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  4840. var material = subMesh.getMaterial();
  4841. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  4842. if (material && material.needAlphaTesting()) {
  4843. var alphaTexture = material.getAlphaTestTexture();
  4844. _this._effect.setTexture("diffuseSampler", alphaTexture);
  4845. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  4846. }
  4847. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  4848. if (useBones) {
  4849. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  4850. }
  4851. if (hardwareInstancedRendering) {
  4852. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  4853. } else {
  4854. if (batch.renderSelf[subMesh._id]) {
  4855. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  4856. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  4857. }
  4858. if (batch.visibleInstances[subMesh._id]) {
  4859. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  4860. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  4861. _this._effect.setMatrix("world", instance.getWorldMatrix());
  4862. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  4863. }
  4864. }
  4865. }
  4866. } else {
  4867. _this._shadowMap.resetRefreshCounter();
  4868. }
  4869. };
  4870. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  4871. var index;
  4872. for (index = 0; index < opaqueSubMeshes.length; index++) {
  4873. renderSubMesh(opaqueSubMeshes.data[index]);
  4874. }
  4875. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  4876. renderSubMesh(alphaTestSubMeshes.data[index]);
  4877. }
  4878. if (_this._transparencyShadow) {
  4879. for (index = 0; index < transparentSubMeshes.length; index++) {
  4880. renderSubMesh(transparentSubMeshes.data[index]);
  4881. }
  4882. }
  4883. };
  4884. }
  4885. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  4886. get: function () {
  4887. return ShadowGenerator._FILTER_NONE;
  4888. },
  4889. enumerable: true,
  4890. configurable: true
  4891. });
  4892. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  4893. get: function () {
  4894. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  4895. },
  4896. enumerable: true,
  4897. configurable: true
  4898. });
  4899. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  4900. get: function () {
  4901. return ShadowGenerator._FILTER_POISSONSAMPLING;
  4902. },
  4903. enumerable: true,
  4904. configurable: true
  4905. });
  4906. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  4907. get: function () {
  4908. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4909. },
  4910. set: function (value) {
  4911. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  4912. },
  4913. enumerable: true,
  4914. configurable: true
  4915. });
  4916. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  4917. get: function () {
  4918. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  4919. },
  4920. set: function (value) {
  4921. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  4922. },
  4923. enumerable: true,
  4924. configurable: true
  4925. });
  4926. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  4927. var defines = [];
  4928. if (this.useVarianceShadowMap) {
  4929. defines.push("#define VSM");
  4930. }
  4931. var attribs = [BABYLON.VertexBuffer.PositionKind];
  4932. var mesh = subMesh.getMesh();
  4933. var scene = mesh.getScene();
  4934. var material = subMesh.getMaterial();
  4935. if (material && material.needAlphaTesting()) {
  4936. defines.push("#define ALPHATEST");
  4937. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  4938. attribs.push(BABYLON.VertexBuffer.UVKind);
  4939. defines.push("#define UV1");
  4940. }
  4941. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  4942. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  4943. defines.push("#define UV2");
  4944. }
  4945. }
  4946. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  4947. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  4948. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  4949. defines.push("#define BONES");
  4950. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  4951. }
  4952. if (useInstances) {
  4953. defines.push("#define INSTANCES");
  4954. attribs.push("world0");
  4955. attribs.push("world1");
  4956. attribs.push("world2");
  4957. attribs.push("world3");
  4958. }
  4959. var join = defines.join("\n");
  4960. if (this._cachedDefines != join) {
  4961. this._cachedDefines = join;
  4962. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  4963. }
  4964. return this._effect.isReady();
  4965. };
  4966. ShadowGenerator.prototype.getShadowMap = function () {
  4967. return this._shadowMap;
  4968. };
  4969. ShadowGenerator.prototype.getLight = function () {
  4970. return this._light;
  4971. };
  4972. ShadowGenerator.prototype.getTransformMatrix = function () {
  4973. var lightPosition = this._light.position;
  4974. var lightDirection = this._light.direction;
  4975. if (this._light._computeTransformedPosition()) {
  4976. lightPosition = this._light._transformedPosition;
  4977. }
  4978. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  4979. this._cachedPosition = lightPosition.clone();
  4980. this._cachedDirection = lightDirection.clone();
  4981. var activeCamera = this._scene.activeCamera;
  4982. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  4983. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  4984. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  4985. }
  4986. return this._transformMatrix;
  4987. };
  4988. ShadowGenerator.prototype.getDarkness = function () {
  4989. return this._darkness;
  4990. };
  4991. ShadowGenerator.prototype.setDarkness = function (darkness) {
  4992. if (darkness >= 1.0)
  4993. this._darkness = 1.0;
  4994. else if (darkness <= 0.0)
  4995. this._darkness = 0.0;
  4996. else
  4997. this._darkness = darkness;
  4998. };
  4999. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5000. this._transparencyShadow = hasShadow;
  5001. };
  5002. ShadowGenerator.prototype.dispose = function () {
  5003. this._shadowMap.dispose();
  5004. };
  5005. ShadowGenerator._FILTER_NONE = 0;
  5006. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5007. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5008. return ShadowGenerator;
  5009. })();
  5010. BABYLON.ShadowGenerator = ShadowGenerator;
  5011. })(BABYLON || (BABYLON = {}));
  5012. var __extends = this.__extends || function (d, b) {
  5013. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5014. function __() { this.constructor = d; }
  5015. __.prototype = b.prototype;
  5016. d.prototype = new __();
  5017. };
  5018. var BABYLON;
  5019. (function (BABYLON) {
  5020. var HemisphericLight = (function (_super) {
  5021. __extends(HemisphericLight, _super);
  5022. function HemisphericLight(name, direction, scene) {
  5023. _super.call(this, name, scene);
  5024. this.direction = direction;
  5025. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5026. }
  5027. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5028. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5029. return this.direction;
  5030. };
  5031. HemisphericLight.prototype.getShadowGenerator = function () {
  5032. return null;
  5033. };
  5034. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5035. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5036. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5037. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5038. };
  5039. HemisphericLight.prototype._getWorldMatrix = function () {
  5040. if (!this._worldMatrix) {
  5041. this._worldMatrix = BABYLON.Matrix.Identity();
  5042. }
  5043. return this._worldMatrix;
  5044. };
  5045. return HemisphericLight;
  5046. })(BABYLON.Light);
  5047. BABYLON.HemisphericLight = HemisphericLight;
  5048. })(BABYLON || (BABYLON = {}));
  5049. var BABYLON;
  5050. (function (BABYLON) {
  5051. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5052. if (boxMin.x > sphereCenter.x + sphereRadius)
  5053. return false;
  5054. if (sphereCenter.x - sphereRadius > boxMax.x)
  5055. return false;
  5056. if (boxMin.y > sphereCenter.y + sphereRadius)
  5057. return false;
  5058. if (sphereCenter.y - sphereRadius > boxMax.y)
  5059. return false;
  5060. if (boxMin.z > sphereCenter.z + sphereRadius)
  5061. return false;
  5062. if (sphereCenter.z - sphereRadius > boxMax.z)
  5063. return false;
  5064. return true;
  5065. };
  5066. var getLowestRoot = function (a, b, c, maxR) {
  5067. var determinant = b * b - 4.0 * a * c;
  5068. var result = { root: 0, found: false };
  5069. if (determinant < 0)
  5070. return result;
  5071. var sqrtD = Math.sqrt(determinant);
  5072. var r1 = (-b - sqrtD) / (2.0 * a);
  5073. var r2 = (-b + sqrtD) / (2.0 * a);
  5074. if (r1 > r2) {
  5075. var temp = r2;
  5076. r2 = r1;
  5077. r1 = temp;
  5078. }
  5079. if (r1 > 0 && r1 < maxR) {
  5080. result.root = r1;
  5081. result.found = true;
  5082. return result;
  5083. }
  5084. if (r2 > 0 && r2 < maxR) {
  5085. result.root = r2;
  5086. result.found = true;
  5087. return result;
  5088. }
  5089. return result;
  5090. };
  5091. var Collider = (function () {
  5092. function Collider() {
  5093. this.radius = new BABYLON.Vector3(1, 1, 1);
  5094. this.retry = 0;
  5095. this.basePointWorld = BABYLON.Vector3.Zero();
  5096. this.velocityWorld = BABYLON.Vector3.Zero();
  5097. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5098. this._collisionPoint = BABYLON.Vector3.Zero();
  5099. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5100. this._tempVector = BABYLON.Vector3.Zero();
  5101. this._tempVector2 = BABYLON.Vector3.Zero();
  5102. this._tempVector3 = BABYLON.Vector3.Zero();
  5103. this._tempVector4 = BABYLON.Vector3.Zero();
  5104. this._edge = BABYLON.Vector3.Zero();
  5105. this._baseToVertex = BABYLON.Vector3.Zero();
  5106. this._destinationPoint = BABYLON.Vector3.Zero();
  5107. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5108. this._displacementVector = BABYLON.Vector3.Zero();
  5109. }
  5110. Collider.prototype._initialize = function (source, dir, e) {
  5111. this.velocity = dir;
  5112. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5113. this.basePoint = source;
  5114. source.multiplyToRef(this.radius, this.basePointWorld);
  5115. dir.multiplyToRef(this.radius, this.velocityWorld);
  5116. this.velocityWorldLength = this.velocityWorld.length();
  5117. this.epsilon = e;
  5118. this.collisionFound = false;
  5119. };
  5120. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5121. pa.subtractToRef(point, this._tempVector);
  5122. pb.subtractToRef(point, this._tempVector2);
  5123. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5124. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5125. if (d < 0)
  5126. return false;
  5127. pc.subtractToRef(point, this._tempVector3);
  5128. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5129. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5130. if (d < 0)
  5131. return false;
  5132. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  5133. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5134. return d >= 0;
  5135. };
  5136. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  5137. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  5138. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  5139. if (distance > this.velocityWorldLength + max + sphereRadius) {
  5140. return false;
  5141. }
  5142. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  5143. return false;
  5144. return true;
  5145. };
  5146. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  5147. var t0;
  5148. var embeddedInPlane = false;
  5149. if (!subMesh._trianglePlanes) {
  5150. subMesh._trianglePlanes = [];
  5151. }
  5152. if (!subMesh._trianglePlanes[faceIndex]) {
  5153. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  5154. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  5155. }
  5156. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5157. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5158. return;
  5159. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5160. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5161. if (normalDotVelocity == 0) {
  5162. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5163. return;
  5164. embeddedInPlane = true;
  5165. t0 = 0;
  5166. } else {
  5167. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5168. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5169. if (t0 > t1) {
  5170. var temp = t1;
  5171. t1 = t0;
  5172. t0 = temp;
  5173. }
  5174. if (t0 > 1.0 || t1 < 0.0)
  5175. return;
  5176. if (t0 < 0)
  5177. t0 = 0;
  5178. if (t0 > 1.0)
  5179. t0 = 1.0;
  5180. }
  5181. this._collisionPoint.copyFromFloats(0, 0, 0);
  5182. var found = false;
  5183. var t = 1.0;
  5184. if (!embeddedInPlane) {
  5185. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5186. this.velocity.scaleToRef(t0, this._tempVector);
  5187. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5188. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5189. found = true;
  5190. t = t0;
  5191. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5192. }
  5193. }
  5194. if (!found) {
  5195. var velocitySquaredLength = this.velocity.lengthSquared();
  5196. var a = velocitySquaredLength;
  5197. this.basePoint.subtractToRef(p1, this._tempVector);
  5198. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5199. var c = this._tempVector.lengthSquared() - 1.0;
  5200. var lowestRoot = getLowestRoot(a, b, c, t);
  5201. if (lowestRoot.found) {
  5202. t = lowestRoot.root;
  5203. found = true;
  5204. this._collisionPoint.copyFrom(p1);
  5205. }
  5206. this.basePoint.subtractToRef(p2, this._tempVector);
  5207. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5208. c = this._tempVector.lengthSquared() - 1.0;
  5209. lowestRoot = getLowestRoot(a, b, c, t);
  5210. if (lowestRoot.found) {
  5211. t = lowestRoot.root;
  5212. found = true;
  5213. this._collisionPoint.copyFrom(p2);
  5214. }
  5215. this.basePoint.subtractToRef(p3, this._tempVector);
  5216. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5217. c = this._tempVector.lengthSquared() - 1.0;
  5218. lowestRoot = getLowestRoot(a, b, c, t);
  5219. if (lowestRoot.found) {
  5220. t = lowestRoot.root;
  5221. found = true;
  5222. this._collisionPoint.copyFrom(p3);
  5223. }
  5224. p2.subtractToRef(p1, this._edge);
  5225. p1.subtractToRef(this.basePoint, this._baseToVertex);
  5226. var edgeSquaredLength = this._edge.lengthSquared();
  5227. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5228. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5229. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5230. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5231. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5232. lowestRoot = getLowestRoot(a, b, c, t);
  5233. if (lowestRoot.found) {
  5234. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5235. if (f >= 0.0 && f <= 1.0) {
  5236. t = lowestRoot.root;
  5237. found = true;
  5238. this._edge.scaleInPlace(f);
  5239. p1.addToRef(this._edge, this._collisionPoint);
  5240. }
  5241. }
  5242. p3.subtractToRef(p2, this._edge);
  5243. p2.subtractToRef(this.basePoint, this._baseToVertex);
  5244. edgeSquaredLength = this._edge.lengthSquared();
  5245. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5246. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5247. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5248. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5249. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5250. lowestRoot = getLowestRoot(a, b, c, t);
  5251. if (lowestRoot.found) {
  5252. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5253. if (f >= 0.0 && f <= 1.0) {
  5254. t = lowestRoot.root;
  5255. found = true;
  5256. this._edge.scaleInPlace(f);
  5257. p2.addToRef(this._edge, this._collisionPoint);
  5258. }
  5259. }
  5260. p1.subtractToRef(p3, this._edge);
  5261. p3.subtractToRef(this.basePoint, this._baseToVertex);
  5262. edgeSquaredLength = this._edge.lengthSquared();
  5263. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5264. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5265. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5266. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5267. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5268. lowestRoot = getLowestRoot(a, b, c, t);
  5269. if (lowestRoot.found) {
  5270. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5271. if (f >= 0.0 && f <= 1.0) {
  5272. t = lowestRoot.root;
  5273. found = true;
  5274. this._edge.scaleInPlace(f);
  5275. p3.addToRef(this._edge, this._collisionPoint);
  5276. }
  5277. }
  5278. }
  5279. if (found) {
  5280. var distToCollision = t * this.velocity.length();
  5281. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  5282. if (!this.intersectionPoint) {
  5283. this.intersectionPoint = this._collisionPoint.clone();
  5284. } else {
  5285. this.intersectionPoint.copyFrom(this._collisionPoint);
  5286. }
  5287. this.nearestDistance = distToCollision;
  5288. this.collisionFound = true;
  5289. this.collidedMesh = subMesh.getMesh();
  5290. }
  5291. }
  5292. };
  5293. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  5294. for (var i = indexStart; i < indexEnd; i += 3) {
  5295. var p1 = pts[indices[i] - decal];
  5296. var p2 = pts[indices[i + 1] - decal];
  5297. var p3 = pts[indices[i + 2] - decal];
  5298. this._testTriangle(i, subMesh, p3, p2, p1);
  5299. }
  5300. };
  5301. Collider.prototype._getResponse = function (pos, vel) {
  5302. pos.addToRef(vel, this._destinationPoint);
  5303. vel.scaleInPlace((this.nearestDistance / vel.length()));
  5304. this.basePoint.addToRef(vel, pos);
  5305. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  5306. this._slidePlaneNormal.normalize();
  5307. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  5308. pos.addInPlace(this._displacementVector);
  5309. this.intersectionPoint.addInPlace(this._displacementVector);
  5310. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  5311. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  5312. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  5313. };
  5314. return Collider;
  5315. })();
  5316. BABYLON.Collider = Collider;
  5317. })(BABYLON || (BABYLON = {}));
  5318. var __extends = this.__extends || function (d, b) {
  5319. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5320. function __() { this.constructor = d; }
  5321. __.prototype = b.prototype;
  5322. d.prototype = new __();
  5323. };
  5324. var BABYLON;
  5325. (function (BABYLON) {
  5326. var Camera = (function (_super) {
  5327. __extends(Camera, _super);
  5328. function Camera(name, position, scene) {
  5329. _super.call(this, name, scene);
  5330. this.position = position;
  5331. this.upVector = BABYLON.Vector3.Up();
  5332. this.orthoLeft = null;
  5333. this.orthoRight = null;
  5334. this.orthoBottom = null;
  5335. this.orthoTop = null;
  5336. this.fov = 0.8;
  5337. this.minZ = 1.0;
  5338. this.maxZ = 10000.0;
  5339. this.inertia = 0.9;
  5340. this.mode = Camera.PERSPECTIVE_CAMERA;
  5341. this.isIntermediate = false;
  5342. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  5343. this.subCameras = [];
  5344. this.layerMask = 0xFFFFFFFF;
  5345. this._computedViewMatrix = BABYLON.Matrix.Identity();
  5346. this._projectionMatrix = new BABYLON.Matrix();
  5347. this._postProcesses = new Array();
  5348. this._postProcessesTakenIndices = [];
  5349. scene.cameras.push(this);
  5350. if (!scene.activeCamera) {
  5351. scene.activeCamera = this;
  5352. }
  5353. }
  5354. Camera.prototype._initCache = function () {
  5355. _super.prototype._initCache.call(this);
  5356. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5357. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5358. this._cache.mode = undefined;
  5359. this._cache.minZ = undefined;
  5360. this._cache.maxZ = undefined;
  5361. this._cache.fov = undefined;
  5362. this._cache.aspectRatio = undefined;
  5363. this._cache.orthoLeft = undefined;
  5364. this._cache.orthoRight = undefined;
  5365. this._cache.orthoBottom = undefined;
  5366. this._cache.orthoTop = undefined;
  5367. this._cache.renderWidth = undefined;
  5368. this._cache.renderHeight = undefined;
  5369. };
  5370. Camera.prototype._updateCache = function (ignoreParentClass) {
  5371. if (!ignoreParentClass) {
  5372. _super.prototype._updateCache.call(this);
  5373. }
  5374. var engine = this.getEngine();
  5375. this._cache.position.copyFrom(this.position);
  5376. this._cache.upVector.copyFrom(this.upVector);
  5377. this._cache.mode = this.mode;
  5378. this._cache.minZ = this.minZ;
  5379. this._cache.maxZ = this.maxZ;
  5380. this._cache.fov = this.fov;
  5381. this._cache.aspectRatio = engine.getAspectRatio(this);
  5382. this._cache.orthoLeft = this.orthoLeft;
  5383. this._cache.orthoRight = this.orthoRight;
  5384. this._cache.orthoBottom = this.orthoBottom;
  5385. this._cache.orthoTop = this.orthoTop;
  5386. this._cache.renderWidth = engine.getRenderWidth();
  5387. this._cache.renderHeight = engine.getRenderHeight();
  5388. };
  5389. Camera.prototype._updateFromScene = function () {
  5390. this.updateCache();
  5391. this._update();
  5392. };
  5393. Camera.prototype._isSynchronized = function () {
  5394. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  5395. };
  5396. Camera.prototype._isSynchronizedViewMatrix = function () {
  5397. if (!_super.prototype._isSynchronized.call(this))
  5398. return false;
  5399. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  5400. };
  5401. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  5402. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  5403. if (!check) {
  5404. return false;
  5405. }
  5406. var engine = this.getEngine();
  5407. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5408. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  5409. } else {
  5410. 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();
  5411. }
  5412. return check;
  5413. };
  5414. Camera.prototype.attachControl = function (element) {
  5415. };
  5416. Camera.prototype.detachControl = function (element) {
  5417. };
  5418. Camera.prototype._update = function () {
  5419. };
  5420. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  5421. if (typeof insertAt === "undefined") { insertAt = null; }
  5422. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  5423. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  5424. return 0;
  5425. }
  5426. if (insertAt == null || insertAt < 0) {
  5427. this._postProcesses.push(postProcess);
  5428. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  5429. return this._postProcesses.length - 1;
  5430. }
  5431. var add = 0;
  5432. if (this._postProcesses[insertAt]) {
  5433. var start = this._postProcesses.length - 1;
  5434. for (var i = start; i >= insertAt + 1; --i) {
  5435. this._postProcesses[i + 1] = this._postProcesses[i];
  5436. }
  5437. add = 1;
  5438. }
  5439. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5440. if (this._postProcessesTakenIndices[i] < insertAt) {
  5441. continue;
  5442. }
  5443. start = this._postProcessesTakenIndices.length - 1;
  5444. for (var j = start; j >= i; --j) {
  5445. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  5446. }
  5447. this._postProcessesTakenIndices[i] = insertAt;
  5448. break;
  5449. }
  5450. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  5451. this._postProcessesTakenIndices.push(insertAt);
  5452. }
  5453. var result = insertAt + add;
  5454. this._postProcesses[result] = postProcess;
  5455. return result;
  5456. };
  5457. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  5458. if (typeof atIndices === "undefined") { atIndices = null; }
  5459. var result = [];
  5460. if (!atIndices) {
  5461. var length = this._postProcesses.length;
  5462. for (var i = 0; i < length; i++) {
  5463. if (this._postProcesses[i] !== postProcess) {
  5464. continue;
  5465. }
  5466. delete this._postProcesses[i];
  5467. var index = this._postProcessesTakenIndices.indexOf(i);
  5468. this._postProcessesTakenIndices.splice(index, 1);
  5469. }
  5470. } else {
  5471. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  5472. for (i = 0; i < atIndices.length; i++) {
  5473. var foundPostProcess = this._postProcesses[atIndices[i]];
  5474. if (foundPostProcess !== postProcess) {
  5475. result.push(i);
  5476. continue;
  5477. }
  5478. delete this._postProcesses[atIndices[i]];
  5479. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  5480. this._postProcessesTakenIndices.splice(index, 1);
  5481. }
  5482. }
  5483. return result;
  5484. };
  5485. Camera.prototype.getWorldMatrix = function () {
  5486. if (!this._worldMatrix) {
  5487. this._worldMatrix = BABYLON.Matrix.Identity();
  5488. }
  5489. var viewMatrix = this.getViewMatrix();
  5490. viewMatrix.invertToRef(this._worldMatrix);
  5491. return this._worldMatrix;
  5492. };
  5493. Camera.prototype._getViewMatrix = function () {
  5494. return BABYLON.Matrix.Identity();
  5495. };
  5496. Camera.prototype.getViewMatrix = function () {
  5497. this._computedViewMatrix = this._computeViewMatrix();
  5498. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  5499. return this._computedViewMatrix;
  5500. }
  5501. if (!this._worldMatrix) {
  5502. this._worldMatrix = BABYLON.Matrix.Identity();
  5503. }
  5504. this._computedViewMatrix.invertToRef(this._worldMatrix);
  5505. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  5506. this._computedViewMatrix.invert();
  5507. this._currentRenderId = this.getScene().getRenderId();
  5508. return this._computedViewMatrix;
  5509. };
  5510. Camera.prototype._computeViewMatrix = function (force) {
  5511. if (!force && this._isSynchronizedViewMatrix()) {
  5512. return this._computedViewMatrix;
  5513. }
  5514. this._computedViewMatrix = this._getViewMatrix();
  5515. if (!this.parent || !this.parent.getWorldMatrix) {
  5516. this._currentRenderId = this.getScene().getRenderId();
  5517. }
  5518. return this._computedViewMatrix;
  5519. };
  5520. Camera.prototype.getProjectionMatrix = function (force) {
  5521. if (!force && this._isSynchronizedProjectionMatrix()) {
  5522. return this._projectionMatrix;
  5523. }
  5524. var engine = this.getEngine();
  5525. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5526. if (this.minZ <= 0) {
  5527. this.minZ = 0.1;
  5528. }
  5529. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  5530. return this._projectionMatrix;
  5531. }
  5532. var halfWidth = engine.getRenderWidth() / 2.0;
  5533. var halfHeight = engine.getRenderHeight() / 2.0;
  5534. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  5535. return this._projectionMatrix;
  5536. };
  5537. Camera.prototype.dispose = function () {
  5538. var index = this.getScene().cameras.indexOf(this);
  5539. this.getScene().cameras.splice(index, 1);
  5540. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5541. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  5542. }
  5543. };
  5544. Camera.PERSPECTIVE_CAMERA = 0;
  5545. Camera.ORTHOGRAPHIC_CAMERA = 1;
  5546. return Camera;
  5547. })(BABYLON.Node);
  5548. BABYLON.Camera = Camera;
  5549. })(BABYLON || (BABYLON = {}));
  5550. var __extends = this.__extends || function (d, b) {
  5551. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5552. function __() { this.constructor = d; }
  5553. __.prototype = b.prototype;
  5554. d.prototype = new __();
  5555. };
  5556. var BABYLON;
  5557. (function (BABYLON) {
  5558. var TargetCamera = (function (_super) {
  5559. __extends(TargetCamera, _super);
  5560. function TargetCamera(name, position, scene) {
  5561. _super.call(this, name, position, scene);
  5562. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5563. this.cameraRotation = new BABYLON.Vector2(0, 0);
  5564. this.rotation = new BABYLON.Vector3(0, 0, 0);
  5565. this.speed = 2.0;
  5566. this.noRotationConstraint = false;
  5567. this.lockedTarget = null;
  5568. this._currentTarget = BABYLON.Vector3.Zero();
  5569. this._viewMatrix = BABYLON.Matrix.Zero();
  5570. this._camMatrix = BABYLON.Matrix.Zero();
  5571. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  5572. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  5573. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  5574. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  5575. this._lookAtTemp = BABYLON.Matrix.Zero();
  5576. this._tempMatrix = BABYLON.Matrix.Zero();
  5577. }
  5578. TargetCamera.prototype._getLockedTargetPosition = function () {
  5579. if (!this.lockedTarget) {
  5580. return null;
  5581. }
  5582. return this.lockedTarget.position || this.lockedTarget;
  5583. };
  5584. TargetCamera.prototype._initCache = function () {
  5585. _super.prototype._initCache.call(this);
  5586. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5587. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5588. };
  5589. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  5590. if (!ignoreParentClass) {
  5591. _super.prototype._updateCache.call(this);
  5592. }
  5593. var lockedTargetPosition = this._getLockedTargetPosition();
  5594. if (!lockedTargetPosition) {
  5595. this._cache.lockedTarget = null;
  5596. } else {
  5597. if (!this._cache.lockedTarget) {
  5598. this._cache.lockedTarget = lockedTargetPosition.clone();
  5599. } else {
  5600. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  5601. }
  5602. }
  5603. this._cache.rotation.copyFrom(this.rotation);
  5604. };
  5605. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  5606. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  5607. return false;
  5608. }
  5609. var lockedTargetPosition = this._getLockedTargetPosition();
  5610. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  5611. };
  5612. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  5613. return this.speed * ((BABYLON.Tools.GetDeltaTime() / (BABYLON.Tools.GetFps() * 10.0)));
  5614. };
  5615. TargetCamera.prototype.setTarget = function (target) {
  5616. this.upVector.normalize();
  5617. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  5618. this._camMatrix.invert();
  5619. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  5620. var vDir = target.subtract(this.position);
  5621. if (vDir.x >= 0.0) {
  5622. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5623. } else {
  5624. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5625. }
  5626. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5627. if (isNaN(this.rotation.x)) {
  5628. this.rotation.x = 0;
  5629. }
  5630. if (isNaN(this.rotation.y)) {
  5631. this.rotation.y = 0;
  5632. }
  5633. if (isNaN(this.rotation.z)) {
  5634. this.rotation.z = 0;
  5635. }
  5636. };
  5637. TargetCamera.prototype.getTarget = function () {
  5638. return this._currentTarget;
  5639. };
  5640. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5641. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5642. };
  5643. TargetCamera.prototype._updatePosition = function () {
  5644. this.position.addInPlace(this.cameraDirection);
  5645. };
  5646. TargetCamera.prototype._update = function () {
  5647. var needToMove = this._decideIfNeedsToMove();
  5648. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5649. if (needToMove) {
  5650. this._updatePosition();
  5651. }
  5652. if (needToRotate) {
  5653. this.rotation.x += this.cameraRotation.x;
  5654. this.rotation.y += this.cameraRotation.y;
  5655. if (!this.noRotationConstraint) {
  5656. var limit = (Math.PI / 2) * 0.95;
  5657. if (this.rotation.x > limit)
  5658. this.rotation.x = limit;
  5659. if (this.rotation.x < -limit)
  5660. this.rotation.x = -limit;
  5661. }
  5662. }
  5663. if (needToMove) {
  5664. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  5665. this.cameraDirection.x = 0;
  5666. }
  5667. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  5668. this.cameraDirection.y = 0;
  5669. }
  5670. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  5671. this.cameraDirection.z = 0;
  5672. }
  5673. this.cameraDirection.scaleInPlace(this.inertia);
  5674. }
  5675. if (needToRotate) {
  5676. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  5677. this.cameraRotation.x = 0;
  5678. }
  5679. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  5680. this.cameraRotation.y = 0;
  5681. }
  5682. this.cameraRotation.scaleInPlace(this.inertia);
  5683. }
  5684. };
  5685. TargetCamera.prototype._getViewMatrix = function () {
  5686. if (!this.lockedTarget) {
  5687. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  5688. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  5689. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5690. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  5691. this._lookAtTemp.invert();
  5692. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  5693. } else {
  5694. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5695. }
  5696. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  5697. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  5698. } else {
  5699. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  5700. }
  5701. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  5702. return this._viewMatrix;
  5703. };
  5704. return TargetCamera;
  5705. })(BABYLON.Camera);
  5706. BABYLON.TargetCamera = TargetCamera;
  5707. })(BABYLON || (BABYLON = {}));
  5708. var __extends = this.__extends || function (d, b) {
  5709. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5710. function __() { this.constructor = d; }
  5711. __.prototype = b.prototype;
  5712. d.prototype = new __();
  5713. };
  5714. var BABYLON;
  5715. (function (BABYLON) {
  5716. var FollowCamera = (function (_super) {
  5717. __extends(FollowCamera, _super);
  5718. function FollowCamera(name, position, scene) {
  5719. _super.call(this, name, position, scene);
  5720. this.radius = 12;
  5721. this.rotationOffset = 0;
  5722. this.heightOffset = 4;
  5723. this.cameraAcceleration = 0.05;
  5724. this.maxCameraSpeed = 20;
  5725. }
  5726. FollowCamera.prototype.getRadians = function (degrees) {
  5727. return degrees * Math.PI / 180;
  5728. };
  5729. FollowCamera.prototype.follow = function (cameraTarget) {
  5730. if (!cameraTarget)
  5731. return;
  5732. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  5733. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  5734. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  5735. var dx = targetX - this.position.x;
  5736. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  5737. var dz = (targetZ) - this.position.z;
  5738. var vx = dx * this.cameraAcceleration * 2;
  5739. var vy = dy * this.cameraAcceleration;
  5740. var vz = dz * this.cameraAcceleration * 2;
  5741. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  5742. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5743. }
  5744. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  5745. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5746. }
  5747. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  5748. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5749. }
  5750. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  5751. this.setTarget(cameraTarget.position);
  5752. };
  5753. FollowCamera.prototype._update = function () {
  5754. _super.prototype._update.call(this);
  5755. this.follow(this.target);
  5756. };
  5757. return FollowCamera;
  5758. })(BABYLON.TargetCamera);
  5759. BABYLON.FollowCamera = FollowCamera;
  5760. })(BABYLON || (BABYLON = {}));
  5761. var __extends = this.__extends || function (d, b) {
  5762. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5763. function __() { this.constructor = d; }
  5764. __.prototype = b.prototype;
  5765. d.prototype = new __();
  5766. };
  5767. var BABYLON;
  5768. (function (BABYLON) {
  5769. var FreeCamera = (function (_super) {
  5770. __extends(FreeCamera, _super);
  5771. function FreeCamera(name, position, scene) {
  5772. _super.call(this, name, position, scene);
  5773. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  5774. this.keysUp = [38];
  5775. this.keysDown = [40];
  5776. this.keysLeft = [37];
  5777. this.keysRight = [39];
  5778. this.checkCollisions = false;
  5779. this.applyGravity = false;
  5780. this.angularSensibility = 2000.0;
  5781. this._keys = [];
  5782. this._collider = new BABYLON.Collider();
  5783. this._needMoveForGravity = true;
  5784. this._oldPosition = BABYLON.Vector3.Zero();
  5785. this._diffPosition = BABYLON.Vector3.Zero();
  5786. this._newPosition = BABYLON.Vector3.Zero();
  5787. }
  5788. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  5789. var _this = this;
  5790. var previousPosition;
  5791. var engine = this.getEngine();
  5792. if (this._attachedElement) {
  5793. return;
  5794. }
  5795. this._attachedElement = element;
  5796. if (this._onMouseDown === undefined) {
  5797. this._onMouseDown = function (evt) {
  5798. previousPosition = {
  5799. x: evt.clientX,
  5800. y: evt.clientY
  5801. };
  5802. if (!noPreventDefault) {
  5803. evt.preventDefault();
  5804. }
  5805. };
  5806. this._onMouseUp = function (evt) {
  5807. previousPosition = null;
  5808. if (!noPreventDefault) {
  5809. evt.preventDefault();
  5810. }
  5811. };
  5812. this._onMouseOut = function (evt) {
  5813. previousPosition = null;
  5814. _this._keys = [];
  5815. if (!noPreventDefault) {
  5816. evt.preventDefault();
  5817. }
  5818. };
  5819. this._onMouseMove = function (evt) {
  5820. if (!previousPosition && !engine.isPointerLock) {
  5821. return;
  5822. }
  5823. var offsetX;
  5824. var offsetY;
  5825. if (!engine.isPointerLock) {
  5826. offsetX = evt.clientX - previousPosition.x;
  5827. offsetY = evt.clientY - previousPosition.y;
  5828. } else {
  5829. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5830. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5831. }
  5832. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  5833. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  5834. previousPosition = {
  5835. x: evt.clientX,
  5836. y: evt.clientY
  5837. };
  5838. if (!noPreventDefault) {
  5839. evt.preventDefault();
  5840. }
  5841. };
  5842. this._onKeyDown = function (evt) {
  5843. 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) {
  5844. var index = _this._keys.indexOf(evt.keyCode);
  5845. if (index === -1) {
  5846. _this._keys.push(evt.keyCode);
  5847. }
  5848. if (!noPreventDefault) {
  5849. evt.preventDefault();
  5850. }
  5851. }
  5852. };
  5853. this._onKeyUp = function (evt) {
  5854. 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) {
  5855. var index = _this._keys.indexOf(evt.keyCode);
  5856. if (index >= 0) {
  5857. _this._keys.splice(index, 1);
  5858. }
  5859. if (!noPreventDefault) {
  5860. evt.preventDefault();
  5861. }
  5862. }
  5863. };
  5864. this._onLostFocus = function () {
  5865. _this._keys = [];
  5866. };
  5867. this._reset = function () {
  5868. _this._keys = [];
  5869. previousPosition = null;
  5870. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5871. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  5872. };
  5873. }
  5874. element.addEventListener("mousedown", this._onMouseDown, false);
  5875. element.addEventListener("mouseup", this._onMouseUp, false);
  5876. element.addEventListener("mouseout", this._onMouseOut, false);
  5877. element.addEventListener("mousemove", this._onMouseMove, false);
  5878. BABYLON.Tools.RegisterTopRootEvents([
  5879. { name: "keydown", handler: this._onKeyDown },
  5880. { name: "keyup", handler: this._onKeyUp },
  5881. { name: "blur", handler: this._onLostFocus }
  5882. ]);
  5883. };
  5884. FreeCamera.prototype.detachControl = function (element) {
  5885. if (this._attachedElement != element) {
  5886. return;
  5887. }
  5888. element.removeEventListener("mousedown", this._onMouseDown);
  5889. element.removeEventListener("mouseup", this._onMouseUp);
  5890. element.removeEventListener("mouseout", this._onMouseOut);
  5891. element.removeEventListener("mousemove", this._onMouseMove);
  5892. BABYLON.Tools.UnregisterTopRootEvents([
  5893. { name: "keydown", handler: this._onKeyDown },
  5894. { name: "keyup", handler: this._onKeyUp },
  5895. { name: "blur", handler: this._onLostFocus }
  5896. ]);
  5897. this._attachedElement = null;
  5898. if (this._reset) {
  5899. this._reset();
  5900. }
  5901. };
  5902. FreeCamera.prototype._collideWithWorld = function (velocity) {
  5903. var globalPosition;
  5904. if (this.parent) {
  5905. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  5906. } else {
  5907. globalPosition = this.position;
  5908. }
  5909. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  5910. this._collider.radius = this.ellipsoid;
  5911. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  5912. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  5913. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  5914. this.position.addInPlace(this._diffPosition);
  5915. if (this.onCollide) {
  5916. this.onCollide(this._collider.collidedMesh);
  5917. }
  5918. }
  5919. };
  5920. FreeCamera.prototype._checkInputs = function () {
  5921. if (!this._localDirection) {
  5922. this._localDirection = BABYLON.Vector3.Zero();
  5923. this._transformedDirection = BABYLON.Vector3.Zero();
  5924. }
  5925. for (var index = 0; index < this._keys.length; index++) {
  5926. var keyCode = this._keys[index];
  5927. var speed = this._computeLocalCameraSpeed();
  5928. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5929. this._localDirection.copyFromFloats(-speed, 0, 0);
  5930. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5931. this._localDirection.copyFromFloats(0, 0, speed);
  5932. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5933. this._localDirection.copyFromFloats(speed, 0, 0);
  5934. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5935. this._localDirection.copyFromFloats(0, 0, -speed);
  5936. }
  5937. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  5938. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  5939. this.cameraDirection.addInPlace(this._transformedDirection);
  5940. }
  5941. };
  5942. FreeCamera.prototype._decideIfNeedsToMove = function () {
  5943. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5944. };
  5945. FreeCamera.prototype._updatePosition = function () {
  5946. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  5947. this._collideWithWorld(this.cameraDirection);
  5948. if (this.applyGravity) {
  5949. var oldPosition = this.position;
  5950. this._collideWithWorld(this.getScene().gravity);
  5951. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  5952. }
  5953. } else {
  5954. this.position.addInPlace(this.cameraDirection);
  5955. }
  5956. };
  5957. FreeCamera.prototype._update = function () {
  5958. this._checkInputs();
  5959. _super.prototype._update.call(this);
  5960. };
  5961. return FreeCamera;
  5962. })(BABYLON.TargetCamera);
  5963. BABYLON.FreeCamera = FreeCamera;
  5964. })(BABYLON || (BABYLON = {}));
  5965. var __extends = this.__extends || function (d, b) {
  5966. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5967. function __() { this.constructor = d; }
  5968. __.prototype = b.prototype;
  5969. d.prototype = new __();
  5970. };
  5971. var BABYLON;
  5972. (function (BABYLON) {
  5973. var TouchCamera = (function (_super) {
  5974. __extends(TouchCamera, _super);
  5975. function TouchCamera(name, position, scene) {
  5976. _super.call(this, name, position, scene);
  5977. this._offsetX = null;
  5978. this._offsetY = null;
  5979. this._pointerCount = 0;
  5980. this._pointerPressed = [];
  5981. this.angularSensibility = 200000.0;
  5982. this.moveSensibility = 500.0;
  5983. }
  5984. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5985. var _this = this;
  5986. var previousPosition;
  5987. if (this._attachedCanvas) {
  5988. return;
  5989. }
  5990. this._attachedCanvas = canvas;
  5991. if (this._onPointerDown === undefined) {
  5992. this._onPointerDown = function (evt) {
  5993. if (!noPreventDefault) {
  5994. evt.preventDefault();
  5995. }
  5996. _this._pointerPressed.push(evt.pointerId);
  5997. if (_this._pointerPressed.length !== 1) {
  5998. return;
  5999. }
  6000. previousPosition = {
  6001. x: evt.clientX,
  6002. y: evt.clientY
  6003. };
  6004. };
  6005. this._onPointerUp = function (evt) {
  6006. if (!noPreventDefault) {
  6007. evt.preventDefault();
  6008. }
  6009. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6010. if (index === -1) {
  6011. return;
  6012. }
  6013. _this._pointerPressed.splice(index, 1);
  6014. if (index != 0) {
  6015. return;
  6016. }
  6017. previousPosition = null;
  6018. _this._offsetX = null;
  6019. _this._offsetY = null;
  6020. };
  6021. this._onPointerMove = function (evt) {
  6022. if (!noPreventDefault) {
  6023. evt.preventDefault();
  6024. }
  6025. if (!previousPosition) {
  6026. return;
  6027. }
  6028. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6029. if (index != 0) {
  6030. return;
  6031. }
  6032. _this._offsetX = evt.clientX - previousPosition.x;
  6033. _this._offsetY = -(evt.clientY - previousPosition.y);
  6034. };
  6035. this._onLostFocus = function () {
  6036. _this._offsetX = null;
  6037. _this._offsetY = null;
  6038. };
  6039. }
  6040. canvas.addEventListener("pointerdown", this._onPointerDown);
  6041. canvas.addEventListener("pointerup", this._onPointerUp);
  6042. canvas.addEventListener("pointerout", this._onPointerUp);
  6043. canvas.addEventListener("pointermove", this._onPointerMove);
  6044. BABYLON.Tools.RegisterTopRootEvents([
  6045. { name: "blur", handler: this._onLostFocus }
  6046. ]);
  6047. };
  6048. TouchCamera.prototype.detachControl = function (canvas) {
  6049. if (this._attachedCanvas != canvas) {
  6050. return;
  6051. }
  6052. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6053. canvas.removeEventListener("pointerup", this._onPointerUp);
  6054. canvas.removeEventListener("pointerout", this._onPointerUp);
  6055. canvas.removeEventListener("pointermove", this._onPointerMove);
  6056. BABYLON.Tools.UnregisterTopRootEvents([
  6057. { name: "blur", handler: this._onLostFocus }
  6058. ]);
  6059. this._attachedCanvas = null;
  6060. };
  6061. TouchCamera.prototype._checkInputs = function () {
  6062. if (!this._offsetX) {
  6063. return;
  6064. }
  6065. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6066. if (this._pointerPressed.length > 1) {
  6067. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6068. } else {
  6069. var speed = this._computeLocalCameraSpeed();
  6070. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6071. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6072. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6073. }
  6074. };
  6075. return TouchCamera;
  6076. })(BABYLON.FreeCamera);
  6077. BABYLON.TouchCamera = TouchCamera;
  6078. })(BABYLON || (BABYLON = {}));
  6079. var __extends = this.__extends || function (d, b) {
  6080. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  6081. function __() { this.constructor = d; }
  6082. __.prototype = b.prototype;
  6083. d.prototype = new __();
  6084. };
  6085. var BABYLON;
  6086. (function (BABYLON) {
  6087. var DeviceOrientationCamera = (function (_super) {
  6088. __extends(DeviceOrientationCamera, _super);
  6089. function DeviceOrientationCamera(name, position, scene) {
  6090. var _this = this;
  6091. _super.call(this, name, position, scene);
  6092. this._offsetX = null;
  6093. this._offsetY = null;
  6094. this._orientationGamma = 0;
  6095. this._orientationBeta = 0;
  6096. this._initialOrientationGamma = 0;
  6097. this._initialOrientationBeta = 0;
  6098. this.angularSensibility = 10000.0;
  6099. this.moveSensibility = 50.0;
  6100. window.addEventListener("resize", function () {
  6101. _this._initialOrientationGamma = null;
  6102. }, false);
  6103. }
  6104. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6105. var _this = this;
  6106. if (this._attachedCanvas) {
  6107. return;
  6108. }
  6109. this._attachedCanvas = canvas;
  6110. if (!this._orientationChanged) {
  6111. this._orientationChanged = function (evt) {
  6112. if (!_this._initialOrientationGamma) {
  6113. _this._initialOrientationGamma = evt.gamma;
  6114. _this._initialOrientationBeta = evt.beta;
  6115. }
  6116. _this._orientationGamma = evt.gamma;
  6117. _this._orientationBeta = evt.beta;
  6118. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  6119. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  6120. };
  6121. }
  6122. window.addEventListener("deviceorientation", this._orientationChanged);
  6123. };
  6124. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  6125. if (this._attachedCanvas != canvas) {
  6126. return;
  6127. }
  6128. window.removeEventListener("deviceorientation", this._orientationChanged);
  6129. this._attachedCanvas = null;
  6130. this._orientationGamma = 0;
  6131. this._orientationBeta = 0;
  6132. this._initialOrientationGamma = 0;
  6133. this._initialOrientationBeta = 0;
  6134. };
  6135. DeviceOrientationCamera.prototype._checkInputs = function () {
  6136. if (!this._offsetX) {
  6137. return;
  6138. }
  6139. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  6140. var speed = this._computeLocalCameraSpeed();
  6141. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6142. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6143. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6144. };
  6145. return DeviceOrientationCamera;
  6146. })(BABYLON.FreeCamera);
  6147. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  6148. })(BABYLON || (BABYLON = {}));
  6149. var __extends = this.__extends || function (d, b) {
  6150. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  6151. function __() { this.constructor = d; }
  6152. __.prototype = b.prototype;
  6153. d.prototype = new __();
  6154. };
  6155. var BABYLON;
  6156. (function (BABYLON) {
  6157. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6158. var ArcRotateCamera = (function (_super) {
  6159. __extends(ArcRotateCamera, _super);
  6160. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6161. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6162. this.alpha = alpha;
  6163. this.beta = beta;
  6164. this.radius = radius;
  6165. this.target = target;
  6166. this.inertialAlphaOffset = 0;
  6167. this.inertialBetaOffset = 0;
  6168. this.inertialRadiusOffset = 0;
  6169. this.lowerAlphaLimit = null;
  6170. this.upperAlphaLimit = null;
  6171. this.lowerBetaLimit = 0.01;
  6172. this.upperBetaLimit = Math.PI;
  6173. this.lowerRadiusLimit = null;
  6174. this.upperRadiusLimit = null;
  6175. this.angularSensibility = 1000.0;
  6176. this.wheelPrecision = 3.0;
  6177. this.keysUp = [38];
  6178. this.keysDown = [40];
  6179. this.keysLeft = [37];
  6180. this.keysRight = [39];
  6181. this.zoomOnFactor = 1;
  6182. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6183. this._keys = [];
  6184. this._viewMatrix = new BABYLON.Matrix();
  6185. this.checkCollisions = false;
  6186. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6187. this._collider = new BABYLON.Collider();
  6188. this._previousPosition = BABYLON.Vector3.Zero();
  6189. this._collisionVelocity = BABYLON.Vector3.Zero();
  6190. this._newPosition = BABYLON.Vector3.Zero();
  6191. this.pinchPrecision = 20;
  6192. this.getViewMatrix();
  6193. }
  6194. ArcRotateCamera.prototype._getTargetPosition = function () {
  6195. return this.target.position || this.target;
  6196. };
  6197. ArcRotateCamera.prototype._initCache = function () {
  6198. _super.prototype._initCache.call(this);
  6199. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6200. this._cache.alpha = undefined;
  6201. this._cache.beta = undefined;
  6202. this._cache.radius = undefined;
  6203. this._cache.targetScreenOffset = undefined;
  6204. };
  6205. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6206. if (!ignoreParentClass) {
  6207. _super.prototype._updateCache.call(this);
  6208. }
  6209. this._cache.target.copyFrom(this._getTargetPosition());
  6210. this._cache.alpha = this.alpha;
  6211. this._cache.beta = this.beta;
  6212. this._cache.radius = this.radius;
  6213. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  6214. };
  6215. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  6216. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  6217. return false;
  6218. 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);
  6219. };
  6220. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  6221. var _this = this;
  6222. var previousPosition;
  6223. var pointerId;
  6224. var pinchStarted = false;
  6225. var pinchPointX1, pinchPointX2;
  6226. if (this._attachedElement) {
  6227. return;
  6228. }
  6229. this._attachedElement = element;
  6230. var engine = this.getEngine();
  6231. if (this._onPointerDown === undefined) {
  6232. this._onPointerDown = function (evt) {
  6233. if (pointerId) {
  6234. return;
  6235. }
  6236. pointerId = evt.pointerId;
  6237. previousPosition = {
  6238. x: evt.clientX,
  6239. y: evt.clientY
  6240. };
  6241. if (!noPreventDefault) {
  6242. evt.preventDefault();
  6243. }
  6244. };
  6245. this._onPointerUp = function (evt) {
  6246. previousPosition = null;
  6247. pointerId = null;
  6248. if (!noPreventDefault) {
  6249. evt.preventDefault();
  6250. }
  6251. };
  6252. this._onPointerMove = function (evt) {
  6253. if (!previousPosition) {
  6254. return;
  6255. }
  6256. if (pointerId !== evt.pointerId) {
  6257. return;
  6258. }
  6259. if (pinchStarted) {
  6260. return;
  6261. }
  6262. var offsetX = evt.clientX - previousPosition.x;
  6263. var offsetY = evt.clientY - previousPosition.y;
  6264. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6265. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6266. previousPosition = {
  6267. x: evt.clientX,
  6268. y: evt.clientY
  6269. };
  6270. if (!noPreventDefault) {
  6271. evt.preventDefault();
  6272. }
  6273. };
  6274. this._onMouseMove = function (evt) {
  6275. if (!engine.isPointerLock) {
  6276. return;
  6277. }
  6278. if (pinchStarted) {
  6279. return;
  6280. }
  6281. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6282. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6283. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6284. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6285. if (!noPreventDefault) {
  6286. evt.preventDefault();
  6287. }
  6288. };
  6289. this._wheel = function (event) {
  6290. var delta = 0;
  6291. if (event.wheelDelta) {
  6292. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  6293. } else if (event.detail) {
  6294. delta = -event.detail / _this.wheelPrecision;
  6295. }
  6296. if (delta)
  6297. _this.inertialRadiusOffset += delta;
  6298. if (event.preventDefault) {
  6299. if (!noPreventDefault) {
  6300. event.preventDefault();
  6301. }
  6302. }
  6303. };
  6304. this._onKeyDown = function (evt) {
  6305. 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) {
  6306. var index = _this._keys.indexOf(evt.keyCode);
  6307. if (index === -1) {
  6308. _this._keys.push(evt.keyCode);
  6309. }
  6310. if (evt.preventDefault) {
  6311. if (!noPreventDefault) {
  6312. evt.preventDefault();
  6313. }
  6314. }
  6315. }
  6316. };
  6317. this._onKeyUp = function (evt) {
  6318. 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) {
  6319. var index = _this._keys.indexOf(evt.keyCode);
  6320. if (index >= 0) {
  6321. _this._keys.splice(index, 1);
  6322. }
  6323. if (evt.preventDefault) {
  6324. if (!noPreventDefault) {
  6325. evt.preventDefault();
  6326. }
  6327. }
  6328. }
  6329. };
  6330. this._onLostFocus = function () {
  6331. _this._keys = [];
  6332. pointerId = null;
  6333. };
  6334. this._onGestureStart = function (e) {
  6335. if (window.MSGesture === undefined) {
  6336. return;
  6337. }
  6338. if (!_this._MSGestureHandler) {
  6339. _this._MSGestureHandler = new MSGesture();
  6340. _this._MSGestureHandler.target = element;
  6341. }
  6342. _this._MSGestureHandler.addPointer(e.pointerId);
  6343. };
  6344. this._onGesture = function (e) {
  6345. _this.radius *= e.scale;
  6346. if (e.preventDefault) {
  6347. if (!noPreventDefault) {
  6348. e.stopPropagation();
  6349. e.preventDefault();
  6350. }
  6351. }
  6352. };
  6353. this._reset = function () {
  6354. _this._keys = [];
  6355. _this.inertialAlphaOffset = 0;
  6356. _this.inertialBetaOffset = 0;
  6357. _this.inertialRadiusOffset = 0;
  6358. previousPosition = null;
  6359. pointerId = null;
  6360. };
  6361. this._touchStart = function (event) {
  6362. if (event.touches.length == 2) {
  6363. pinchStarted = true;
  6364. _this._pinchStart(event);
  6365. }
  6366. };
  6367. this._touchMove = function (event) {
  6368. if (pinchStarted) {
  6369. _this._pinchMove(event);
  6370. }
  6371. };
  6372. this._touchEnd = function (event) {
  6373. if (pinchStarted) {
  6374. _this._pinchEnd(event);
  6375. }
  6376. };
  6377. this._pinchStart = function (event) {
  6378. pinchPointX1 = event.touches[0].clientX;
  6379. pinchPointX2 = event.touches[1].clientX;
  6380. pinchStarted = true;
  6381. };
  6382. this._pinchMove = function (event) {
  6383. var delta = 0;
  6384. var direction = 1;
  6385. var distanceXOrigine, distanceXNow;
  6386. if (event.touches.length != 2)
  6387. return;
  6388. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  6389. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  6390. if (distanceXNow < distanceXOrigine) {
  6391. direction = -1;
  6392. }
  6393. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  6394. _this.inertialRadiusOffset += delta;
  6395. pinchPointX1 = event.touches[0].clientX;
  6396. pinchPointX2 = event.touches[1].clientX;
  6397. };
  6398. this._pinchEnd = function (event) {
  6399. pinchStarted = false;
  6400. };
  6401. }
  6402. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6403. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  6404. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  6405. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6406. element.addEventListener("mousemove", this._onMouseMove, false);
  6407. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  6408. element.addEventListener("MSGestureChange", this._onGesture, false);
  6409. element.addEventListener('mousewheel', this._wheel, false);
  6410. element.addEventListener('DOMMouseScroll', this._wheel, false);
  6411. element.addEventListener('touchstart', this._touchStart, false);
  6412. element.addEventListener('touchmove', this._touchMove, false);
  6413. element.addEventListener('touchend', this._touchEnd, false);
  6414. BABYLON.Tools.RegisterTopRootEvents([
  6415. { name: "keydown", handler: this._onKeyDown },
  6416. { name: "keyup", handler: this._onKeyUp },
  6417. { name: "blur", handler: this._onLostFocus }
  6418. ]);
  6419. };
  6420. ArcRotateCamera.prototype.detachControl = function (element) {
  6421. if (this._attachedElement != element) {
  6422. return;
  6423. }
  6424. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  6425. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  6426. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  6427. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  6428. element.removeEventListener("mousemove", this._onMouseMove);
  6429. element.removeEventListener("MSPointerDown", this._onGestureStart);
  6430. element.removeEventListener("MSGestureChange", this._onGesture);
  6431. element.removeEventListener('mousewheel', this._wheel);
  6432. element.removeEventListener('DOMMouseScroll', this._wheel);
  6433. element.removeEventListener('touchstart', this._touchStart);
  6434. element.removeEventListener('touchmove', this._touchMove);
  6435. element.removeEventListener('touchend', this._touchEnd);
  6436. BABYLON.Tools.UnregisterTopRootEvents([
  6437. { name: "keydown", handler: this._onKeyDown },
  6438. { name: "keyup", handler: this._onKeyUp },
  6439. { name: "blur", handler: this._onLostFocus }
  6440. ]);
  6441. this._MSGestureHandler = null;
  6442. this._attachedElement = null;
  6443. if (this._reset) {
  6444. this._reset();
  6445. }
  6446. };
  6447. ArcRotateCamera.prototype._update = function () {
  6448. for (var index = 0; index < this._keys.length; index++) {
  6449. var keyCode = this._keys[index];
  6450. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6451. this.inertialAlphaOffset -= 0.01;
  6452. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6453. this.inertialBetaOffset -= 0.01;
  6454. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6455. this.inertialAlphaOffset += 0.01;
  6456. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6457. this.inertialBetaOffset += 0.01;
  6458. }
  6459. }
  6460. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  6461. this.alpha += this.inertialAlphaOffset;
  6462. this.beta += this.inertialBetaOffset;
  6463. this.radius -= this.inertialRadiusOffset;
  6464. this.inertialAlphaOffset *= this.inertia;
  6465. this.inertialBetaOffset *= this.inertia;
  6466. this.inertialRadiusOffset *= this.inertia;
  6467. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  6468. this.inertialAlphaOffset = 0;
  6469. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  6470. this.inertialBetaOffset = 0;
  6471. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  6472. this.inertialRadiusOffset = 0;
  6473. }
  6474. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  6475. this.alpha = this.lowerAlphaLimit;
  6476. }
  6477. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  6478. this.alpha = this.upperAlphaLimit;
  6479. }
  6480. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  6481. this.beta = this.lowerBetaLimit;
  6482. }
  6483. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  6484. this.beta = this.upperBetaLimit;
  6485. }
  6486. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  6487. this.radius = this.lowerRadiusLimit;
  6488. }
  6489. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  6490. this.radius = this.upperRadiusLimit;
  6491. }
  6492. };
  6493. ArcRotateCamera.prototype.setPosition = function (position) {
  6494. var radiusv3 = position.subtract(this._getTargetPosition());
  6495. this.radius = radiusv3.length();
  6496. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  6497. if (radiusv3.z < 0) {
  6498. this.alpha = 2 * Math.PI - this.alpha;
  6499. }
  6500. this.beta = Math.acos(radiusv3.y / this.radius);
  6501. };
  6502. ArcRotateCamera.prototype._getViewMatrix = function () {
  6503. var cosa = Math.cos(this.alpha);
  6504. var sina = Math.sin(this.alpha);
  6505. var cosb = Math.cos(this.beta);
  6506. var sinb = Math.sin(this.beta);
  6507. var target = this._getTargetPosition();
  6508. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  6509. if (this.checkCollisions) {
  6510. this._collider.radius = this.collisionRadius;
  6511. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  6512. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  6513. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  6514. this.position.copyFrom(this._previousPosition);
  6515. this.alpha = this._previousAlpha;
  6516. this.beta = this._previousBeta;
  6517. this.radius = this._previousRadius;
  6518. if (this.onCollide) {
  6519. this.onCollide(this._collider.collidedMesh);
  6520. }
  6521. }
  6522. }
  6523. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  6524. this._previousAlpha = this.alpha;
  6525. this._previousBeta = this.beta;
  6526. this._previousRadius = this.radius;
  6527. this._previousPosition.copyFrom(this.position);
  6528. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  6529. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  6530. return this._viewMatrix;
  6531. };
  6532. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  6533. meshes = meshes || this.getScene().meshes;
  6534. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  6535. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  6536. this.radius = distance * this.zoomOnFactor;
  6537. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  6538. };
  6539. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  6540. var meshesOrMinMaxVector;
  6541. var distance;
  6542. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  6543. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  6544. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  6545. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  6546. } else {
  6547. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  6548. distance = meshesOrMinMaxVectorAndDistance.distance;
  6549. }
  6550. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  6551. this.maxZ = distance * 2;
  6552. };
  6553. return ArcRotateCamera;
  6554. })(BABYLON.Camera);
  6555. BABYLON.ArcRotateCamera = ArcRotateCamera;
  6556. })(BABYLON || (BABYLON = {}));
  6557. var BABYLON;
  6558. (function (BABYLON) {
  6559. var Scene = (function () {
  6560. function Scene(engine) {
  6561. this.autoClear = true;
  6562. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6563. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  6564. this.forceWireframe = false;
  6565. this.forcePointsCloud = false;
  6566. this.forceShowBoundingBoxes = false;
  6567. this.animationsEnabled = true;
  6568. this.cameraToUseForPointers = null;
  6569. this.fogEnabled = true;
  6570. this.fogMode = Scene.FOGMODE_NONE;
  6571. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6572. this.fogDensity = 0.1;
  6573. this.fogStart = 0;
  6574. this.fogEnd = 1000.0;
  6575. this.shadowsEnabled = true;
  6576. this.lightsEnabled = true;
  6577. this.lights = new Array();
  6578. this.cameras = new Array();
  6579. this.activeCameras = new Array();
  6580. this.meshes = new Array();
  6581. this._geometries = new Array();
  6582. this.materials = new Array();
  6583. this.multiMaterials = new Array();
  6584. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  6585. this.texturesEnabled = true;
  6586. this.textures = new Array();
  6587. this.particlesEnabled = true;
  6588. this.particleSystems = new Array();
  6589. this.spriteManagers = new Array();
  6590. this.layers = new Array();
  6591. this.skeletonsEnabled = true;
  6592. this.skeletons = new Array();
  6593. this.lensFlaresEnabled = true;
  6594. this.lensFlareSystems = new Array();
  6595. this.collisionsEnabled = true;
  6596. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  6597. this.postProcessesEnabled = true;
  6598. this.renderTargetsEnabled = true;
  6599. this.customRenderTargets = new Array();
  6600. this.importedMeshesFiles = new Array();
  6601. this._actionManagers = new Array();
  6602. this._meshesForIntersections = new BABYLON.SmartArray(256);
  6603. this.proceduralTexturesEnabled = true;
  6604. this._proceduralTextures = new Array();
  6605. this.soundTracks = new Array();
  6606. this._totalVertices = 0;
  6607. this._activeVertices = 0;
  6608. this._activeParticles = 0;
  6609. this._lastFrameDuration = 0;
  6610. this._evaluateActiveMeshesDuration = 0;
  6611. this._renderTargetsDuration = 0;
  6612. this._particlesDuration = 0;
  6613. this._renderDuration = 0;
  6614. this._spritesDuration = 0;
  6615. this._animationRatio = 0;
  6616. this._renderId = 0;
  6617. this._executeWhenReadyTimeoutId = -1;
  6618. this._toBeDisposed = new BABYLON.SmartArray(256);
  6619. this._onReadyCallbacks = new Array();
  6620. this._pendingData = [];
  6621. this._onBeforeRenderCallbacks = new Array();
  6622. this._onAfterRenderCallbacks = new Array();
  6623. this._activeMeshes = new BABYLON.SmartArray(256);
  6624. this._processedMaterials = new BABYLON.SmartArray(256);
  6625. this._renderTargets = new BABYLON.SmartArray(256);
  6626. this._activeParticleSystems = new BABYLON.SmartArray(256);
  6627. this._activeSkeletons = new BABYLON.SmartArray(32);
  6628. this._activeBones = 0;
  6629. this._activeAnimatables = new Array();
  6630. this._transformMatrix = BABYLON.Matrix.Zero();
  6631. this._scaledPosition = BABYLON.Vector3.Zero();
  6632. this._scaledVelocity = BABYLON.Vector3.Zero();
  6633. this._engine = engine;
  6634. engine.scenes.push(this);
  6635. this._renderingManager = new BABYLON.RenderingManager(this);
  6636. this.postProcessManager = new BABYLON.PostProcessManager(this);
  6637. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  6638. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  6639. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  6640. this.attachControl();
  6641. this._debugLayer = new BABYLON.DebugLayer(this);
  6642. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  6643. }
  6644. Object.defineProperty(Scene.prototype, "debugLayer", {
  6645. get: function () {
  6646. return this._debugLayer;
  6647. },
  6648. enumerable: true,
  6649. configurable: true
  6650. });
  6651. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  6652. get: function () {
  6653. return this._meshUnderPointer;
  6654. },
  6655. enumerable: true,
  6656. configurable: true
  6657. });
  6658. Object.defineProperty(Scene.prototype, "pointerX", {
  6659. get: function () {
  6660. return this._pointerX;
  6661. },
  6662. enumerable: true,
  6663. configurable: true
  6664. });
  6665. Object.defineProperty(Scene.prototype, "pointerY", {
  6666. get: function () {
  6667. return this._pointerY;
  6668. },
  6669. enumerable: true,
  6670. configurable: true
  6671. });
  6672. Scene.prototype.getCachedMaterial = function () {
  6673. return this._cachedMaterial;
  6674. };
  6675. Scene.prototype.getBoundingBoxRenderer = function () {
  6676. return this._boundingBoxRenderer;
  6677. };
  6678. Scene.prototype.getOutlineRenderer = function () {
  6679. return this._outlineRenderer;
  6680. };
  6681. Scene.prototype.getEngine = function () {
  6682. return this._engine;
  6683. };
  6684. Scene.prototype.getTotalVertices = function () {
  6685. return this._totalVertices;
  6686. };
  6687. Scene.prototype.getActiveVertices = function () {
  6688. return this._activeVertices;
  6689. };
  6690. Scene.prototype.getActiveParticles = function () {
  6691. return this._activeParticles;
  6692. };
  6693. Scene.prototype.getActiveBones = function () {
  6694. return this._activeBones;
  6695. };
  6696. Scene.prototype.getLastFrameDuration = function () {
  6697. return this._lastFrameDuration;
  6698. };
  6699. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  6700. return this._evaluateActiveMeshesDuration;
  6701. };
  6702. Scene.prototype.getActiveMeshes = function () {
  6703. return this._activeMeshes;
  6704. };
  6705. Scene.prototype.getRenderTargetsDuration = function () {
  6706. return this._renderTargetsDuration;
  6707. };
  6708. Scene.prototype.getRenderDuration = function () {
  6709. return this._renderDuration;
  6710. };
  6711. Scene.prototype.getParticlesDuration = function () {
  6712. return this._particlesDuration;
  6713. };
  6714. Scene.prototype.getSpritesDuration = function () {
  6715. return this._spritesDuration;
  6716. };
  6717. Scene.prototype.getAnimationRatio = function () {
  6718. return this._animationRatio;
  6719. };
  6720. Scene.prototype.getRenderId = function () {
  6721. return this._renderId;
  6722. };
  6723. Scene.prototype._updatePointerPosition = function (evt) {
  6724. var canvasRect = this._engine.getRenderingCanvasClientRect();
  6725. this._pointerX = evt.clientX - canvasRect.left;
  6726. this._pointerY = evt.clientY - canvasRect.top;
  6727. if (this.cameraToUseForPointers) {
  6728. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  6729. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  6730. }
  6731. };
  6732. Scene.prototype.attachControl = function () {
  6733. var _this = this;
  6734. this._onPointerMove = function (evt) {
  6735. var canvas = _this._engine.getRenderingCanvas();
  6736. _this._updatePointerPosition(evt);
  6737. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  6738. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  6739. }, false, _this.cameraToUseForPointers);
  6740. if (pickResult.hit) {
  6741. _this._meshUnderPointer = pickResult.pickedMesh;
  6742. _this.setPointerOverMesh(pickResult.pickedMesh);
  6743. canvas.style.cursor = "pointer";
  6744. } else {
  6745. _this.setPointerOverMesh(null);
  6746. canvas.style.cursor = "";
  6747. _this._meshUnderPointer = null;
  6748. }
  6749. };
  6750. this._onPointerDown = function (evt) {
  6751. var predicate = null;
  6752. if (!_this.onPointerDown) {
  6753. predicate = function (mesh) {
  6754. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  6755. };
  6756. }
  6757. _this._updatePointerPosition(evt);
  6758. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  6759. if (pickResult.hit) {
  6760. if (pickResult.pickedMesh.actionManager) {
  6761. switch (evt.button) {
  6762. case 0:
  6763. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  6764. break;
  6765. case 1:
  6766. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  6767. break;
  6768. case 2:
  6769. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  6770. break;
  6771. }
  6772. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  6773. }
  6774. }
  6775. if (_this.onPointerDown) {
  6776. _this.onPointerDown(evt, pickResult);
  6777. }
  6778. };
  6779. this._onKeyDown = function (evt) {
  6780. if (_this.actionManager) {
  6781. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6782. }
  6783. };
  6784. this._onKeyUp = function (evt) {
  6785. if (_this.actionManager) {
  6786. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6787. }
  6788. };
  6789. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6790. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6791. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6792. window.addEventListener("keydown", this._onKeyDown, false);
  6793. window.addEventListener("keyup", this._onKeyUp, false);
  6794. };
  6795. Scene.prototype.detachControl = function () {
  6796. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6797. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  6798. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  6799. window.removeEventListener("keydown", this._onKeyDown);
  6800. window.removeEventListener("keyup", this._onKeyUp);
  6801. };
  6802. Scene.prototype.isReady = function () {
  6803. if (this._pendingData.length > 0) {
  6804. return false;
  6805. }
  6806. for (var index = 0; index < this._geometries.length; index++) {
  6807. var geometry = this._geometries[index];
  6808. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  6809. return false;
  6810. }
  6811. }
  6812. for (index = 0; index < this.meshes.length; index++) {
  6813. var mesh = this.meshes[index];
  6814. if (!mesh.isReady()) {
  6815. return false;
  6816. }
  6817. var mat = mesh.material;
  6818. if (mat) {
  6819. if (!mat.isReady(mesh)) {
  6820. return false;
  6821. }
  6822. }
  6823. }
  6824. return true;
  6825. };
  6826. Scene.prototype.resetCachedMaterial = function () {
  6827. this._cachedMaterial = null;
  6828. };
  6829. Scene.prototype.registerBeforeRender = function (func) {
  6830. this._onBeforeRenderCallbacks.push(func);
  6831. };
  6832. Scene.prototype.unregisterBeforeRender = function (func) {
  6833. var index = this._onBeforeRenderCallbacks.indexOf(func);
  6834. if (index > -1) {
  6835. this._onBeforeRenderCallbacks.splice(index, 1);
  6836. }
  6837. };
  6838. Scene.prototype.registerAfterRender = function (func) {
  6839. this._onAfterRenderCallbacks.push(func);
  6840. };
  6841. Scene.prototype.unregisterAfterRender = function (func) {
  6842. var index = this._onAfterRenderCallbacks.indexOf(func);
  6843. if (index > -1) {
  6844. this._onAfterRenderCallbacks.splice(index, 1);
  6845. }
  6846. };
  6847. Scene.prototype._addPendingData = function (data) {
  6848. this._pendingData.push(data);
  6849. };
  6850. Scene.prototype._removePendingData = function (data) {
  6851. var index = this._pendingData.indexOf(data);
  6852. if (index !== -1) {
  6853. this._pendingData.splice(index, 1);
  6854. }
  6855. };
  6856. Scene.prototype.getWaitingItemsCount = function () {
  6857. return this._pendingData.length;
  6858. };
  6859. Scene.prototype.executeWhenReady = function (func) {
  6860. var _this = this;
  6861. this._onReadyCallbacks.push(func);
  6862. if (this._executeWhenReadyTimeoutId !== -1) {
  6863. return;
  6864. }
  6865. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6866. _this._checkIsReady();
  6867. }, 150);
  6868. };
  6869. Scene.prototype._checkIsReady = function () {
  6870. var _this = this;
  6871. if (this.isReady()) {
  6872. this._onReadyCallbacks.forEach(function (func) {
  6873. func();
  6874. });
  6875. this._onReadyCallbacks = [];
  6876. this._executeWhenReadyTimeoutId = -1;
  6877. return;
  6878. }
  6879. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6880. _this._checkIsReady();
  6881. }, 150);
  6882. };
  6883. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  6884. if (speedRatio === undefined) {
  6885. speedRatio = 1.0;
  6886. }
  6887. this.stopAnimation(target);
  6888. if (!animatable) {
  6889. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  6890. }
  6891. if (target.animations) {
  6892. animatable.appendAnimations(target, target.animations);
  6893. }
  6894. if (target.getAnimatables) {
  6895. var animatables = target.getAnimatables();
  6896. for (var index = 0; index < animatables.length; index++) {
  6897. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  6898. }
  6899. }
  6900. return animatable;
  6901. };
  6902. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  6903. if (speedRatio === undefined) {
  6904. speedRatio = 1.0;
  6905. }
  6906. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  6907. return animatable;
  6908. };
  6909. Scene.prototype.getAnimatableByTarget = function (target) {
  6910. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6911. if (this._activeAnimatables[index].target === target) {
  6912. return this._activeAnimatables[index];
  6913. }
  6914. }
  6915. return null;
  6916. };
  6917. Scene.prototype.stopAnimation = function (target) {
  6918. var animatable = this.getAnimatableByTarget(target);
  6919. if (animatable) {
  6920. animatable.stop();
  6921. }
  6922. };
  6923. Scene.prototype._animate = function () {
  6924. if (!this.animationsEnabled) {
  6925. return;
  6926. }
  6927. if (!this._animationStartDate) {
  6928. this._animationStartDate = BABYLON.Tools.Now;
  6929. }
  6930. var now = BABYLON.Tools.Now;
  6931. var delay = now - this._animationStartDate;
  6932. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6933. if (!this._activeAnimatables[index]._animate(delay)) {
  6934. this._activeAnimatables.splice(index, 1);
  6935. index--;
  6936. }
  6937. }
  6938. };
  6939. Scene.prototype.getViewMatrix = function () {
  6940. return this._viewMatrix;
  6941. };
  6942. Scene.prototype.getProjectionMatrix = function () {
  6943. return this._projectionMatrix;
  6944. };
  6945. Scene.prototype.getTransformMatrix = function () {
  6946. return this._transformMatrix;
  6947. };
  6948. Scene.prototype.setTransformMatrix = function (view, projection) {
  6949. this._viewMatrix = view;
  6950. this._projectionMatrix = projection;
  6951. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6952. };
  6953. Scene.prototype.setActiveCameraByID = function (id) {
  6954. var camera = this.getCameraByID(id);
  6955. if (camera) {
  6956. this.activeCamera = camera;
  6957. return camera;
  6958. }
  6959. return null;
  6960. };
  6961. Scene.prototype.setActiveCameraByName = function (name) {
  6962. var camera = this.getCameraByName(name);
  6963. if (camera) {
  6964. this.activeCamera = camera;
  6965. return camera;
  6966. }
  6967. return null;
  6968. };
  6969. Scene.prototype.getMaterialByID = function (id) {
  6970. for (var index = 0; index < this.materials.length; index++) {
  6971. if (this.materials[index].id === id) {
  6972. return this.materials[index];
  6973. }
  6974. }
  6975. return null;
  6976. };
  6977. Scene.prototype.getMaterialByName = function (name) {
  6978. for (var index = 0; index < this.materials.length; index++) {
  6979. if (this.materials[index].name === name) {
  6980. return this.materials[index];
  6981. }
  6982. }
  6983. return null;
  6984. };
  6985. Scene.prototype.getCameraByID = function (id) {
  6986. for (var index = 0; index < this.cameras.length; index++) {
  6987. if (this.cameras[index].id === id) {
  6988. return this.cameras[index];
  6989. }
  6990. }
  6991. return null;
  6992. };
  6993. Scene.prototype.getCameraByName = function (name) {
  6994. for (var index = 0; index < this.cameras.length; index++) {
  6995. if (this.cameras[index].name === name) {
  6996. return this.cameras[index];
  6997. }
  6998. }
  6999. return null;
  7000. };
  7001. Scene.prototype.getLightByName = function (name) {
  7002. for (var index = 0; index < this.lights.length; index++) {
  7003. if (this.lights[index].name === name) {
  7004. return this.lights[index];
  7005. }
  7006. }
  7007. return null;
  7008. };
  7009. Scene.prototype.getLightByID = function (id) {
  7010. for (var index = 0; index < this.lights.length; index++) {
  7011. if (this.lights[index].id === id) {
  7012. return this.lights[index];
  7013. }
  7014. }
  7015. return null;
  7016. };
  7017. Scene.prototype.getGeometryByID = function (id) {
  7018. for (var index = 0; index < this._geometries.length; index++) {
  7019. if (this._geometries[index].id === id) {
  7020. return this._geometries[index];
  7021. }
  7022. }
  7023. return null;
  7024. };
  7025. Scene.prototype.pushGeometry = function (geometry, force) {
  7026. if (!force && this.getGeometryByID(geometry.id)) {
  7027. return false;
  7028. }
  7029. this._geometries.push(geometry);
  7030. return true;
  7031. };
  7032. Scene.prototype.getGeometries = function () {
  7033. return this._geometries;
  7034. };
  7035. Scene.prototype.getMeshByID = function (id) {
  7036. for (var index = 0; index < this.meshes.length; index++) {
  7037. if (this.meshes[index].id === id) {
  7038. return this.meshes[index];
  7039. }
  7040. }
  7041. return null;
  7042. };
  7043. Scene.prototype.getLastMeshByID = function (id) {
  7044. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7045. if (this.meshes[index].id === id) {
  7046. return this.meshes[index];
  7047. }
  7048. }
  7049. return null;
  7050. };
  7051. Scene.prototype.getLastEntryByID = function (id) {
  7052. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7053. if (this.meshes[index].id === id) {
  7054. return this.meshes[index];
  7055. }
  7056. }
  7057. for (index = this.cameras.length - 1; index >= 0; index--) {
  7058. if (this.cameras[index].id === id) {
  7059. return this.cameras[index];
  7060. }
  7061. }
  7062. for (index = this.lights.length - 1; index >= 0; index--) {
  7063. if (this.lights[index].id === id) {
  7064. return this.lights[index];
  7065. }
  7066. }
  7067. return null;
  7068. };
  7069. Scene.prototype.getMeshByName = function (name) {
  7070. for (var index = 0; index < this.meshes.length; index++) {
  7071. if (this.meshes[index].name === name) {
  7072. return this.meshes[index];
  7073. }
  7074. }
  7075. return null;
  7076. };
  7077. Scene.prototype.getLastSkeletonByID = function (id) {
  7078. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  7079. if (this.skeletons[index].id === id) {
  7080. return this.skeletons[index];
  7081. }
  7082. }
  7083. return null;
  7084. };
  7085. Scene.prototype.getSkeletonById = function (id) {
  7086. for (var index = 0; index < this.skeletons.length; index++) {
  7087. if (this.skeletons[index].id === id) {
  7088. return this.skeletons[index];
  7089. }
  7090. }
  7091. return null;
  7092. };
  7093. Scene.prototype.getSkeletonByName = function (name) {
  7094. for (var index = 0; index < this.skeletons.length; index++) {
  7095. if (this.skeletons[index].name === name) {
  7096. return this.skeletons[index];
  7097. }
  7098. }
  7099. return null;
  7100. };
  7101. Scene.prototype.isActiveMesh = function (mesh) {
  7102. return (this._activeMeshes.indexOf(mesh) !== -1);
  7103. };
  7104. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  7105. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  7106. var material = subMesh.getMaterial();
  7107. if (mesh.showSubMeshesBoundingBox) {
  7108. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  7109. }
  7110. if (material) {
  7111. if (material.getRenderTargetTextures) {
  7112. if (this._processedMaterials.indexOf(material) === -1) {
  7113. this._processedMaterials.push(material);
  7114. this._renderTargets.concat(material.getRenderTargetTextures());
  7115. }
  7116. }
  7117. this._activeVertices += subMesh.indexCount;
  7118. this._renderingManager.dispatch(subMesh);
  7119. }
  7120. }
  7121. };
  7122. Scene.prototype._evaluateActiveMeshes = function () {
  7123. this._activeMeshes.reset();
  7124. this._renderingManager.reset();
  7125. this._processedMaterials.reset();
  7126. this._activeParticleSystems.reset();
  7127. this._activeSkeletons.reset();
  7128. this._boundingBoxRenderer.reset();
  7129. if (!this._frustumPlanes) {
  7130. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  7131. } else {
  7132. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  7133. }
  7134. var meshes;
  7135. var len;
  7136. if (this._selectionOctree) {
  7137. var selection = this._selectionOctree.select(this._frustumPlanes);
  7138. meshes = selection.data;
  7139. len = selection.length;
  7140. } else {
  7141. len = this.meshes.length;
  7142. meshes = this.meshes;
  7143. }
  7144. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  7145. var mesh = meshes[meshIndex];
  7146. if (mesh.isBlocked) {
  7147. continue;
  7148. }
  7149. this._totalVertices += mesh.getTotalVertices();
  7150. if (!mesh.isReady()) {
  7151. continue;
  7152. }
  7153. mesh.computeWorldMatrix();
  7154. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  7155. this._meshesForIntersections.pushNoDuplicate(mesh);
  7156. }
  7157. var meshLOD = mesh.getLOD(this.activeCamera);
  7158. if (!meshLOD) {
  7159. continue;
  7160. }
  7161. mesh._preActivate();
  7162. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  7163. this._activeMeshes.push(mesh);
  7164. mesh._activate(this._renderId);
  7165. this._activeMesh(meshLOD);
  7166. }
  7167. }
  7168. var beforeParticlesDate = BABYLON.Tools.Now;
  7169. if (this.particlesEnabled) {
  7170. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  7171. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  7172. var particleSystem = this.particleSystems[particleIndex];
  7173. if (!particleSystem.isStarted()) {
  7174. continue;
  7175. }
  7176. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  7177. this._activeParticleSystems.push(particleSystem);
  7178. particleSystem.animate();
  7179. }
  7180. }
  7181. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  7182. }
  7183. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  7184. };
  7185. Scene.prototype._activeMesh = function (mesh) {
  7186. if (mesh.skeleton && this.skeletonsEnabled) {
  7187. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  7188. }
  7189. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  7190. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  7191. }
  7192. if (mesh && mesh.subMeshes) {
  7193. var len;
  7194. var subMeshes;
  7195. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  7196. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  7197. len = intersections.length;
  7198. subMeshes = intersections.data;
  7199. } else {
  7200. subMeshes = mesh.subMeshes;
  7201. len = subMeshes.length;
  7202. }
  7203. for (var subIndex = 0; subIndex < len; subIndex++) {
  7204. var subMesh = subMeshes[subIndex];
  7205. this._evaluateSubMesh(subMesh, mesh);
  7206. }
  7207. }
  7208. };
  7209. Scene.prototype.updateTransformMatrix = function (force) {
  7210. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  7211. };
  7212. Scene.prototype._renderForCamera = function (camera) {
  7213. var engine = this._engine;
  7214. this.activeCamera = camera;
  7215. if (!this.activeCamera)
  7216. throw new Error("Active camera not set");
  7217. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7218. engine.setViewport(this.activeCamera.viewport);
  7219. this._renderId++;
  7220. this.updateTransformMatrix();
  7221. if (this.beforeCameraRender) {
  7222. this.beforeCameraRender(this.activeCamera);
  7223. }
  7224. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  7225. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  7226. this._evaluateActiveMeshes();
  7227. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  7228. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  7229. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  7230. var skeleton = this._activeSkeletons.data[skeletonIndex];
  7231. skeleton.prepare();
  7232. this._activeBones += skeleton.bones.length;
  7233. }
  7234. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7235. if (this.renderTargetsEnabled) {
  7236. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7237. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  7238. var renderTarget = this._renderTargets.data[renderIndex];
  7239. if (renderTarget._shouldRender()) {
  7240. this._renderId++;
  7241. renderTarget.render();
  7242. }
  7243. }
  7244. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7245. this._renderId++;
  7246. }
  7247. if (this._renderTargets.length > 0) {
  7248. engine.restoreDefaultFramebuffer();
  7249. }
  7250. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7251. this.postProcessManager._prepareFrame();
  7252. var beforeRenderDate = BABYLON.Tools.Now;
  7253. if (this.layers.length) {
  7254. engine.setDepthBuffer(false);
  7255. var layerIndex;
  7256. var layer;
  7257. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7258. layer = this.layers[layerIndex];
  7259. if (layer.isBackground) {
  7260. layer.render();
  7261. }
  7262. }
  7263. engine.setDepthBuffer(true);
  7264. }
  7265. BABYLON.Tools.StartPerformanceCounter("Main render");
  7266. this._renderingManager.render(null, null, true, true);
  7267. BABYLON.Tools.EndPerformanceCounter("Main render");
  7268. this._boundingBoxRenderer.render();
  7269. if (this.lensFlaresEnabled) {
  7270. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7271. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  7272. this.lensFlareSystems[lensFlareSystemIndex].render();
  7273. }
  7274. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7275. }
  7276. if (this.layers.length) {
  7277. engine.setDepthBuffer(false);
  7278. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7279. layer = this.layers[layerIndex];
  7280. if (!layer.isBackground) {
  7281. layer.render();
  7282. }
  7283. }
  7284. engine.setDepthBuffer(true);
  7285. }
  7286. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  7287. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  7288. this.activeCamera._updateFromScene();
  7289. this._renderTargets.reset();
  7290. if (this.afterCameraRender) {
  7291. this.afterCameraRender(this.activeCamera);
  7292. }
  7293. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7294. };
  7295. Scene.prototype._processSubCameras = function (camera) {
  7296. if (camera.subCameras.length === 0) {
  7297. this._renderForCamera(camera);
  7298. return;
  7299. }
  7300. for (var index = 0; index < camera.subCameras.length; index++) {
  7301. this._renderForCamera(camera.subCameras[index]);
  7302. }
  7303. this.activeCamera = camera;
  7304. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  7305. this.activeCamera._updateFromScene();
  7306. };
  7307. Scene.prototype._checkIntersections = function () {
  7308. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  7309. var sourceMesh = this._meshesForIntersections.data[index];
  7310. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  7311. var action = sourceMesh.actionManager.actions[actionIndex];
  7312. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7313. var otherMesh = action.getTriggerParameter();
  7314. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  7315. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7316. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  7317. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  7318. sourceMesh._intersectionsInProgress.push(otherMesh);
  7319. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7320. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  7321. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7322. if (indexOfOther > -1) {
  7323. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  7324. }
  7325. }
  7326. }
  7327. }
  7328. }
  7329. };
  7330. Scene.prototype.render = function () {
  7331. var startDate = BABYLON.Tools.Now;
  7332. this._particlesDuration = 0;
  7333. this._spritesDuration = 0;
  7334. this._activeParticles = 0;
  7335. this._renderDuration = 0;
  7336. this._renderTargetsDuration = 0;
  7337. this._evaluateActiveMeshesDuration = 0;
  7338. this._totalVertices = 0;
  7339. this._activeVertices = 0;
  7340. this._activeBones = 0;
  7341. this.getEngine().resetDrawCalls();
  7342. this._meshesForIntersections.reset();
  7343. this.resetCachedMaterial();
  7344. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  7345. if (this.actionManager) {
  7346. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  7347. }
  7348. if (this.beforeRender) {
  7349. this.beforeRender();
  7350. }
  7351. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  7352. this._onBeforeRenderCallbacks[callbackIndex]();
  7353. }
  7354. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  7355. this._animationRatio = deltaTime * (60.0 / 1000.0);
  7356. this._animate();
  7357. if (this._physicsEngine) {
  7358. BABYLON.Tools.StartPerformanceCounter("Physics");
  7359. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  7360. BABYLON.Tools.EndPerformanceCounter("Physics");
  7361. }
  7362. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7363. var engine = this.getEngine();
  7364. if (this.renderTargetsEnabled) {
  7365. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7366. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  7367. var renderTarget = this.customRenderTargets[customIndex];
  7368. if (renderTarget._shouldRender()) {
  7369. this._renderId++;
  7370. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  7371. if (!this.activeCamera)
  7372. throw new Error("Active camera not set");
  7373. engine.setViewport(this.activeCamera.viewport);
  7374. this.updateTransformMatrix();
  7375. renderTarget.render();
  7376. }
  7377. }
  7378. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7379. this._renderId++;
  7380. }
  7381. if (this.customRenderTargets.length > 0) {
  7382. engine.restoreDefaultFramebuffer();
  7383. }
  7384. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7385. if (this.proceduralTexturesEnabled) {
  7386. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7387. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  7388. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  7389. if (proceduralTexture._shouldRender()) {
  7390. proceduralTexture.render();
  7391. }
  7392. }
  7393. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7394. }
  7395. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  7396. if (this.shadowsEnabled) {
  7397. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  7398. var light = this.lights[lightIndex];
  7399. var shadowGenerator = light.getShadowGenerator();
  7400. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  7401. this._renderTargets.push(shadowGenerator.getShadowMap());
  7402. }
  7403. }
  7404. }
  7405. this.postProcessRenderPipelineManager.update();
  7406. if (this.activeCameras.length > 0) {
  7407. var currentRenderId = this._renderId;
  7408. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  7409. this._renderId = currentRenderId;
  7410. this._processSubCameras(this.activeCameras[cameraIndex]);
  7411. }
  7412. } else {
  7413. if (!this.activeCamera) {
  7414. throw new Error("No camera defined");
  7415. }
  7416. this._processSubCameras(this.activeCamera);
  7417. }
  7418. this._checkIntersections();
  7419. this._updateAudioParameters();
  7420. if (this.afterRender) {
  7421. this.afterRender();
  7422. }
  7423. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  7424. this._onAfterRenderCallbacks[callbackIndex]();
  7425. }
  7426. for (var index = 0; index < this._toBeDisposed.length; index++) {
  7427. this._toBeDisposed.data[index].dispose();
  7428. this._toBeDisposed[index] = null;
  7429. }
  7430. this._toBeDisposed.reset();
  7431. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  7432. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  7433. };
  7434. Scene.prototype._updateAudioParameters = function () {
  7435. var listeningCamera;
  7436. var audioEngine = this._engine.getAudioEngine();
  7437. if (this.activeCameras.length > 0) {
  7438. listeningCamera = this.activeCameras[0];
  7439. } else {
  7440. listeningCamera = this.activeCamera;
  7441. }
  7442. if (listeningCamera && audioEngine.canUseWebAudio) {
  7443. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  7444. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  7445. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  7446. cameraDirection.normalize();
  7447. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  7448. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  7449. var sound = this.mainSoundTrack.soundCollection[i];
  7450. if (sound.useBabylonJSAttenuation) {
  7451. sound.updateDistanceFromListener();
  7452. }
  7453. }
  7454. for (var i = 0; i < this.soundTracks.length; i++) {
  7455. for (var j = 0; i < this.soundTracks[i].soundCollection.length; j++) {
  7456. var sound = this.soundTracks[i].soundCollection[j];
  7457. if (sound.useBabylonJSAttenuation) {
  7458. sound.updateDistanceFromListener();
  7459. }
  7460. }
  7461. }
  7462. }
  7463. };
  7464. Scene.prototype.dispose = function () {
  7465. this.beforeRender = null;
  7466. this.afterRender = null;
  7467. this.skeletons = [];
  7468. this._boundingBoxRenderer.dispose();
  7469. this.debugLayer.hide();
  7470. if (this.onDispose) {
  7471. this.onDispose();
  7472. }
  7473. this._onBeforeRenderCallbacks = [];
  7474. this._onAfterRenderCallbacks = [];
  7475. this.detachControl();
  7476. var canvas = this._engine.getRenderingCanvas();
  7477. var index;
  7478. for (index = 0; index < this.cameras.length; index++) {
  7479. this.cameras[index].detachControl(canvas);
  7480. }
  7481. while (this.lights.length) {
  7482. this.lights[0].dispose();
  7483. }
  7484. while (this.meshes.length) {
  7485. this.meshes[0].dispose(true);
  7486. }
  7487. while (this.cameras.length) {
  7488. this.cameras[0].dispose();
  7489. }
  7490. while (this.materials.length) {
  7491. this.materials[0].dispose();
  7492. }
  7493. while (this.particleSystems.length) {
  7494. this.particleSystems[0].dispose();
  7495. }
  7496. while (this.spriteManagers.length) {
  7497. this.spriteManagers[0].dispose();
  7498. }
  7499. while (this.layers.length) {
  7500. this.layers[0].dispose();
  7501. }
  7502. while (this.textures.length) {
  7503. this.textures[0].dispose();
  7504. }
  7505. this.postProcessManager.dispose();
  7506. if (this._physicsEngine) {
  7507. this.disablePhysicsEngine();
  7508. }
  7509. index = this._engine.scenes.indexOf(this);
  7510. if (index > -1) {
  7511. this._engine.scenes.splice(index, 1);
  7512. }
  7513. this._engine.wipeCaches();
  7514. };
  7515. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7516. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7517. position.divideToRef(collider.radius, this._scaledPosition);
  7518. velocity.divideToRef(collider.radius, this._scaledVelocity);
  7519. collider.retry = 0;
  7520. collider.initialVelocity = this._scaledVelocity;
  7521. collider.initialPosition = this._scaledPosition;
  7522. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  7523. finalPosition.multiplyInPlace(collider.radius);
  7524. };
  7525. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7526. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7527. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  7528. if (collider.retry >= maximumRetry) {
  7529. finalPosition.copyFrom(position);
  7530. return;
  7531. }
  7532. collider._initialize(position, velocity, closeDistance);
  7533. for (var index = 0; index < this.meshes.length; index++) {
  7534. var mesh = this.meshes[index];
  7535. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  7536. mesh._checkCollision(collider);
  7537. }
  7538. }
  7539. if (!collider.collisionFound) {
  7540. position.addToRef(velocity, finalPosition);
  7541. return;
  7542. }
  7543. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  7544. collider._getResponse(position, velocity);
  7545. }
  7546. if (velocity.length() <= closeDistance) {
  7547. finalPosition.copyFrom(position);
  7548. return;
  7549. }
  7550. collider.retry++;
  7551. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  7552. };
  7553. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  7554. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7555. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7556. if (!this._selectionOctree) {
  7557. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  7558. }
  7559. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7560. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7561. for (var index = 0; index < this.meshes.length; index++) {
  7562. var mesh = this.meshes[index];
  7563. mesh.computeWorldMatrix(true);
  7564. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  7565. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  7566. BABYLON.Tools.CheckExtends(minBox, min, max);
  7567. BABYLON.Tools.CheckExtends(maxBox, min, max);
  7568. }
  7569. this._selectionOctree.update(min, max, this.meshes);
  7570. return this._selectionOctree;
  7571. };
  7572. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  7573. var engine = this._engine;
  7574. if (!camera) {
  7575. if (!this.activeCamera)
  7576. throw new Error("Active camera not set");
  7577. camera = this.activeCamera;
  7578. }
  7579. var cameraViewport = camera.viewport;
  7580. var viewport = cameraViewport.toGlobal(engine);
  7581. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  7582. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  7583. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  7584. };
  7585. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  7586. var pickingInfo = null;
  7587. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  7588. var mesh = this.meshes[meshIndex];
  7589. if (predicate) {
  7590. if (!predicate(mesh)) {
  7591. continue;
  7592. }
  7593. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  7594. continue;
  7595. }
  7596. var world = mesh.getWorldMatrix();
  7597. var ray = rayFunction(world);
  7598. var result = mesh.intersects(ray, fastCheck);
  7599. if (!result || !result.hit)
  7600. continue;
  7601. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  7602. continue;
  7603. pickingInfo = result;
  7604. if (fastCheck) {
  7605. break;
  7606. }
  7607. }
  7608. return pickingInfo || new BABYLON.PickingInfo();
  7609. };
  7610. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  7611. var _this = this;
  7612. return this._internalPick(function (world) {
  7613. return _this.createPickingRay(x, y, world, camera);
  7614. }, predicate, fastCheck);
  7615. };
  7616. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  7617. var _this = this;
  7618. return this._internalPick(function (world) {
  7619. if (!_this._pickWithRayInverseMatrix) {
  7620. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  7621. }
  7622. world.invertToRef(_this._pickWithRayInverseMatrix);
  7623. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  7624. }, predicate, fastCheck);
  7625. };
  7626. Scene.prototype.setPointerOverMesh = function (mesh) {
  7627. if (this._pointerOverMesh === mesh) {
  7628. return;
  7629. }
  7630. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  7631. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  7632. }
  7633. this._pointerOverMesh = mesh;
  7634. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  7635. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  7636. }
  7637. };
  7638. Scene.prototype.getPointerOverMesh = function () {
  7639. return this._pointerOverMesh;
  7640. };
  7641. Scene.prototype.getPhysicsEngine = function () {
  7642. return this._physicsEngine;
  7643. };
  7644. Scene.prototype.enablePhysics = function (gravity, plugin) {
  7645. if (this._physicsEngine) {
  7646. return true;
  7647. }
  7648. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  7649. if (!this._physicsEngine.isSupported()) {
  7650. this._physicsEngine = null;
  7651. return false;
  7652. }
  7653. this._physicsEngine._initialize(gravity);
  7654. return true;
  7655. };
  7656. Scene.prototype.disablePhysicsEngine = function () {
  7657. if (!this._physicsEngine) {
  7658. return;
  7659. }
  7660. this._physicsEngine.dispose();
  7661. this._physicsEngine = undefined;
  7662. };
  7663. Scene.prototype.isPhysicsEnabled = function () {
  7664. return this._physicsEngine !== undefined;
  7665. };
  7666. Scene.prototype.setGravity = function (gravity) {
  7667. if (!this._physicsEngine) {
  7668. return;
  7669. }
  7670. this._physicsEngine._setGravity(gravity);
  7671. };
  7672. Scene.prototype.createCompoundImpostor = function (parts, options) {
  7673. if (parts.parts) {
  7674. options = parts;
  7675. parts = parts.parts;
  7676. }
  7677. if (!this._physicsEngine) {
  7678. return null;
  7679. }
  7680. for (var index = 0; index < parts.length; index++) {
  7681. var mesh = parts[index].mesh;
  7682. mesh._physicImpostor = parts[index].impostor;
  7683. mesh._physicsMass = options.mass / parts.length;
  7684. mesh._physicsFriction = options.friction;
  7685. mesh._physicRestitution = options.restitution;
  7686. }
  7687. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  7688. };
  7689. Scene.prototype.deleteCompoundImpostor = function (compound) {
  7690. for (var index = 0; index < compound.parts.length; index++) {
  7691. var mesh = compound.parts[index].mesh;
  7692. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7693. this._physicsEngine._unregisterMesh(mesh);
  7694. }
  7695. };
  7696. Scene.prototype._getByTags = function (list, tagsQuery) {
  7697. if (tagsQuery === undefined) {
  7698. return list;
  7699. }
  7700. var listByTags = [];
  7701. for (var i in list) {
  7702. var item = list[i];
  7703. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  7704. listByTags.push(item);
  7705. }
  7706. }
  7707. return listByTags;
  7708. };
  7709. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  7710. return this._getByTags(this.meshes, tagsQuery);
  7711. };
  7712. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  7713. return this._getByTags(this.cameras, tagsQuery);
  7714. };
  7715. Scene.prototype.getLightsByTags = function (tagsQuery) {
  7716. return this._getByTags(this.lights, tagsQuery);
  7717. };
  7718. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  7719. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  7720. };
  7721. Scene.FOGMODE_NONE = 0;
  7722. Scene.FOGMODE_EXP = 1;
  7723. Scene.FOGMODE_EXP2 = 2;
  7724. Scene.FOGMODE_LINEAR = 3;
  7725. Scene.MinDeltaTime = 1.0;
  7726. Scene.MaxDeltaTime = 1000.0;
  7727. return Scene;
  7728. })();
  7729. BABYLON.Scene = Scene;
  7730. })(BABYLON || (BABYLON = {}));
  7731. var BABYLON;
  7732. (function (BABYLON) {
  7733. var VertexBuffer = (function () {
  7734. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  7735. if (engine instanceof BABYLON.Mesh) {
  7736. this._engine = engine.getScene().getEngine();
  7737. } else {
  7738. this._engine = engine;
  7739. }
  7740. this._updatable = updatable;
  7741. this._data = data;
  7742. if (!postponeInternalCreation) {
  7743. this.create();
  7744. }
  7745. this._kind = kind;
  7746. if (stride) {
  7747. this._strideSize = stride;
  7748. return;
  7749. }
  7750. switch (kind) {
  7751. case VertexBuffer.PositionKind:
  7752. this._strideSize = 3;
  7753. break;
  7754. case VertexBuffer.NormalKind:
  7755. this._strideSize = 3;
  7756. break;
  7757. case VertexBuffer.UVKind:
  7758. this._strideSize = 2;
  7759. break;
  7760. case VertexBuffer.UV2Kind:
  7761. this._strideSize = 2;
  7762. break;
  7763. case VertexBuffer.ColorKind:
  7764. this._strideSize = 4;
  7765. break;
  7766. case VertexBuffer.MatricesIndicesKind:
  7767. this._strideSize = 4;
  7768. break;
  7769. case VertexBuffer.MatricesWeightsKind:
  7770. this._strideSize = 4;
  7771. break;
  7772. }
  7773. }
  7774. VertexBuffer.prototype.isUpdatable = function () {
  7775. return this._updatable;
  7776. };
  7777. VertexBuffer.prototype.getData = function () {
  7778. return this._data;
  7779. };
  7780. VertexBuffer.prototype.getBuffer = function () {
  7781. return this._buffer;
  7782. };
  7783. VertexBuffer.prototype.getStrideSize = function () {
  7784. return this._strideSize;
  7785. };
  7786. VertexBuffer.prototype.create = function (data) {
  7787. if (!data && this._buffer) {
  7788. return;
  7789. }
  7790. data = data || this._data;
  7791. if (!this._buffer) {
  7792. if (this._updatable) {
  7793. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  7794. } else {
  7795. this._buffer = this._engine.createVertexBuffer(data);
  7796. }
  7797. }
  7798. if (this._updatable) {
  7799. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7800. this._data = data;
  7801. }
  7802. };
  7803. VertexBuffer.prototype.update = function (data) {
  7804. this.create(data);
  7805. };
  7806. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  7807. if (!this._buffer) {
  7808. return;
  7809. }
  7810. if (this._updatable) {
  7811. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  7812. this._data = null;
  7813. }
  7814. };
  7815. VertexBuffer.prototype.dispose = function () {
  7816. if (!this._buffer) {
  7817. return;
  7818. }
  7819. if (this._engine._releaseBuffer(this._buffer)) {
  7820. this._buffer = null;
  7821. }
  7822. };
  7823. Object.defineProperty(VertexBuffer, "PositionKind", {
  7824. get: function () {
  7825. return VertexBuffer._PositionKind;
  7826. },
  7827. enumerable: true,
  7828. configurable: true
  7829. });
  7830. Object.defineProperty(VertexBuffer, "NormalKind", {
  7831. get: function () {
  7832. return VertexBuffer._NormalKind;
  7833. },
  7834. enumerable: true,
  7835. configurable: true
  7836. });
  7837. Object.defineProperty(VertexBuffer, "UVKind", {
  7838. get: function () {
  7839. return VertexBuffer._UVKind;
  7840. },
  7841. enumerable: true,
  7842. configurable: true
  7843. });
  7844. Object.defineProperty(VertexBuffer, "UV2Kind", {
  7845. get: function () {
  7846. return VertexBuffer._UV2Kind;
  7847. },
  7848. enumerable: true,
  7849. configurable: true
  7850. });
  7851. Object.defineProperty(VertexBuffer, "ColorKind", {
  7852. get: function () {
  7853. return VertexBuffer._ColorKind;
  7854. },
  7855. enumerable: true,
  7856. configurable: true
  7857. });
  7858. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  7859. get: function () {
  7860. return VertexBuffer._MatricesIndicesKind;
  7861. },
  7862. enumerable: true,
  7863. configurable: true
  7864. });
  7865. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  7866. get: function () {
  7867. return VertexBuffer._MatricesWeightsKind;
  7868. },
  7869. enumerable: true,
  7870. configurable: true
  7871. });
  7872. VertexBuffer._PositionKind = "position";
  7873. VertexBuffer._NormalKind = "normal";
  7874. VertexBuffer._UVKind = "uv";
  7875. VertexBuffer._UV2Kind = "uv2";
  7876. VertexBuffer._ColorKind = "color";
  7877. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  7878. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  7879. return VertexBuffer;
  7880. })();
  7881. BABYLON.VertexBuffer = VertexBuffer;
  7882. })(BABYLON || (BABYLON = {}));
  7883. var __extends = this.__extends || function (d, b) {
  7884. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7885. function __() { this.constructor = d; }
  7886. __.prototype = b.prototype;
  7887. d.prototype = new __();
  7888. };
  7889. var BABYLON;
  7890. (function (BABYLON) {
  7891. var AbstractMesh = (function (_super) {
  7892. __extends(AbstractMesh, _super);
  7893. function AbstractMesh(name, scene) {
  7894. _super.call(this, name, scene);
  7895. this.position = new BABYLON.Vector3(0, 0, 0);
  7896. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7897. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7898. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7899. this.visibility = 1.0;
  7900. this.alphaIndex = Number.MAX_VALUE;
  7901. this.infiniteDistance = false;
  7902. this.isVisible = true;
  7903. this.isPickable = true;
  7904. this.showBoundingBox = false;
  7905. this.showSubMeshesBoundingBox = false;
  7906. this.onDispose = null;
  7907. this.checkCollisions = false;
  7908. this.isBlocker = false;
  7909. this.renderingGroupId = 0;
  7910. this.receiveShadows = false;
  7911. this.renderOutline = false;
  7912. this.outlineColor = BABYLON.Color3.Red();
  7913. this.outlineWidth = 0.02;
  7914. this.renderOverlay = false;
  7915. this.overlayColor = BABYLON.Color3.Red();
  7916. this.overlayAlpha = 0.5;
  7917. this.hasVertexAlpha = false;
  7918. this.useVertexColors = true;
  7919. this.applyFog = true;
  7920. this.useOctreeForRenderingSelection = true;
  7921. this.useOctreeForPicking = true;
  7922. this.useOctreeForCollisions = true;
  7923. this.layerMask = 0xFFFFFFFF;
  7924. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7925. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7926. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7927. this._collider = new BABYLON.Collider();
  7928. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7929. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7930. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7931. this._localScaling = BABYLON.Matrix.Zero();
  7932. this._localRotation = BABYLON.Matrix.Zero();
  7933. this._localTranslation = BABYLON.Matrix.Zero();
  7934. this._localBillboard = BABYLON.Matrix.Zero();
  7935. this._localPivotScaling = BABYLON.Matrix.Zero();
  7936. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7937. this._localWorld = BABYLON.Matrix.Zero();
  7938. this._worldMatrix = BABYLON.Matrix.Zero();
  7939. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7940. this._absolutePosition = BABYLON.Vector3.Zero();
  7941. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7942. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7943. this._isDirty = false;
  7944. this._pivotMatrix = BABYLON.Matrix.Identity();
  7945. this._isDisposed = false;
  7946. this._renderId = 0;
  7947. this._intersectionsInProgress = new Array();
  7948. this._onAfterWorldMatrixUpdate = new Array();
  7949. scene.meshes.push(this);
  7950. }
  7951. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7952. get: function () {
  7953. return AbstractMesh._BILLBOARDMODE_NONE;
  7954. },
  7955. enumerable: true,
  7956. configurable: true
  7957. });
  7958. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7959. get: function () {
  7960. return AbstractMesh._BILLBOARDMODE_X;
  7961. },
  7962. enumerable: true,
  7963. configurable: true
  7964. });
  7965. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7966. get: function () {
  7967. return AbstractMesh._BILLBOARDMODE_Y;
  7968. },
  7969. enumerable: true,
  7970. configurable: true
  7971. });
  7972. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7973. get: function () {
  7974. return AbstractMesh._BILLBOARDMODE_Z;
  7975. },
  7976. enumerable: true,
  7977. configurable: true
  7978. });
  7979. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7980. get: function () {
  7981. return AbstractMesh._BILLBOARDMODE_ALL;
  7982. },
  7983. enumerable: true,
  7984. configurable: true
  7985. });
  7986. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7987. get: function () {
  7988. return false;
  7989. },
  7990. enumerable: true,
  7991. configurable: true
  7992. });
  7993. AbstractMesh.prototype.getLOD = function (camera) {
  7994. return this;
  7995. };
  7996. AbstractMesh.prototype.getTotalVertices = function () {
  7997. return 0;
  7998. };
  7999. AbstractMesh.prototype.getIndices = function () {
  8000. return null;
  8001. };
  8002. AbstractMesh.prototype.getVerticesData = function (kind) {
  8003. return null;
  8004. };
  8005. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8006. return false;
  8007. };
  8008. AbstractMesh.prototype.getBoundingInfo = function () {
  8009. if (this._masterMesh) {
  8010. return this._masterMesh.getBoundingInfo();
  8011. }
  8012. if (!this._boundingInfo) {
  8013. this._updateBoundingInfo();
  8014. }
  8015. return this._boundingInfo;
  8016. };
  8017. AbstractMesh.prototype._preActivate = function () {
  8018. };
  8019. AbstractMesh.prototype._activate = function (renderId) {
  8020. this._renderId = renderId;
  8021. };
  8022. AbstractMesh.prototype.getWorldMatrix = function () {
  8023. if (this._masterMesh) {
  8024. return this._masterMesh.getWorldMatrix();
  8025. }
  8026. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8027. this.computeWorldMatrix();
  8028. }
  8029. return this._worldMatrix;
  8030. };
  8031. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8032. get: function () {
  8033. return this._worldMatrix;
  8034. },
  8035. enumerable: true,
  8036. configurable: true
  8037. });
  8038. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8039. get: function () {
  8040. return this._absolutePosition;
  8041. },
  8042. enumerable: true,
  8043. configurable: true
  8044. });
  8045. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8046. if (!this.rotationQuaternion) {
  8047. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8048. this.rotation = BABYLON.Vector3.Zero();
  8049. }
  8050. if (!space || space == 0 /* LOCAL */) {
  8051. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8052. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8053. } else {
  8054. if (this.parent) {
  8055. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8056. invertParentWorldMatrix.invert();
  8057. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8058. }
  8059. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8060. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8061. }
  8062. };
  8063. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8064. var displacementVector = axis.scale(distance);
  8065. if (!space || space == 0 /* LOCAL */) {
  8066. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8067. this.setPositionWithLocalVector(tempV3);
  8068. } else {
  8069. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8070. }
  8071. };
  8072. AbstractMesh.prototype.getAbsolutePosition = function () {
  8073. this.computeWorldMatrix();
  8074. return this._absolutePosition;
  8075. };
  8076. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8077. if (!absolutePosition) {
  8078. return;
  8079. }
  8080. var absolutePositionX;
  8081. var absolutePositionY;
  8082. var absolutePositionZ;
  8083. if (absolutePosition.x === undefined) {
  8084. if (arguments.length < 3) {
  8085. return;
  8086. }
  8087. absolutePositionX = arguments[0];
  8088. absolutePositionY = arguments[1];
  8089. absolutePositionZ = arguments[2];
  8090. } else {
  8091. absolutePositionX = absolutePosition.x;
  8092. absolutePositionY = absolutePosition.y;
  8093. absolutePositionZ = absolutePosition.z;
  8094. }
  8095. if (this.parent) {
  8096. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8097. invertParentWorldMatrix.invert();
  8098. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8099. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8100. } else {
  8101. this.position.x = absolutePositionX;
  8102. this.position.y = absolutePositionY;
  8103. this.position.z = absolutePositionZ;
  8104. }
  8105. };
  8106. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8107. this._pivotMatrix = matrix;
  8108. this._cache.pivotMatrixUpdated = true;
  8109. };
  8110. AbstractMesh.prototype.getPivotMatrix = function () {
  8111. return this._pivotMatrix;
  8112. };
  8113. AbstractMesh.prototype._isSynchronized = function () {
  8114. if (this._isDirty) {
  8115. return false;
  8116. }
  8117. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8118. return false;
  8119. if (this._cache.pivotMatrixUpdated) {
  8120. return false;
  8121. }
  8122. if (this.infiniteDistance) {
  8123. return false;
  8124. }
  8125. if (!this._cache.position.equals(this.position))
  8126. return false;
  8127. if (this.rotationQuaternion) {
  8128. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8129. return false;
  8130. } else {
  8131. if (!this._cache.rotation.equals(this.rotation))
  8132. return false;
  8133. }
  8134. if (!this._cache.scaling.equals(this.scaling))
  8135. return false;
  8136. return true;
  8137. };
  8138. AbstractMesh.prototype._initCache = function () {
  8139. _super.prototype._initCache.call(this);
  8140. this._cache.localMatrixUpdated = false;
  8141. this._cache.position = BABYLON.Vector3.Zero();
  8142. this._cache.scaling = BABYLON.Vector3.Zero();
  8143. this._cache.rotation = BABYLON.Vector3.Zero();
  8144. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8145. };
  8146. AbstractMesh.prototype.markAsDirty = function (property) {
  8147. if (property === "rotation") {
  8148. this.rotationQuaternion = null;
  8149. }
  8150. this._currentRenderId = Number.MAX_VALUE;
  8151. this._isDirty = true;
  8152. };
  8153. AbstractMesh.prototype._updateBoundingInfo = function () {
  8154. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8155. this._boundingInfo._update(this.worldMatrixFromCache);
  8156. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8157. };
  8158. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8159. if (!this.subMeshes) {
  8160. return;
  8161. }
  8162. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8163. var subMesh = this.subMeshes[subIndex];
  8164. subMesh.updateBoundingInfo(matrix);
  8165. }
  8166. };
  8167. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8168. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  8169. return this._worldMatrix;
  8170. }
  8171. this._cache.position.copyFrom(this.position);
  8172. this._cache.scaling.copyFrom(this.scaling);
  8173. this._cache.pivotMatrixUpdated = false;
  8174. this._currentRenderId = this.getScene().getRenderId();
  8175. this._isDirty = false;
  8176. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  8177. if (this.rotationQuaternion) {
  8178. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8179. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8180. } else {
  8181. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8182. this._cache.rotation.copyFrom(this.rotation);
  8183. }
  8184. if (this.infiniteDistance && !this.parent) {
  8185. var camera = this.getScene().activeCamera;
  8186. var cameraWorldMatrix = camera.getWorldMatrix();
  8187. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8188. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8189. } else {
  8190. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8191. }
  8192. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8193. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8194. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8195. var localPosition = this.position.clone();
  8196. var zero = this.getScene().activeCamera.position.clone();
  8197. if (this.parent && this.parent.position) {
  8198. localPosition.addInPlace(this.parent.position);
  8199. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8200. }
  8201. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  8202. zero = this.getScene().activeCamera.position;
  8203. } else {
  8204. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  8205. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8206. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  8207. zero.y = localPosition.y + 0.001;
  8208. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  8209. zero.z = localPosition.z + 0.001;
  8210. }
  8211. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8212. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8213. this._localBillboard.invert();
  8214. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8215. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8216. }
  8217. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8218. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  8219. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8220. } else {
  8221. this._worldMatrix.copyFrom(this._localWorld);
  8222. }
  8223. this._updateBoundingInfo();
  8224. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8225. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8226. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8227. }
  8228. return this._worldMatrix;
  8229. };
  8230. /**
  8231. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8232. * @param func: callback function to add
  8233. */
  8234. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8235. this._onAfterWorldMatrixUpdate.push(func);
  8236. };
  8237. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8238. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8239. if (index > -1) {
  8240. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8241. }
  8242. };
  8243. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8244. this.computeWorldMatrix();
  8245. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8246. };
  8247. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8248. this.computeWorldMatrix();
  8249. var invLocalWorldMatrix = this._localWorld.clone();
  8250. invLocalWorldMatrix.invert();
  8251. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8252. };
  8253. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8254. this.computeWorldMatrix();
  8255. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8256. };
  8257. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8258. yawCor = yawCor || 0;
  8259. pitchCor = pitchCor || 0;
  8260. rollCor = rollCor || 0;
  8261. var dv = targetPoint.subtract(this.position);
  8262. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8263. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8264. var pitch = Math.atan2(dv.y, len);
  8265. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8266. };
  8267. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8268. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  8269. return false;
  8270. }
  8271. return true;
  8272. };
  8273. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8274. if (!camera) {
  8275. camera = this.getScene().activeCamera;
  8276. }
  8277. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8278. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8279. return false;
  8280. }
  8281. return true;
  8282. };
  8283. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8284. if (!this._boundingInfo || !mesh._boundingInfo) {
  8285. return false;
  8286. }
  8287. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8288. };
  8289. AbstractMesh.prototype.intersectsPoint = function (point) {
  8290. if (!this._boundingInfo) {
  8291. return false;
  8292. }
  8293. return this._boundingInfo.intersectsPoint(point);
  8294. };
  8295. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8296. var physicsEngine = this.getScene().getPhysicsEngine();
  8297. if (!physicsEngine) {
  8298. return;
  8299. }
  8300. if (impostor.impostor) {
  8301. options = impostor;
  8302. impostor = impostor.impostor;
  8303. }
  8304. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8305. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8306. physicsEngine._unregisterMesh(this);
  8307. return;
  8308. }
  8309. options.mass = options.mass || 0;
  8310. options.friction = options.friction || 0.2;
  8311. options.restitution = options.restitution || 0.2;
  8312. this._physicImpostor = impostor;
  8313. this._physicsMass = options.mass;
  8314. this._physicsFriction = options.friction;
  8315. this._physicRestitution = options.restitution;
  8316. return physicsEngine._registerMesh(this, impostor, options);
  8317. };
  8318. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8319. if (!this._physicImpostor) {
  8320. return BABYLON.PhysicsEngine.NoImpostor;
  8321. }
  8322. return this._physicImpostor;
  8323. };
  8324. AbstractMesh.prototype.getPhysicsMass = function () {
  8325. if (!this._physicsMass) {
  8326. return 0;
  8327. }
  8328. return this._physicsMass;
  8329. };
  8330. AbstractMesh.prototype.getPhysicsFriction = function () {
  8331. if (!this._physicsFriction) {
  8332. return 0;
  8333. }
  8334. return this._physicsFriction;
  8335. };
  8336. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8337. if (!this._physicRestitution) {
  8338. return 0;
  8339. }
  8340. return this._physicRestitution;
  8341. };
  8342. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8343. if (!camera) {
  8344. camera = this.getScene().activeCamera;
  8345. }
  8346. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8347. };
  8348. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8349. if (!camera) {
  8350. camera = this.getScene().activeCamera;
  8351. }
  8352. return this.absolutePosition.subtract(camera.position).length();
  8353. };
  8354. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8355. if (!this._physicImpostor) {
  8356. return;
  8357. }
  8358. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8359. };
  8360. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8361. if (!this._physicImpostor) {
  8362. return;
  8363. }
  8364. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8365. };
  8366. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8367. if (!this._physicImpostor) {
  8368. return;
  8369. }
  8370. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8371. };
  8372. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8373. var globalPosition = this.getAbsolutePosition();
  8374. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8375. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8376. this._collider.radius = this.ellipsoid;
  8377. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  8378. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  8379. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8380. this.position.addInPlace(this._diffPositionForCollisions);
  8381. }
  8382. };
  8383. /**
  8384. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8385. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8386. */
  8387. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8388. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8389. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8390. if (!this._submeshesOctree) {
  8391. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8392. }
  8393. this.computeWorldMatrix(true);
  8394. var bbox = this.getBoundingInfo().boundingBox;
  8395. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8396. return this._submeshesOctree;
  8397. };
  8398. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8399. this._generatePointsArray();
  8400. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8401. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8402. subMesh._lastColliderWorldVertices = [];
  8403. subMesh._trianglePlanes = [];
  8404. var start = subMesh.verticesStart;
  8405. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8406. for (var i = start; i < end; i++) {
  8407. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8408. }
  8409. }
  8410. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  8411. };
  8412. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8413. var subMeshes;
  8414. var len;
  8415. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8416. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8417. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8418. len = intersections.length;
  8419. subMeshes = intersections.data;
  8420. } else {
  8421. subMeshes = this.subMeshes;
  8422. len = subMeshes.length;
  8423. }
  8424. for (var index = 0; index < len; index++) {
  8425. var subMesh = subMeshes[index];
  8426. if (len > 1 && !subMesh._checkCollision(collider))
  8427. continue;
  8428. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8429. }
  8430. };
  8431. AbstractMesh.prototype._checkCollision = function (collider) {
  8432. if (!this._boundingInfo._checkCollision(collider))
  8433. return;
  8434. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8435. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8436. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8437. };
  8438. AbstractMesh.prototype._generatePointsArray = function () {
  8439. return false;
  8440. };
  8441. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8442. var pickingInfo = new BABYLON.PickingInfo();
  8443. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8444. return pickingInfo;
  8445. }
  8446. if (!this._generatePointsArray()) {
  8447. return pickingInfo;
  8448. }
  8449. var intersectInfo = null;
  8450. var subMeshes;
  8451. var len;
  8452. if (this._submeshesOctree && this.useOctreeForPicking) {
  8453. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8454. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8455. len = intersections.length;
  8456. subMeshes = intersections.data;
  8457. } else {
  8458. subMeshes = this.subMeshes;
  8459. len = subMeshes.length;
  8460. }
  8461. for (var index = 0; index < len; index++) {
  8462. var subMesh = subMeshes[index];
  8463. if (len > 1 && !subMesh.canIntersects(ray))
  8464. continue;
  8465. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8466. if (currentIntersectInfo) {
  8467. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8468. intersectInfo = currentIntersectInfo;
  8469. if (fastCheck) {
  8470. break;
  8471. }
  8472. }
  8473. }
  8474. }
  8475. if (intersectInfo) {
  8476. var world = this.getWorldMatrix();
  8477. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8478. var direction = ray.direction.clone();
  8479. direction.normalize();
  8480. direction = direction.scale(intersectInfo.distance);
  8481. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8482. var pickedPoint = worldOrigin.add(worldDirection);
  8483. pickingInfo.hit = true;
  8484. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8485. pickingInfo.pickedPoint = pickedPoint;
  8486. pickingInfo.pickedMesh = this;
  8487. pickingInfo.bu = intersectInfo.bu;
  8488. pickingInfo.bv = intersectInfo.bv;
  8489. pickingInfo.faceId = intersectInfo.faceId;
  8490. return pickingInfo;
  8491. }
  8492. return pickingInfo;
  8493. };
  8494. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8495. return null;
  8496. };
  8497. AbstractMesh.prototype.releaseSubMeshes = function () {
  8498. if (this.subMeshes) {
  8499. while (this.subMeshes.length) {
  8500. this.subMeshes[0].dispose();
  8501. }
  8502. } else {
  8503. this.subMeshes = new Array();
  8504. }
  8505. };
  8506. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8507. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  8508. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8509. }
  8510. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8511. var other = this._intersectionsInProgress[index];
  8512. var pos = other._intersectionsInProgress.indexOf(this);
  8513. other._intersectionsInProgress.splice(pos, 1);
  8514. }
  8515. this._intersectionsInProgress = [];
  8516. this.releaseSubMeshes();
  8517. var index = this.getScene().meshes.indexOf(this);
  8518. if (index != -1) {
  8519. this.getScene().meshes.splice(index, 1);
  8520. }
  8521. if (!doNotRecurse) {
  8522. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8523. if (this.getScene().particleSystems[index].emitter == this) {
  8524. this.getScene().particleSystems[index].dispose();
  8525. index--;
  8526. }
  8527. }
  8528. var objects = this.getScene().meshes.slice(0);
  8529. for (index = 0; index < objects.length; index++) {
  8530. if (objects[index].parent == this) {
  8531. objects[index].dispose();
  8532. }
  8533. }
  8534. } else {
  8535. for (index = 0; index < this.getScene().meshes.length; index++) {
  8536. var obj = this.getScene().meshes[index];
  8537. if (obj.parent === this) {
  8538. obj.parent = null;
  8539. obj.computeWorldMatrix(true);
  8540. }
  8541. }
  8542. }
  8543. this._onAfterWorldMatrixUpdate = [];
  8544. this._isDisposed = true;
  8545. if (this.onDispose) {
  8546. this.onDispose();
  8547. }
  8548. };
  8549. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8550. AbstractMesh._BILLBOARDMODE_X = 1;
  8551. AbstractMesh._BILLBOARDMODE_Y = 2;
  8552. AbstractMesh._BILLBOARDMODE_Z = 4;
  8553. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8554. return AbstractMesh;
  8555. })(BABYLON.Node);
  8556. BABYLON.AbstractMesh = AbstractMesh;
  8557. })(BABYLON || (BABYLON = {}));
  8558. var __extends = this.__extends || function (d, b) {
  8559. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8560. function __() { this.constructor = d; }
  8561. __.prototype = b.prototype;
  8562. d.prototype = new __();
  8563. };
  8564. var BABYLON;
  8565. (function (BABYLON) {
  8566. var _InstancesBatch = (function () {
  8567. function _InstancesBatch() {
  8568. this.mustReturn = false;
  8569. this.visibleInstances = new Array();
  8570. this.renderSelf = new Array();
  8571. }
  8572. return _InstancesBatch;
  8573. })();
  8574. BABYLON._InstancesBatch = _InstancesBatch;
  8575. var Mesh = (function (_super) {
  8576. __extends(Mesh, _super);
  8577. function Mesh(name, scene) {
  8578. _super.call(this, name, scene);
  8579. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  8580. this.instances = new Array();
  8581. this._LODLevels = new Array();
  8582. this._onBeforeRenderCallbacks = new Array();
  8583. this._onAfterRenderCallbacks = new Array();
  8584. this._visibleInstances = {};
  8585. this._renderIdForInstances = new Array();
  8586. this._batchCache = new _InstancesBatch();
  8587. this._instancesBufferSize = 32 * 16 * 4;
  8588. }
  8589. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  8590. get: function () {
  8591. return this._LODLevels.length > 0;
  8592. },
  8593. enumerable: true,
  8594. configurable: true
  8595. });
  8596. Mesh.prototype._sortLODLevels = function () {
  8597. this._LODLevels.sort(function (a, b) {
  8598. if (a.distance < b.distance) {
  8599. return 1;
  8600. }
  8601. if (a.distance > b.distance) {
  8602. return -1;
  8603. }
  8604. return 0;
  8605. });
  8606. };
  8607. Mesh.prototype.addLODLevel = function (distance, mesh) {
  8608. if (mesh && mesh._masterMesh) {
  8609. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  8610. return this;
  8611. }
  8612. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  8613. this._LODLevels.push(level);
  8614. if (mesh) {
  8615. mesh._masterMesh = this;
  8616. }
  8617. this._sortLODLevels();
  8618. return this;
  8619. };
  8620. Mesh.prototype.removeLODLevel = function (mesh) {
  8621. for (var index = 0; index < this._LODLevels.length; index++) {
  8622. if (this._LODLevels[index].mesh === mesh) {
  8623. this._LODLevels.splice(index, 1);
  8624. if (mesh) {
  8625. mesh._masterMesh = null;
  8626. }
  8627. }
  8628. }
  8629. this._sortLODLevels();
  8630. return this;
  8631. };
  8632. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  8633. if (!this._LODLevels || this._LODLevels.length === 0) {
  8634. return this;
  8635. }
  8636. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  8637. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  8638. return this;
  8639. }
  8640. for (var index = 0; index < this._LODLevels.length; index++) {
  8641. var level = this._LODLevels[index];
  8642. if (level.distance < distanceToCamera) {
  8643. if (level.mesh) {
  8644. level.mesh._preActivate();
  8645. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8646. }
  8647. return level.mesh;
  8648. }
  8649. }
  8650. return this;
  8651. };
  8652. Object.defineProperty(Mesh.prototype, "geometry", {
  8653. get: function () {
  8654. return this._geometry;
  8655. },
  8656. enumerable: true,
  8657. configurable: true
  8658. });
  8659. Mesh.prototype.getTotalVertices = function () {
  8660. if (!this._geometry) {
  8661. return 0;
  8662. }
  8663. return this._geometry.getTotalVertices();
  8664. };
  8665. Mesh.prototype.getVerticesData = function (kind) {
  8666. if (!this._geometry) {
  8667. return null;
  8668. }
  8669. return this._geometry.getVerticesData(kind);
  8670. };
  8671. Mesh.prototype.getVertexBuffer = function (kind) {
  8672. if (!this._geometry) {
  8673. return undefined;
  8674. }
  8675. return this._geometry.getVertexBuffer(kind);
  8676. };
  8677. Mesh.prototype.isVerticesDataPresent = function (kind) {
  8678. if (!this._geometry) {
  8679. if (this._delayInfo) {
  8680. return this._delayInfo.indexOf(kind) !== -1;
  8681. }
  8682. return false;
  8683. }
  8684. return this._geometry.isVerticesDataPresent(kind);
  8685. };
  8686. Mesh.prototype.getVerticesDataKinds = function () {
  8687. if (!this._geometry) {
  8688. var result = [];
  8689. if (this._delayInfo) {
  8690. for (var kind in this._delayInfo) {
  8691. result.push(kind);
  8692. }
  8693. }
  8694. return result;
  8695. }
  8696. return this._geometry.getVerticesDataKinds();
  8697. };
  8698. Mesh.prototype.getTotalIndices = function () {
  8699. if (!this._geometry) {
  8700. return 0;
  8701. }
  8702. return this._geometry.getTotalIndices();
  8703. };
  8704. Mesh.prototype.getIndices = function () {
  8705. if (!this._geometry) {
  8706. return [];
  8707. }
  8708. return this._geometry.getIndices();
  8709. };
  8710. Object.defineProperty(Mesh.prototype, "isBlocked", {
  8711. get: function () {
  8712. return this._masterMesh !== null && this._masterMesh !== undefined;
  8713. },
  8714. enumerable: true,
  8715. configurable: true
  8716. });
  8717. Mesh.prototype.isReady = function () {
  8718. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8719. return false;
  8720. }
  8721. return _super.prototype.isReady.call(this);
  8722. };
  8723. Mesh.prototype.isDisposed = function () {
  8724. return this._isDisposed;
  8725. };
  8726. Mesh.prototype._preActivate = function () {
  8727. var sceneRenderId = this.getScene().getRenderId();
  8728. if (this._preActivateId == sceneRenderId) {
  8729. return;
  8730. }
  8731. this._preActivateId = sceneRenderId;
  8732. this._visibleInstances = null;
  8733. };
  8734. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  8735. if (!this._visibleInstances) {
  8736. this._visibleInstances = {};
  8737. this._visibleInstances.defaultRenderId = renderId;
  8738. this._visibleInstances.selfDefaultRenderId = this._renderId;
  8739. }
  8740. if (!this._visibleInstances[renderId]) {
  8741. this._visibleInstances[renderId] = new Array();
  8742. }
  8743. this._visibleInstances[renderId].push(instance);
  8744. };
  8745. Mesh.prototype.refreshBoundingInfo = function () {
  8746. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8747. if (data) {
  8748. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  8749. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8750. }
  8751. if (this.subMeshes) {
  8752. for (var index = 0; index < this.subMeshes.length; index++) {
  8753. this.subMeshes[index].refreshBoundingInfo();
  8754. }
  8755. }
  8756. this._updateBoundingInfo();
  8757. };
  8758. Mesh.prototype._createGlobalSubMesh = function () {
  8759. var totalVertices = this.getTotalVertices();
  8760. if (!totalVertices || !this.getIndices()) {
  8761. return null;
  8762. }
  8763. this.releaseSubMeshes();
  8764. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  8765. };
  8766. Mesh.prototype.subdivide = function (count) {
  8767. if (count < 1) {
  8768. return;
  8769. }
  8770. var totalIndices = this.getTotalIndices();
  8771. var subdivisionSize = (totalIndices / count) | 0;
  8772. var offset = 0;
  8773. while (subdivisionSize % 3 != 0) {
  8774. subdivisionSize++;
  8775. }
  8776. this.releaseSubMeshes();
  8777. for (var index = 0; index < count; index++) {
  8778. if (offset >= totalIndices) {
  8779. break;
  8780. }
  8781. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  8782. offset += subdivisionSize;
  8783. }
  8784. this.synchronizeInstances();
  8785. };
  8786. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  8787. if (kind instanceof Array) {
  8788. var temp = data;
  8789. data = kind;
  8790. kind = temp;
  8791. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  8792. }
  8793. if (!this._geometry) {
  8794. var vertexData = new BABYLON.VertexData();
  8795. vertexData.set(data, kind);
  8796. var scene = this.getScene();
  8797. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  8798. } else {
  8799. this._geometry.setVerticesData(kind, data, updatable, stride);
  8800. }
  8801. };
  8802. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  8803. if (!this._geometry) {
  8804. return;
  8805. }
  8806. if (!makeItUnique) {
  8807. this._geometry.updateVerticesData(kind, data, updateExtends);
  8808. } else {
  8809. this.makeGeometryUnique();
  8810. this.updateVerticesData(kind, data, updateExtends, false);
  8811. }
  8812. };
  8813. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  8814. if (!this._geometry) {
  8815. return;
  8816. }
  8817. if (!makeItUnique) {
  8818. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  8819. } else {
  8820. this.makeGeometryUnique();
  8821. this.updateVerticesDataDirectly(kind, data, offset, false);
  8822. }
  8823. };
  8824. Mesh.prototype.makeGeometryUnique = function () {
  8825. if (!this._geometry) {
  8826. return;
  8827. }
  8828. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  8829. geometry.applyToMesh(this);
  8830. };
  8831. Mesh.prototype.setIndices = function (indices, totalVertices) {
  8832. if (!this._geometry) {
  8833. var vertexData = new BABYLON.VertexData();
  8834. vertexData.indices = indices;
  8835. var scene = this.getScene();
  8836. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  8837. } else {
  8838. this._geometry.setIndices(indices, totalVertices);
  8839. }
  8840. };
  8841. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  8842. var engine = this.getScene().getEngine();
  8843. var indexToBind;
  8844. switch (fillMode) {
  8845. case BABYLON.Material.PointFillMode:
  8846. indexToBind = null;
  8847. break;
  8848. case BABYLON.Material.WireFrameFillMode:
  8849. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  8850. break;
  8851. default:
  8852. case BABYLON.Material.TriangleFillMode:
  8853. indexToBind = this._geometry.getIndexBuffer();
  8854. break;
  8855. }
  8856. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  8857. };
  8858. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  8859. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8860. return;
  8861. }
  8862. var engine = this.getScene().getEngine();
  8863. switch (fillMode) {
  8864. case BABYLON.Material.PointFillMode:
  8865. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  8866. break;
  8867. case BABYLON.Material.WireFrameFillMode:
  8868. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  8869. break;
  8870. default:
  8871. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  8872. }
  8873. };
  8874. Mesh.prototype.registerBeforeRender = function (func) {
  8875. this._onBeforeRenderCallbacks.push(func);
  8876. };
  8877. Mesh.prototype.unregisterBeforeRender = function (func) {
  8878. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8879. if (index > -1) {
  8880. this._onBeforeRenderCallbacks.splice(index, 1);
  8881. }
  8882. };
  8883. Mesh.prototype.registerAfterRender = function (func) {
  8884. this._onAfterRenderCallbacks.push(func);
  8885. };
  8886. Mesh.prototype.unregisterAfterRender = function (func) {
  8887. var index = this._onAfterRenderCallbacks.indexOf(func);
  8888. if (index > -1) {
  8889. this._onAfterRenderCallbacks.splice(index, 1);
  8890. }
  8891. };
  8892. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  8893. var scene = this.getScene();
  8894. this._batchCache.mustReturn = false;
  8895. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  8896. this._batchCache.visibleInstances[subMeshId] = null;
  8897. if (this._visibleInstances) {
  8898. var currentRenderId = scene.getRenderId();
  8899. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  8900. var selfRenderId = this._renderId;
  8901. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  8902. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  8903. currentRenderId = this._visibleInstances.defaultRenderId;
  8904. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  8905. }
  8906. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  8907. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  8908. this._batchCache.mustReturn = true;
  8909. return this._batchCache;
  8910. }
  8911. if (currentRenderId !== selfRenderId) {
  8912. this._batchCache.renderSelf[subMeshId] = false;
  8913. }
  8914. }
  8915. this._renderIdForInstances[subMeshId] = currentRenderId;
  8916. }
  8917. return this._batchCache;
  8918. };
  8919. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  8920. var visibleInstances = batch.visibleInstances[subMesh._id];
  8921. var matricesCount = visibleInstances.length + 1;
  8922. var bufferSize = matricesCount * 16 * 4;
  8923. while (this._instancesBufferSize < bufferSize) {
  8924. this._instancesBufferSize *= 2;
  8925. }
  8926. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  8927. if (this._worldMatricesInstancesBuffer) {
  8928. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8929. }
  8930. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  8931. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  8932. }
  8933. var offset = 0;
  8934. var instancesCount = 0;
  8935. var world = this.getWorldMatrix();
  8936. if (batch.renderSelf[subMesh._id]) {
  8937. world.copyToArray(this._worldMatricesInstancesArray, offset);
  8938. offset += 16;
  8939. instancesCount++;
  8940. }
  8941. if (visibleInstances) {
  8942. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  8943. var instance = visibleInstances[instanceIndex];
  8944. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  8945. offset += 16;
  8946. instancesCount++;
  8947. }
  8948. }
  8949. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  8950. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  8951. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  8952. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  8953. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  8954. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  8955. this._draw(subMesh, fillMode, instancesCount);
  8956. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  8957. };
  8958. Mesh.prototype.render = function (subMesh) {
  8959. var scene = this.getScene();
  8960. var batch = this._getInstancesRenderList(subMesh._id);
  8961. if (batch.mustReturn) {
  8962. return;
  8963. }
  8964. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8965. return;
  8966. }
  8967. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8968. this._onBeforeRenderCallbacks[callbackIndex]();
  8969. }
  8970. var engine = scene.getEngine();
  8971. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  8972. var effectiveMaterial = subMesh.getMaterial();
  8973. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  8974. return;
  8975. }
  8976. var savedDepthWrite = engine.getDepthWrite();
  8977. if (this.renderOutline) {
  8978. engine.setDepthWrite(false);
  8979. scene.getOutlineRenderer().render(subMesh, batch);
  8980. engine.setDepthWrite(savedDepthWrite);
  8981. }
  8982. effectiveMaterial._preBind();
  8983. var effect = effectiveMaterial.getEffect();
  8984. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  8985. this._bind(subMesh, effect, fillMode);
  8986. var world = this.getWorldMatrix();
  8987. effectiveMaterial.bind(world, this);
  8988. if (hardwareInstancedRendering) {
  8989. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  8990. } else {
  8991. if (batch.renderSelf[subMesh._id]) {
  8992. this._draw(subMesh, fillMode);
  8993. }
  8994. if (batch.visibleInstances[subMesh._id]) {
  8995. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  8996. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  8997. world = instance.getWorldMatrix();
  8998. effectiveMaterial.bindOnlyWorldMatrix(world);
  8999. this._draw(subMesh, fillMode);
  9000. }
  9001. }
  9002. }
  9003. effectiveMaterial.unbind();
  9004. if (this.renderOutline && savedDepthWrite) {
  9005. engine.setDepthWrite(true);
  9006. engine.setColorWrite(false);
  9007. scene.getOutlineRenderer().render(subMesh, batch);
  9008. engine.setColorWrite(true);
  9009. }
  9010. if (this.renderOverlay) {
  9011. var currentMode = engine.getAlphaMode();
  9012. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9013. scene.getOutlineRenderer().render(subMesh, batch, true);
  9014. engine.setAlphaMode(currentMode);
  9015. }
  9016. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9017. this._onAfterRenderCallbacks[callbackIndex]();
  9018. }
  9019. };
  9020. Mesh.prototype.getEmittedParticleSystems = function () {
  9021. var results = new Array();
  9022. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9023. var particleSystem = this.getScene().particleSystems[index];
  9024. if (particleSystem.emitter === this) {
  9025. results.push(particleSystem);
  9026. }
  9027. }
  9028. return results;
  9029. };
  9030. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  9031. var results = new Array();
  9032. var descendants = this.getDescendants();
  9033. descendants.push(this);
  9034. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9035. var particleSystem = this.getScene().particleSystems[index];
  9036. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  9037. results.push(particleSystem);
  9038. }
  9039. }
  9040. return results;
  9041. };
  9042. Mesh.prototype.getChildren = function () {
  9043. var results = [];
  9044. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9045. var mesh = this.getScene().meshes[index];
  9046. if (mesh.parent == this) {
  9047. results.push(mesh);
  9048. }
  9049. }
  9050. return results;
  9051. };
  9052. Mesh.prototype._checkDelayState = function () {
  9053. var _this = this;
  9054. var that = this;
  9055. var scene = this.getScene();
  9056. if (this._geometry) {
  9057. this._geometry.load(scene);
  9058. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9059. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  9060. scene._addPendingData(that);
  9061. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  9062. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  9063. if (data instanceof ArrayBuffer) {
  9064. _this._delayLoadingFunction(data, _this);
  9065. } else {
  9066. _this._delayLoadingFunction(JSON.parse(data), _this);
  9067. }
  9068. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9069. scene._removePendingData(_this);
  9070. }, function () {
  9071. }, scene.database, getBinaryData);
  9072. }
  9073. };
  9074. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  9075. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9076. return false;
  9077. }
  9078. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  9079. return false;
  9080. }
  9081. this._checkDelayState();
  9082. return true;
  9083. };
  9084. Mesh.prototype.setMaterialByID = function (id) {
  9085. var materials = this.getScene().materials;
  9086. for (var index = 0; index < materials.length; index++) {
  9087. if (materials[index].id == id) {
  9088. this.material = materials[index];
  9089. return;
  9090. }
  9091. }
  9092. var multiMaterials = this.getScene().multiMaterials;
  9093. for (index = 0; index < multiMaterials.length; index++) {
  9094. if (multiMaterials[index].id == id) {
  9095. this.material = multiMaterials[index];
  9096. return;
  9097. }
  9098. }
  9099. };
  9100. Mesh.prototype.getAnimatables = function () {
  9101. var results = [];
  9102. if (this.material) {
  9103. results.push(this.material);
  9104. }
  9105. if (this.skeleton) {
  9106. results.push(this.skeleton);
  9107. }
  9108. return results;
  9109. };
  9110. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  9111. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  9112. return;
  9113. }
  9114. this._resetPointsArrayCache();
  9115. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9116. var temp = [];
  9117. for (var index = 0; index < data.length; index += 3) {
  9118. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9119. }
  9120. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  9121. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9122. return;
  9123. }
  9124. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9125. for (index = 0; index < data.length; index += 3) {
  9126. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9127. }
  9128. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  9129. };
  9130. Mesh.prototype._resetPointsArrayCache = function () {
  9131. this._positions = null;
  9132. };
  9133. Mesh.prototype._generatePointsArray = function () {
  9134. if (this._positions)
  9135. return true;
  9136. this._positions = [];
  9137. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9138. if (!data) {
  9139. return false;
  9140. }
  9141. for (var index = 0; index < data.length; index += 3) {
  9142. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  9143. }
  9144. return true;
  9145. };
  9146. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9147. var result = new BABYLON.Mesh(name, this.getScene());
  9148. if (this._geometry) {
  9149. this._geometry.applyToMesh(result);
  9150. }
  9151. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  9152. result.material = this.material;
  9153. if (newParent) {
  9154. result.parent = newParent;
  9155. }
  9156. if (!doNotCloneChildren) {
  9157. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9158. var mesh = this.getScene().meshes[index];
  9159. if (mesh.parent == this) {
  9160. mesh.clone(mesh.name, result);
  9161. }
  9162. }
  9163. }
  9164. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9165. var system = this.getScene().particleSystems[index];
  9166. if (system.emitter == this) {
  9167. system.clone(system.name, result);
  9168. }
  9169. }
  9170. result.computeWorldMatrix(true);
  9171. return result;
  9172. };
  9173. Mesh.prototype.dispose = function (doNotRecurse) {
  9174. if (this._geometry) {
  9175. this._geometry.releaseForMesh(this, true);
  9176. }
  9177. if (this._worldMatricesInstancesBuffer) {
  9178. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9179. this._worldMatricesInstancesBuffer = null;
  9180. }
  9181. while (this.instances.length) {
  9182. this.instances[0].dispose();
  9183. }
  9184. _super.prototype.dispose.call(this, doNotRecurse);
  9185. };
  9186. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  9187. var _this = this;
  9188. var scene = this.getScene();
  9189. var onload = function (img) {
  9190. var canvas = document.createElement("canvas");
  9191. var context = canvas.getContext("2d");
  9192. var heightMapWidth = img.width;
  9193. var heightMapHeight = img.height;
  9194. canvas.width = heightMapWidth;
  9195. canvas.height = heightMapHeight;
  9196. context.drawImage(img, 0, 0);
  9197. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  9198. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  9199. };
  9200. BABYLON.Tools.LoadImage(url, onload, function () {
  9201. }, scene.database);
  9202. };
  9203. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  9204. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9205. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  9206. return;
  9207. }
  9208. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9209. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9210. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9211. var position = BABYLON.Vector3.Zero();
  9212. var normal = BABYLON.Vector3.Zero();
  9213. var uv = BABYLON.Vector2.Zero();
  9214. for (var index = 0; index < positions.length; index += 3) {
  9215. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  9216. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  9217. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  9218. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  9219. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  9220. var pos = (u + v * heightMapWidth) * 4;
  9221. var r = buffer[pos] / 255.0;
  9222. var g = buffer[pos + 1] / 255.0;
  9223. var b = buffer[pos + 2] / 255.0;
  9224. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  9225. normal.normalize();
  9226. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  9227. position = position.add(normal);
  9228. position.toArray(positions, index);
  9229. }
  9230. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  9231. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  9232. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  9233. };
  9234. Mesh.prototype.convertToFlatShadedMesh = function () {
  9235. var kinds = this.getVerticesDataKinds();
  9236. var vbs = [];
  9237. var data = [];
  9238. var newdata = [];
  9239. var updatableNormals = false;
  9240. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9241. var kind = kinds[kindIndex];
  9242. var vertexBuffer = this.getVertexBuffer(kind);
  9243. if (kind === BABYLON.VertexBuffer.NormalKind) {
  9244. updatableNormals = vertexBuffer.isUpdatable();
  9245. kinds.splice(kindIndex, 1);
  9246. kindIndex--;
  9247. continue;
  9248. }
  9249. vbs[kind] = vertexBuffer;
  9250. data[kind] = vbs[kind].getData();
  9251. newdata[kind] = [];
  9252. }
  9253. var previousSubmeshes = this.subMeshes.slice(0);
  9254. var indices = this.getIndices();
  9255. var totalIndices = this.getTotalIndices();
  9256. for (index = 0; index < totalIndices; index++) {
  9257. var vertexIndex = indices[index];
  9258. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9259. kind = kinds[kindIndex];
  9260. var stride = vbs[kind].getStrideSize();
  9261. for (var offset = 0; offset < stride; offset++) {
  9262. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  9263. }
  9264. }
  9265. }
  9266. var normals = [];
  9267. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  9268. for (var index = 0; index < totalIndices; index += 3) {
  9269. indices[index] = index;
  9270. indices[index + 1] = index + 1;
  9271. indices[index + 2] = index + 2;
  9272. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  9273. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  9274. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  9275. var p1p2 = p1.subtract(p2);
  9276. var p3p2 = p3.subtract(p2);
  9277. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  9278. for (var localIndex = 0; localIndex < 3; localIndex++) {
  9279. normals.push(normal.x);
  9280. normals.push(normal.y);
  9281. normals.push(normal.z);
  9282. }
  9283. }
  9284. this.setIndices(indices);
  9285. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  9286. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9287. kind = kinds[kindIndex];
  9288. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  9289. }
  9290. this.releaseSubMeshes();
  9291. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  9292. var previousOne = previousSubmeshes[submeshIndex];
  9293. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  9294. }
  9295. this.synchronizeInstances();
  9296. };
  9297. Mesh.prototype.createInstance = function (name) {
  9298. return new BABYLON.InstancedMesh(name, this);
  9299. };
  9300. Mesh.prototype.synchronizeInstances = function () {
  9301. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  9302. var instance = this.instances[instanceIndex];
  9303. instance._syncSubMeshes();
  9304. }
  9305. };
  9306. Mesh.CreateBox = function (name, size, scene, updatable) {
  9307. var box = new BABYLON.Mesh(name, scene);
  9308. var vertexData = BABYLON.VertexData.CreateBox(size);
  9309. vertexData.applyToMesh(box, updatable);
  9310. return box;
  9311. };
  9312. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  9313. var sphere = new BABYLON.Mesh(name, scene);
  9314. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  9315. vertexData.applyToMesh(sphere, updatable);
  9316. return sphere;
  9317. };
  9318. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  9319. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  9320. if (scene !== undefined) {
  9321. updatable = scene;
  9322. }
  9323. scene = subdivisions;
  9324. subdivisions = 1;
  9325. }
  9326. var cylinder = new BABYLON.Mesh(name, scene);
  9327. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  9328. vertexData.applyToMesh(cylinder, updatable);
  9329. return cylinder;
  9330. };
  9331. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  9332. var torus = new BABYLON.Mesh(name, scene);
  9333. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  9334. vertexData.applyToMesh(torus, updatable);
  9335. return torus;
  9336. };
  9337. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  9338. var torusKnot = new BABYLON.Mesh(name, scene);
  9339. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  9340. vertexData.applyToMesh(torusKnot, updatable);
  9341. return torusKnot;
  9342. };
  9343. Mesh.CreateLines = function (name, points, scene, updatable) {
  9344. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  9345. var vertexData = BABYLON.VertexData.CreateLines(points);
  9346. vertexData.applyToMesh(lines, updatable);
  9347. return lines;
  9348. };
  9349. Mesh.CreatePlane = function (name, size, scene, updatable) {
  9350. var plane = new BABYLON.Mesh(name, scene);
  9351. var vertexData = BABYLON.VertexData.CreatePlane(size);
  9352. vertexData.applyToMesh(plane, updatable);
  9353. return plane;
  9354. };
  9355. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  9356. var ground = new BABYLON.GroundMesh(name, scene);
  9357. ground._setReady(false);
  9358. ground._subdivisions = subdivisions;
  9359. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  9360. vertexData.applyToMesh(ground, updatable);
  9361. ground._setReady(true);
  9362. return ground;
  9363. };
  9364. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  9365. var tiledGround = new BABYLON.Mesh(name, scene);
  9366. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  9367. vertexData.applyToMesh(tiledGround, updatable);
  9368. return tiledGround;
  9369. };
  9370. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  9371. var ground = new BABYLON.GroundMesh(name, scene);
  9372. ground._subdivisions = subdivisions;
  9373. ground._setReady(false);
  9374. var onload = function (img) {
  9375. var canvas = document.createElement("canvas");
  9376. var context = canvas.getContext("2d");
  9377. var heightMapWidth = img.width;
  9378. var heightMapHeight = img.height;
  9379. canvas.width = heightMapWidth;
  9380. canvas.height = heightMapHeight;
  9381. context.drawImage(img, 0, 0);
  9382. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  9383. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  9384. vertexData.applyToMesh(ground, updatable);
  9385. ground._setReady(true);
  9386. };
  9387. BABYLON.Tools.LoadImage(url, onload, function () {
  9388. }, scene.database);
  9389. return ground;
  9390. };
  9391. Mesh.MinMax = function (meshes) {
  9392. var minVector = null;
  9393. var maxVector = null;
  9394. for (var i in meshes) {
  9395. var mesh = meshes[i];
  9396. var boundingBox = mesh.getBoundingInfo().boundingBox;
  9397. if (!minVector) {
  9398. minVector = boundingBox.minimumWorld;
  9399. maxVector = boundingBox.maximumWorld;
  9400. continue;
  9401. }
  9402. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  9403. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  9404. }
  9405. return {
  9406. min: minVector,
  9407. max: maxVector
  9408. };
  9409. };
  9410. Mesh.Center = function (meshesOrMinMaxVector) {
  9411. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  9412. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  9413. };
  9414. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  9415. if (typeof disposeSource === "undefined") { disposeSource = true; }
  9416. var source = meshes[0];
  9417. var material = source.material;
  9418. var scene = source.getScene();
  9419. if (!allow32BitsIndices) {
  9420. var totalVertices = 0;
  9421. for (var index = 0; index < meshes.length; index++) {
  9422. totalVertices += meshes[index].getTotalVertices();
  9423. if (totalVertices > 65536) {
  9424. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  9425. return null;
  9426. }
  9427. }
  9428. }
  9429. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  9430. vertexData.transform(source.getWorldMatrix());
  9431. for (index = 1; index < meshes.length; index++) {
  9432. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  9433. otherVertexData.transform(meshes[index].getWorldMatrix());
  9434. vertexData.merge(otherVertexData);
  9435. }
  9436. var newMesh = new Mesh(source.name + "_merged", scene);
  9437. vertexData.applyToMesh(newMesh);
  9438. newMesh.material = material;
  9439. newMesh.checkCollisions = source.checkCollisions;
  9440. if (disposeSource) {
  9441. for (index = 0; index < meshes.length; index++) {
  9442. meshes[index].dispose();
  9443. }
  9444. }
  9445. return newMesh;
  9446. };
  9447. return Mesh;
  9448. })(BABYLON.AbstractMesh);
  9449. BABYLON.Mesh = Mesh;
  9450. })(BABYLON || (BABYLON = {}));
  9451. var __extends = this.__extends || function (d, b) {
  9452. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9453. function __() { this.constructor = d; }
  9454. __.prototype = b.prototype;
  9455. d.prototype = new __();
  9456. };
  9457. var BABYLON;
  9458. (function (BABYLON) {
  9459. var GroundMesh = (function (_super) {
  9460. __extends(GroundMesh, _super);
  9461. function GroundMesh(name, scene) {
  9462. _super.call(this, name, scene);
  9463. this.generateOctree = false;
  9464. this._worldInverse = new BABYLON.Matrix();
  9465. }
  9466. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  9467. get: function () {
  9468. return this._subdivisions;
  9469. },
  9470. enumerable: true,
  9471. configurable: true
  9472. });
  9473. GroundMesh.prototype.optimize = function (chunksCount) {
  9474. this.subdivide(this._subdivisions);
  9475. this.createOrUpdateSubmeshesOctree(32);
  9476. };
  9477. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  9478. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  9479. this.getWorldMatrix().invertToRef(this._worldInverse);
  9480. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  9481. var pickInfo = this.intersects(ray);
  9482. if (pickInfo.hit) {
  9483. return pickInfo.pickedPoint.y;
  9484. }
  9485. return 0;
  9486. };
  9487. return GroundMesh;
  9488. })(BABYLON.Mesh);
  9489. BABYLON.GroundMesh = GroundMesh;
  9490. })(BABYLON || (BABYLON = {}));
  9491. var __extends = this.__extends || function (d, b) {
  9492. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9493. function __() { this.constructor = d; }
  9494. __.prototype = b.prototype;
  9495. d.prototype = new __();
  9496. };
  9497. var BABYLON;
  9498. (function (BABYLON) {
  9499. var InstancedMesh = (function (_super) {
  9500. __extends(InstancedMesh, _super);
  9501. function InstancedMesh(name, source) {
  9502. _super.call(this, name, source.getScene());
  9503. source.instances.push(this);
  9504. this._sourceMesh = source;
  9505. this.position.copyFrom(source.position);
  9506. this.rotation.copyFrom(source.rotation);
  9507. this.scaling.copyFrom(source.scaling);
  9508. if (source.rotationQuaternion) {
  9509. this.rotationQuaternion = source.rotationQuaternion.clone();
  9510. }
  9511. this.infiniteDistance = source.infiniteDistance;
  9512. this.setPivotMatrix(source.getPivotMatrix());
  9513. this.refreshBoundingInfo();
  9514. this._syncSubMeshes();
  9515. }
  9516. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  9517. get: function () {
  9518. return this._sourceMesh.receiveShadows;
  9519. },
  9520. enumerable: true,
  9521. configurable: true
  9522. });
  9523. Object.defineProperty(InstancedMesh.prototype, "material", {
  9524. get: function () {
  9525. return this._sourceMesh.material;
  9526. },
  9527. enumerable: true,
  9528. configurable: true
  9529. });
  9530. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  9531. get: function () {
  9532. return this._sourceMesh.visibility;
  9533. },
  9534. enumerable: true,
  9535. configurable: true
  9536. });
  9537. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  9538. get: function () {
  9539. return this._sourceMesh.skeleton;
  9540. },
  9541. enumerable: true,
  9542. configurable: true
  9543. });
  9544. InstancedMesh.prototype.getTotalVertices = function () {
  9545. return this._sourceMesh.getTotalVertices();
  9546. };
  9547. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  9548. get: function () {
  9549. return this._sourceMesh;
  9550. },
  9551. enumerable: true,
  9552. configurable: true
  9553. });
  9554. InstancedMesh.prototype.getVerticesData = function (kind) {
  9555. return this._sourceMesh.getVerticesData(kind);
  9556. };
  9557. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  9558. return this._sourceMesh.isVerticesDataPresent(kind);
  9559. };
  9560. InstancedMesh.prototype.getIndices = function () {
  9561. return this._sourceMesh.getIndices();
  9562. };
  9563. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  9564. get: function () {
  9565. return this._sourceMesh._positions;
  9566. },
  9567. enumerable: true,
  9568. configurable: true
  9569. });
  9570. InstancedMesh.prototype.refreshBoundingInfo = function () {
  9571. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9572. if (data) {
  9573. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  9574. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9575. }
  9576. this._updateBoundingInfo();
  9577. };
  9578. InstancedMesh.prototype._preActivate = function () {
  9579. if (this._currentLOD) {
  9580. this._currentLOD._preActivate();
  9581. }
  9582. };
  9583. InstancedMesh.prototype._activate = function (renderId) {
  9584. if (this._currentLOD) {
  9585. this._currentLOD._registerInstanceForRenderId(this, renderId);
  9586. }
  9587. };
  9588. InstancedMesh.prototype.getLOD = function (camera) {
  9589. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  9590. return this._currentLOD;
  9591. };
  9592. InstancedMesh.prototype._syncSubMeshes = function () {
  9593. this.releaseSubMeshes();
  9594. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  9595. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  9596. }
  9597. };
  9598. InstancedMesh.prototype._generatePointsArray = function () {
  9599. return this._sourceMesh._generatePointsArray();
  9600. };
  9601. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9602. var result = this._sourceMesh.createInstance(name);
  9603. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  9604. this.refreshBoundingInfo();
  9605. if (newParent) {
  9606. result.parent = newParent;
  9607. }
  9608. if (!doNotCloneChildren) {
  9609. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9610. var mesh = this.getScene().meshes[index];
  9611. if (mesh.parent == this) {
  9612. mesh.clone(mesh.name, result);
  9613. }
  9614. }
  9615. }
  9616. result.computeWorldMatrix(true);
  9617. return result;
  9618. };
  9619. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  9620. var index = this._sourceMesh.instances.indexOf(this);
  9621. this._sourceMesh.instances.splice(index, 1);
  9622. _super.prototype.dispose.call(this, doNotRecurse);
  9623. };
  9624. return InstancedMesh;
  9625. })(BABYLON.AbstractMesh);
  9626. BABYLON.InstancedMesh = InstancedMesh;
  9627. })(BABYLON || (BABYLON = {}));
  9628. var BABYLON;
  9629. (function (BABYLON) {
  9630. var SubMesh = (function () {
  9631. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  9632. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  9633. this.materialIndex = materialIndex;
  9634. this.verticesStart = verticesStart;
  9635. this.verticesCount = verticesCount;
  9636. this.indexStart = indexStart;
  9637. this.indexCount = indexCount;
  9638. this._renderId = 0;
  9639. this._mesh = mesh;
  9640. this._renderingMesh = renderingMesh || mesh;
  9641. mesh.subMeshes.push(this);
  9642. this._id = mesh.subMeshes.length - 1;
  9643. if (createBoundingBox) {
  9644. this.refreshBoundingInfo();
  9645. }
  9646. }
  9647. SubMesh.prototype.getBoundingInfo = function () {
  9648. return this._boundingInfo;
  9649. };
  9650. SubMesh.prototype.getMesh = function () {
  9651. return this._mesh;
  9652. };
  9653. SubMesh.prototype.getRenderingMesh = function () {
  9654. return this._renderingMesh;
  9655. };
  9656. SubMesh.prototype.getMaterial = function () {
  9657. var rootMaterial = this._renderingMesh.material;
  9658. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  9659. var multiMaterial = rootMaterial;
  9660. return multiMaterial.getSubMaterial(this.materialIndex);
  9661. }
  9662. if (!rootMaterial) {
  9663. return this._mesh.getScene().defaultMaterial;
  9664. }
  9665. return rootMaterial;
  9666. };
  9667. SubMesh.prototype.refreshBoundingInfo = function () {
  9668. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9669. if (!data) {
  9670. this._boundingInfo = this._mesh._boundingInfo;
  9671. return;
  9672. }
  9673. var indices = this._renderingMesh.getIndices();
  9674. var extend;
  9675. if (this.indexStart === 0 && this.indexCount === indices.length) {
  9676. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  9677. } else {
  9678. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  9679. }
  9680. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9681. };
  9682. SubMesh.prototype._checkCollision = function (collider) {
  9683. return this._boundingInfo._checkCollision(collider);
  9684. };
  9685. SubMesh.prototype.updateBoundingInfo = function (world) {
  9686. if (!this._boundingInfo) {
  9687. this.refreshBoundingInfo();
  9688. }
  9689. this._boundingInfo._update(world);
  9690. };
  9691. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  9692. return this._boundingInfo.isInFrustum(frustumPlanes);
  9693. };
  9694. SubMesh.prototype.render = function () {
  9695. this._renderingMesh.render(this);
  9696. };
  9697. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  9698. if (!this._linesIndexBuffer) {
  9699. var linesIndices = [];
  9700. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  9701. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  9702. }
  9703. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  9704. this.linesIndexCount = linesIndices.length;
  9705. }
  9706. return this._linesIndexBuffer;
  9707. };
  9708. SubMesh.prototype.canIntersects = function (ray) {
  9709. return ray.intersectsBox(this._boundingInfo.boundingBox);
  9710. };
  9711. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  9712. var intersectInfo = null;
  9713. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  9714. var p0 = positions[indices[index]];
  9715. var p1 = positions[indices[index + 1]];
  9716. var p2 = positions[indices[index + 2]];
  9717. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  9718. if (currentIntersectInfo) {
  9719. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9720. intersectInfo = currentIntersectInfo;
  9721. intersectInfo.faceId = index / 3;
  9722. if (fastCheck) {
  9723. break;
  9724. }
  9725. }
  9726. }
  9727. }
  9728. return intersectInfo;
  9729. };
  9730. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  9731. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  9732. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  9733. return result;
  9734. };
  9735. SubMesh.prototype.dispose = function () {
  9736. if (this._linesIndexBuffer) {
  9737. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  9738. this._linesIndexBuffer = null;
  9739. }
  9740. var index = this._mesh.subMeshes.indexOf(this);
  9741. this._mesh.subMeshes.splice(index, 1);
  9742. };
  9743. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  9744. var minVertexIndex = Number.MAX_VALUE;
  9745. var maxVertexIndex = -Number.MAX_VALUE;
  9746. renderingMesh = renderingMesh || mesh;
  9747. var indices = renderingMesh.getIndices();
  9748. for (var index = startIndex; index < startIndex + indexCount; index++) {
  9749. var vertexIndex = indices[index];
  9750. if (vertexIndex < minVertexIndex)
  9751. minVertexIndex = vertexIndex;
  9752. if (vertexIndex > maxVertexIndex)
  9753. maxVertexIndex = vertexIndex;
  9754. }
  9755. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  9756. };
  9757. return SubMesh;
  9758. })();
  9759. BABYLON.SubMesh = SubMesh;
  9760. })(BABYLON || (BABYLON = {}));
  9761. var BABYLON;
  9762. (function (BABYLON) {
  9763. var BaseTexture = (function () {
  9764. function BaseTexture(scene) {
  9765. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9766. this.hasAlpha = false;
  9767. this.getAlphaFromRGB = false;
  9768. this.level = 1;
  9769. this.isCube = false;
  9770. this.isRenderTarget = false;
  9771. this.animations = new Array();
  9772. this.coordinatesIndex = 0;
  9773. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  9774. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  9775. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  9776. this.anisotropicFilteringLevel = 4;
  9777. this._scene = scene;
  9778. this._scene.textures.push(this);
  9779. }
  9780. BaseTexture.prototype.getScene = function () {
  9781. return this._scene;
  9782. };
  9783. BaseTexture.prototype.getTextureMatrix = function () {
  9784. return null;
  9785. };
  9786. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  9787. return null;
  9788. };
  9789. BaseTexture.prototype.getInternalTexture = function () {
  9790. return this._texture;
  9791. };
  9792. BaseTexture.prototype.isReady = function () {
  9793. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9794. return true;
  9795. }
  9796. if (this._texture) {
  9797. return this._texture.isReady;
  9798. }
  9799. return false;
  9800. };
  9801. BaseTexture.prototype.getSize = function () {
  9802. if (this._texture._width) {
  9803. return { width: this._texture._width, height: this._texture._height };
  9804. }
  9805. if (this._texture._size) {
  9806. return { width: this._texture._size, height: this._texture._size };
  9807. }
  9808. return { width: 0, height: 0 };
  9809. };
  9810. BaseTexture.prototype.getBaseSize = function () {
  9811. if (!this.isReady())
  9812. return { width: 0, height: 0 };
  9813. if (this._texture._size) {
  9814. return { width: this._texture._size, height: this._texture._size };
  9815. }
  9816. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  9817. };
  9818. BaseTexture.prototype.scale = function (ratio) {
  9819. };
  9820. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  9821. get: function () {
  9822. return false;
  9823. },
  9824. enumerable: true,
  9825. configurable: true
  9826. });
  9827. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  9828. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9829. for (var index = 0; index < texturesCache.length; index++) {
  9830. var texturesCacheEntry = texturesCache[index];
  9831. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  9832. texturesCache.splice(index, 1);
  9833. return;
  9834. }
  9835. }
  9836. };
  9837. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  9838. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9839. for (var index = 0; index < texturesCache.length; index++) {
  9840. var texturesCacheEntry = texturesCache[index];
  9841. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  9842. texturesCacheEntry.references++;
  9843. return texturesCacheEntry;
  9844. }
  9845. }
  9846. return null;
  9847. };
  9848. BaseTexture.prototype.delayLoad = function () {
  9849. };
  9850. BaseTexture.prototype.releaseInternalTexture = function () {
  9851. if (!this._texture) {
  9852. return;
  9853. }
  9854. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9855. this._texture.references--;
  9856. if (this._texture.references === 0) {
  9857. var index = texturesCache.indexOf(this._texture);
  9858. texturesCache.splice(index, 1);
  9859. this._scene.getEngine()._releaseTexture(this._texture);
  9860. delete this._texture;
  9861. }
  9862. };
  9863. BaseTexture.prototype.clone = function () {
  9864. return null;
  9865. };
  9866. BaseTexture.prototype.dispose = function () {
  9867. var index = this._scene.textures.indexOf(this);
  9868. if (index >= 0) {
  9869. this._scene.textures.splice(index, 1);
  9870. }
  9871. if (this._texture === undefined) {
  9872. return;
  9873. }
  9874. this.releaseInternalTexture();
  9875. if (this.onDispose) {
  9876. this.onDispose();
  9877. }
  9878. };
  9879. return BaseTexture;
  9880. })();
  9881. BABYLON.BaseTexture = BaseTexture;
  9882. })(BABYLON || (BABYLON = {}));
  9883. var BABYLON;
  9884. (function (BABYLON) {
  9885. var RenderingGroup = (function () {
  9886. function RenderingGroup(index, scene) {
  9887. this.index = index;
  9888. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  9889. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  9890. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  9891. this._scene = scene;
  9892. }
  9893. RenderingGroup.prototype.render = function (customRenderFunction) {
  9894. if (customRenderFunction) {
  9895. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  9896. return true;
  9897. }
  9898. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  9899. return false;
  9900. }
  9901. var engine = this._scene.getEngine();
  9902. var subIndex;
  9903. var submesh;
  9904. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  9905. submesh = this._opaqueSubMeshes.data[subIndex];
  9906. submesh.render();
  9907. }
  9908. engine.setAlphaTesting(true);
  9909. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  9910. submesh = this._alphaTestSubMeshes.data[subIndex];
  9911. submesh.render();
  9912. }
  9913. engine.setAlphaTesting(false);
  9914. if (this._transparentSubMeshes.length) {
  9915. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  9916. submesh = this._transparentSubMeshes.data[subIndex];
  9917. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  9918. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  9919. }
  9920. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  9921. sortedArray.sort(function (a, b) {
  9922. if (a._alphaIndex > b._alphaIndex) {
  9923. return 1;
  9924. }
  9925. if (a._alphaIndex < b._alphaIndex) {
  9926. return -1;
  9927. }
  9928. if (a._distanceToCamera < b._distanceToCamera) {
  9929. return 1;
  9930. }
  9931. if (a._distanceToCamera > b._distanceToCamera) {
  9932. return -1;
  9933. }
  9934. return 0;
  9935. });
  9936. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9937. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  9938. submesh = sortedArray[subIndex];
  9939. submesh.render();
  9940. }
  9941. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  9942. }
  9943. return true;
  9944. };
  9945. RenderingGroup.prototype.prepare = function () {
  9946. this._opaqueSubMeshes.reset();
  9947. this._transparentSubMeshes.reset();
  9948. this._alphaTestSubMeshes.reset();
  9949. };
  9950. RenderingGroup.prototype.dispatch = function (subMesh) {
  9951. var material = subMesh.getMaterial();
  9952. var mesh = subMesh.getMesh();
  9953. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  9954. this._transparentSubMeshes.push(subMesh);
  9955. } else if (material.needAlphaTesting()) {
  9956. this._alphaTestSubMeshes.push(subMesh);
  9957. } else {
  9958. this._opaqueSubMeshes.push(subMesh);
  9959. }
  9960. };
  9961. return RenderingGroup;
  9962. })();
  9963. BABYLON.RenderingGroup = RenderingGroup;
  9964. })(BABYLON || (BABYLON = {}));
  9965. var BABYLON;
  9966. (function (BABYLON) {
  9967. var RenderingManager = (function () {
  9968. function RenderingManager(scene) {
  9969. this._renderingGroups = new Array();
  9970. this._scene = scene;
  9971. }
  9972. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  9973. if (this._scene._activeParticleSystems.length === 0) {
  9974. return;
  9975. }
  9976. var beforeParticlesDate = BABYLON.Tools.Now;
  9977. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  9978. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  9979. if (particleSystem.renderingGroupId !== index) {
  9980. continue;
  9981. }
  9982. this._clearDepthBuffer();
  9983. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  9984. this._scene._activeParticles += particleSystem.render();
  9985. }
  9986. }
  9987. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  9988. };
  9989. RenderingManager.prototype._renderSprites = function (index) {
  9990. if (this._scene.spriteManagers.length === 0) {
  9991. return;
  9992. }
  9993. var beforeSpritessDate = BABYLON.Tools.Now;
  9994. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  9995. var spriteManager = this._scene.spriteManagers[id];
  9996. if (spriteManager.renderingGroupId === index) {
  9997. this._clearDepthBuffer();
  9998. spriteManager.render();
  9999. }
  10000. }
  10001. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  10002. };
  10003. RenderingManager.prototype._clearDepthBuffer = function () {
  10004. if (this._depthBufferAlreadyCleaned) {
  10005. return;
  10006. }
  10007. this._scene.getEngine().clear(0, false, true);
  10008. this._depthBufferAlreadyCleaned = true;
  10009. };
  10010. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  10011. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  10012. this._depthBufferAlreadyCleaned = false;
  10013. var renderingGroup = this._renderingGroups[index];
  10014. if (renderingGroup) {
  10015. this._clearDepthBuffer();
  10016. if (!renderingGroup.render(customRenderFunction)) {
  10017. this._renderingGroups.splice(index, 1);
  10018. }
  10019. }
  10020. this._renderSprites(index);
  10021. if (renderParticles) {
  10022. this._renderParticles(index, activeMeshes);
  10023. }
  10024. }
  10025. };
  10026. RenderingManager.prototype.reset = function () {
  10027. for (var index in this._renderingGroups) {
  10028. var renderingGroup = this._renderingGroups[index];
  10029. renderingGroup.prepare();
  10030. }
  10031. };
  10032. RenderingManager.prototype.dispatch = function (subMesh) {
  10033. var mesh = subMesh.getMesh();
  10034. var renderingGroupId = mesh.renderingGroupId || 0;
  10035. if (!this._renderingGroups[renderingGroupId]) {
  10036. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  10037. }
  10038. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  10039. };
  10040. RenderingManager.MAX_RENDERINGGROUPS = 4;
  10041. return RenderingManager;
  10042. })();
  10043. BABYLON.RenderingManager = RenderingManager;
  10044. })(BABYLON || (BABYLON = {}));
  10045. var __extends = this.__extends || function (d, b) {
  10046. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10047. function __() { this.constructor = d; }
  10048. __.prototype = b.prototype;
  10049. d.prototype = new __();
  10050. };
  10051. var BABYLON;
  10052. (function (BABYLON) {
  10053. var Texture = (function (_super) {
  10054. __extends(Texture, _super);
  10055. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  10056. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  10057. if (typeof onLoad === "undefined") { onLoad = null; }
  10058. if (typeof onError === "undefined") { onError = null; }
  10059. if (typeof buffer === "undefined") { buffer = null; }
  10060. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  10061. _super.call(this, scene);
  10062. this.uOffset = 0;
  10063. this.vOffset = 0;
  10064. this.uScale = 1.0;
  10065. this.vScale = 1.0;
  10066. this.uAng = 0;
  10067. this.vAng = 0;
  10068. this.wAng = 0;
  10069. this.name = url;
  10070. this.url = url;
  10071. this._noMipmap = noMipmap;
  10072. this._invertY = invertY;
  10073. this._samplingMode = samplingMode;
  10074. this._buffer = buffer;
  10075. this._deleteBuffer = deleteBuffer;
  10076. if (!url) {
  10077. return;
  10078. }
  10079. this._texture = this._getFromCache(url, noMipmap);
  10080. if (!this._texture) {
  10081. if (!scene.useDelayedTextureLoading) {
  10082. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  10083. if (deleteBuffer) {
  10084. delete this._buffer;
  10085. }
  10086. } else {
  10087. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10088. }
  10089. }
  10090. }
  10091. Texture.prototype.delayLoad = function () {
  10092. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10093. return;
  10094. }
  10095. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10096. this._texture = this._getFromCache(this.url, this._noMipmap);
  10097. if (!this._texture) {
  10098. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  10099. if (this._deleteBuffer) {
  10100. delete this._buffer;
  10101. }
  10102. }
  10103. };
  10104. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  10105. x -= this.uOffset + 0.5;
  10106. y -= this.vOffset + 0.5;
  10107. z -= 0.5;
  10108. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  10109. t.x *= this.uScale;
  10110. t.y *= this.vScale;
  10111. t.x += 0.5;
  10112. t.y += 0.5;
  10113. t.z += 0.5;
  10114. };
  10115. Texture.prototype.getTextureMatrix = function () {
  10116. 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) {
  10117. return this._cachedTextureMatrix;
  10118. }
  10119. this._cachedUOffset = this.uOffset;
  10120. this._cachedVOffset = this.vOffset;
  10121. this._cachedUScale = this.uScale;
  10122. this._cachedVScale = this.vScale;
  10123. this._cachedUAng = this.uAng;
  10124. this._cachedVAng = this.vAng;
  10125. this._cachedWAng = this.wAng;
  10126. if (!this._cachedTextureMatrix) {
  10127. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  10128. this._rowGenerationMatrix = new BABYLON.Matrix();
  10129. this._t0 = BABYLON.Vector3.Zero();
  10130. this._t1 = BABYLON.Vector3.Zero();
  10131. this._t2 = BABYLON.Vector3.Zero();
  10132. }
  10133. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  10134. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  10135. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  10136. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  10137. this._t1.subtractInPlace(this._t0);
  10138. this._t2.subtractInPlace(this._t0);
  10139. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10140. this._cachedTextureMatrix.m[0] = this._t1.x;
  10141. this._cachedTextureMatrix.m[1] = this._t1.y;
  10142. this._cachedTextureMatrix.m[2] = this._t1.z;
  10143. this._cachedTextureMatrix.m[4] = this._t2.x;
  10144. this._cachedTextureMatrix.m[5] = this._t2.y;
  10145. this._cachedTextureMatrix.m[6] = this._t2.z;
  10146. this._cachedTextureMatrix.m[8] = this._t0.x;
  10147. this._cachedTextureMatrix.m[9] = this._t0.y;
  10148. this._cachedTextureMatrix.m[10] = this._t0.z;
  10149. return this._cachedTextureMatrix;
  10150. };
  10151. Texture.prototype.getReflectionTextureMatrix = function () {
  10152. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  10153. return this._cachedTextureMatrix;
  10154. }
  10155. if (!this._cachedTextureMatrix) {
  10156. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  10157. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  10158. }
  10159. this._cachedCoordinatesMode = this.coordinatesMode;
  10160. switch (this.coordinatesMode) {
  10161. case BABYLON.Texture.SPHERICAL_MODE:
  10162. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10163. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  10164. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  10165. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  10166. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  10167. break;
  10168. case BABYLON.Texture.PLANAR_MODE:
  10169. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10170. this._cachedTextureMatrix[0] = this.uScale;
  10171. this._cachedTextureMatrix[5] = this.vScale;
  10172. this._cachedTextureMatrix[12] = this.uOffset;
  10173. this._cachedTextureMatrix[13] = this.vOffset;
  10174. break;
  10175. case BABYLON.Texture.PROJECTION_MODE:
  10176. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  10177. this._projectionModeMatrix.m[0] = 0.5;
  10178. this._projectionModeMatrix.m[5] = -0.5;
  10179. this._projectionModeMatrix.m[10] = 0.0;
  10180. this._projectionModeMatrix.m[12] = 0.5;
  10181. this._projectionModeMatrix.m[13] = 0.5;
  10182. this._projectionModeMatrix.m[14] = 1.0;
  10183. this._projectionModeMatrix.m[15] = 1.0;
  10184. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  10185. break;
  10186. default:
  10187. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10188. break;
  10189. }
  10190. return this._cachedTextureMatrix;
  10191. };
  10192. Texture.prototype.clone = function () {
  10193. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  10194. newTexture.hasAlpha = this.hasAlpha;
  10195. newTexture.level = this.level;
  10196. newTexture.wrapU = this.wrapU;
  10197. newTexture.wrapV = this.wrapV;
  10198. newTexture.coordinatesIndex = this.coordinatesIndex;
  10199. newTexture.coordinatesMode = this.coordinatesMode;
  10200. newTexture.uOffset = this.uOffset;
  10201. newTexture.vOffset = this.vOffset;
  10202. newTexture.uScale = this.uScale;
  10203. newTexture.vScale = this.vScale;
  10204. newTexture.uAng = this.uAng;
  10205. newTexture.vAng = this.vAng;
  10206. newTexture.wAng = this.wAng;
  10207. return newTexture;
  10208. };
  10209. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  10210. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  10211. if (typeof onLoad === "undefined") { onLoad = null; }
  10212. if (typeof onError === "undefined") { onError = null; }
  10213. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  10214. };
  10215. Texture.NEAREST_SAMPLINGMODE = 1;
  10216. Texture.BILINEAR_SAMPLINGMODE = 2;
  10217. Texture.TRILINEAR_SAMPLINGMODE = 3;
  10218. Texture.EXPLICIT_MODE = 0;
  10219. Texture.SPHERICAL_MODE = 1;
  10220. Texture.PLANAR_MODE = 2;
  10221. Texture.CUBIC_MODE = 3;
  10222. Texture.PROJECTION_MODE = 4;
  10223. Texture.SKYBOX_MODE = 5;
  10224. Texture.CLAMP_ADDRESSMODE = 0;
  10225. Texture.WRAP_ADDRESSMODE = 1;
  10226. Texture.MIRROR_ADDRESSMODE = 2;
  10227. return Texture;
  10228. })(BABYLON.BaseTexture);
  10229. BABYLON.Texture = Texture;
  10230. })(BABYLON || (BABYLON = {}));
  10231. var __extends = this.__extends || function (d, b) {
  10232. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10233. function __() { this.constructor = d; }
  10234. __.prototype = b.prototype;
  10235. d.prototype = new __();
  10236. };
  10237. var BABYLON;
  10238. (function (BABYLON) {
  10239. var CubeTexture = (function (_super) {
  10240. __extends(CubeTexture, _super);
  10241. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  10242. _super.call(this, scene);
  10243. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  10244. this.name = rootUrl;
  10245. this.url = rootUrl;
  10246. this._noMipmap = noMipmap;
  10247. this.hasAlpha = false;
  10248. this._texture = this._getFromCache(rootUrl, noMipmap);
  10249. if (!extensions) {
  10250. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  10251. }
  10252. this._extensions = extensions;
  10253. if (!this._texture) {
  10254. if (!scene.useDelayedTextureLoading) {
  10255. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  10256. } else {
  10257. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10258. }
  10259. }
  10260. this.isCube = true;
  10261. this._textureMatrix = BABYLON.Matrix.Identity();
  10262. }
  10263. CubeTexture.prototype.clone = function () {
  10264. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  10265. newTexture.level = this.level;
  10266. newTexture.wrapU = this.wrapU;
  10267. newTexture.wrapV = this.wrapV;
  10268. newTexture.coordinatesIndex = this.coordinatesIndex;
  10269. newTexture.coordinatesMode = this.coordinatesMode;
  10270. return newTexture;
  10271. };
  10272. CubeTexture.prototype.delayLoad = function () {
  10273. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10274. return;
  10275. }
  10276. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10277. this._texture = this._getFromCache(this.url, this._noMipmap);
  10278. if (!this._texture) {
  10279. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  10280. }
  10281. };
  10282. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  10283. return this._textureMatrix;
  10284. };
  10285. return CubeTexture;
  10286. })(BABYLON.BaseTexture);
  10287. BABYLON.CubeTexture = CubeTexture;
  10288. })(BABYLON || (BABYLON = {}));
  10289. var __extends = this.__extends || function (d, b) {
  10290. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10291. function __() { this.constructor = d; }
  10292. __.prototype = b.prototype;
  10293. d.prototype = new __();
  10294. };
  10295. var BABYLON;
  10296. (function (BABYLON) {
  10297. var RenderTargetTexture = (function (_super) {
  10298. __extends(RenderTargetTexture, _super);
  10299. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  10300. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  10301. _super.call(this, null, scene, !generateMipMaps);
  10302. this.renderList = new Array();
  10303. this.renderParticles = true;
  10304. this.renderSprites = false;
  10305. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  10306. this._currentRefreshId = -1;
  10307. this._refreshRate = 1;
  10308. this.name = name;
  10309. this.isRenderTarget = true;
  10310. this._size = size;
  10311. this._generateMipMaps = generateMipMaps;
  10312. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  10313. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  10314. this._renderingManager = new BABYLON.RenderingManager(scene);
  10315. }
  10316. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  10317. this._currentRefreshId = -1;
  10318. };
  10319. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  10320. get: function () {
  10321. return this._refreshRate;
  10322. },
  10323. set: function (value) {
  10324. this._refreshRate = value;
  10325. this.resetRefreshCounter();
  10326. },
  10327. enumerable: true,
  10328. configurable: true
  10329. });
  10330. RenderTargetTexture.prototype._shouldRender = function () {
  10331. if (this._currentRefreshId === -1) {
  10332. this._currentRefreshId = 1;
  10333. return true;
  10334. }
  10335. if (this.refreshRate == this._currentRefreshId) {
  10336. this._currentRefreshId = 1;
  10337. return true;
  10338. }
  10339. this._currentRefreshId++;
  10340. return false;
  10341. };
  10342. RenderTargetTexture.prototype.isReady = function () {
  10343. if (!this.getScene().renderTargetsEnabled) {
  10344. return false;
  10345. }
  10346. return _super.prototype.isReady.call(this);
  10347. };
  10348. RenderTargetTexture.prototype.getRenderSize = function () {
  10349. return this._size;
  10350. };
  10351. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  10352. get: function () {
  10353. return true;
  10354. },
  10355. enumerable: true,
  10356. configurable: true
  10357. });
  10358. RenderTargetTexture.prototype.scale = function (ratio) {
  10359. var newSize = this._size * ratio;
  10360. this.resize(newSize, this._generateMipMaps);
  10361. };
  10362. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  10363. this.releaseInternalTexture();
  10364. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  10365. };
  10366. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  10367. var scene = this.getScene();
  10368. var engine = scene.getEngine();
  10369. if (this._waitingRenderList) {
  10370. this.renderList = [];
  10371. for (var index = 0; index < this._waitingRenderList.length; index++) {
  10372. var id = this._waitingRenderList[index];
  10373. this.renderList.push(scene.getMeshByID(id));
  10374. }
  10375. delete this._waitingRenderList;
  10376. }
  10377. if (!this.renderList) {
  10378. return;
  10379. }
  10380. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  10381. engine.bindFramebuffer(this._texture);
  10382. }
  10383. engine.clear(scene.clearColor, true, true);
  10384. this._renderingManager.reset();
  10385. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  10386. var mesh = this.renderList[meshIndex];
  10387. if (mesh) {
  10388. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  10389. this.resetRefreshCounter();
  10390. continue;
  10391. }
  10392. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  10393. mesh._activate(scene.getRenderId());
  10394. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  10395. var subMesh = mesh.subMeshes[subIndex];
  10396. scene._activeVertices += subMesh.indexCount;
  10397. this._renderingManager.dispatch(subMesh);
  10398. }
  10399. }
  10400. }
  10401. }
  10402. if (!this._doNotChangeAspectRatio) {
  10403. scene.updateTransformMatrix(true);
  10404. }
  10405. if (this.onBeforeRender) {
  10406. this.onBeforeRender();
  10407. }
  10408. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  10409. if (useCameraPostProcess) {
  10410. scene.postProcessManager._finalizeFrame(false, this._texture);
  10411. }
  10412. if (this.onAfterRender) {
  10413. this.onAfterRender();
  10414. }
  10415. engine.unBindFramebuffer(this._texture);
  10416. if (!this._doNotChangeAspectRatio) {
  10417. scene.updateTransformMatrix(true);
  10418. }
  10419. };
  10420. RenderTargetTexture.prototype.clone = function () {
  10421. var textureSize = this.getSize();
  10422. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10423. newTexture.hasAlpha = this.hasAlpha;
  10424. newTexture.level = this.level;
  10425. newTexture.coordinatesMode = this.coordinatesMode;
  10426. newTexture.renderList = this.renderList.slice(0);
  10427. return newTexture;
  10428. };
  10429. return RenderTargetTexture;
  10430. })(BABYLON.Texture);
  10431. BABYLON.RenderTargetTexture = RenderTargetTexture;
  10432. })(BABYLON || (BABYLON = {}));
  10433. var __extends = this.__extends || function (d, b) {
  10434. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10435. function __() { this.constructor = d; }
  10436. __.prototype = b.prototype;
  10437. d.prototype = new __();
  10438. };
  10439. var BABYLON;
  10440. (function (BABYLON) {
  10441. var ProceduralTexture = (function (_super) {
  10442. __extends(ProceduralTexture, _super);
  10443. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  10444. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  10445. _super.call(this, null, scene, !generateMipMaps);
  10446. this._currentRefreshId = -1;
  10447. this._refreshRate = 1;
  10448. this._vertexDeclaration = [2];
  10449. this._vertexStrideSize = 2 * 4;
  10450. this._uniforms = new Array();
  10451. this._samplers = new Array();
  10452. this._textures = new Array();
  10453. this._floats = new Array();
  10454. this._floatsArrays = {};
  10455. this._colors3 = new Array();
  10456. this._colors4 = new Array();
  10457. this._vectors2 = new Array();
  10458. this._vectors3 = new Array();
  10459. this._matrices = new Array();
  10460. this._fallbackTextureUsed = false;
  10461. scene._proceduralTextures.push(this);
  10462. this.name = name;
  10463. this.isRenderTarget = true;
  10464. this._size = size;
  10465. this._generateMipMaps = generateMipMaps;
  10466. this.setFragment(fragment);
  10467. this._fallbackTexture = fallbackTexture;
  10468. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  10469. var vertices = [];
  10470. vertices.push(1, 1);
  10471. vertices.push(-1, 1);
  10472. vertices.push(-1, -1);
  10473. vertices.push(1, -1);
  10474. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  10475. var indices = [];
  10476. indices.push(0);
  10477. indices.push(1);
  10478. indices.push(2);
  10479. indices.push(0);
  10480. indices.push(2);
  10481. indices.push(3);
  10482. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  10483. }
  10484. ProceduralTexture.prototype.reset = function () {
  10485. if (this._effect === undefined) {
  10486. return;
  10487. }
  10488. var engine = this.getScene().getEngine();
  10489. engine._releaseEffect(this._effect);
  10490. };
  10491. ProceduralTexture.prototype.isReady = function () {
  10492. var _this = this;
  10493. var engine = this.getScene().getEngine();
  10494. var shaders;
  10495. if (!this._fragment) {
  10496. return false;
  10497. }
  10498. if (this._fallbackTextureUsed) {
  10499. return true;
  10500. }
  10501. if (this._fragment.fragmentElement !== undefined) {
  10502. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  10503. } else {
  10504. shaders = { vertex: "procedural", fragment: this._fragment };
  10505. }
  10506. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  10507. _this.releaseInternalTexture();
  10508. if (_this._fallbackTexture) {
  10509. _this._texture = _this._fallbackTexture._texture;
  10510. _this._texture.references++;
  10511. }
  10512. _this._fallbackTextureUsed = true;
  10513. });
  10514. return this._effect.isReady();
  10515. };
  10516. ProceduralTexture.prototype.resetRefreshCounter = function () {
  10517. this._currentRefreshId = -1;
  10518. };
  10519. ProceduralTexture.prototype.setFragment = function (fragment) {
  10520. this._fragment = fragment;
  10521. };
  10522. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  10523. get: function () {
  10524. return this._refreshRate;
  10525. },
  10526. set: function (value) {
  10527. this._refreshRate = value;
  10528. this.resetRefreshCounter();
  10529. },
  10530. enumerable: true,
  10531. configurable: true
  10532. });
  10533. ProceduralTexture.prototype._shouldRender = function () {
  10534. if (!this.isReady() || !this._texture) {
  10535. return false;
  10536. }
  10537. if (this._fallbackTextureUsed) {
  10538. return false;
  10539. }
  10540. if (this._currentRefreshId === -1) {
  10541. this._currentRefreshId = 1;
  10542. return true;
  10543. }
  10544. if (this.refreshRate === this._currentRefreshId) {
  10545. this._currentRefreshId = 1;
  10546. return true;
  10547. }
  10548. this._currentRefreshId++;
  10549. return false;
  10550. };
  10551. ProceduralTexture.prototype.getRenderSize = function () {
  10552. return this._size;
  10553. };
  10554. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  10555. if (this._fallbackTextureUsed) {
  10556. return;
  10557. }
  10558. this.releaseInternalTexture();
  10559. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  10560. };
  10561. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  10562. if (this._uniforms.indexOf(uniformName) === -1) {
  10563. this._uniforms.push(uniformName);
  10564. }
  10565. };
  10566. ProceduralTexture.prototype.setTexture = function (name, texture) {
  10567. if (this._samplers.indexOf(name) === -1) {
  10568. this._samplers.push(name);
  10569. }
  10570. this._textures[name] = texture;
  10571. return this;
  10572. };
  10573. ProceduralTexture.prototype.setFloat = function (name, value) {
  10574. this._checkUniform(name);
  10575. this._floats[name] = value;
  10576. return this;
  10577. };
  10578. ProceduralTexture.prototype.setFloats = function (name, value) {
  10579. this._checkUniform(name);
  10580. this._floatsArrays[name] = value;
  10581. return this;
  10582. };
  10583. ProceduralTexture.prototype.setColor3 = function (name, value) {
  10584. this._checkUniform(name);
  10585. this._colors3[name] = value;
  10586. return this;
  10587. };
  10588. ProceduralTexture.prototype.setColor4 = function (name, value) {
  10589. this._checkUniform(name);
  10590. this._colors4[name] = value;
  10591. return this;
  10592. };
  10593. ProceduralTexture.prototype.setVector2 = function (name, value) {
  10594. this._checkUniform(name);
  10595. this._vectors2[name] = value;
  10596. return this;
  10597. };
  10598. ProceduralTexture.prototype.setVector3 = function (name, value) {
  10599. this._checkUniform(name);
  10600. this._vectors3[name] = value;
  10601. return this;
  10602. };
  10603. ProceduralTexture.prototype.setMatrix = function (name, value) {
  10604. this._checkUniform(name);
  10605. this._matrices[name] = value;
  10606. return this;
  10607. };
  10608. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  10609. var scene = this.getScene();
  10610. var engine = scene.getEngine();
  10611. engine.bindFramebuffer(this._texture);
  10612. engine.clear(scene.clearColor, true, true);
  10613. engine.enableEffect(this._effect);
  10614. engine.setState(false);
  10615. for (var name in this._textures) {
  10616. this._effect.setTexture(name, this._textures[name]);
  10617. }
  10618. for (name in this._floats) {
  10619. this._effect.setFloat(name, this._floats[name]);
  10620. }
  10621. for (name in this._floatsArrays) {
  10622. this._effect.setArray(name, this._floatsArrays[name]);
  10623. }
  10624. for (name in this._colors3) {
  10625. this._effect.setColor3(name, this._colors3[name]);
  10626. }
  10627. for (name in this._colors4) {
  10628. var color = this._colors4[name];
  10629. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  10630. }
  10631. for (name in this._vectors2) {
  10632. this._effect.setVector2(name, this._vectors2[name]);
  10633. }
  10634. for (name in this._vectors3) {
  10635. this._effect.setVector3(name, this._vectors3[name]);
  10636. }
  10637. for (name in this._matrices) {
  10638. this._effect.setMatrix(name, this._matrices[name]);
  10639. }
  10640. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  10641. engine.draw(true, 0, 6);
  10642. engine.unBindFramebuffer(this._texture);
  10643. };
  10644. ProceduralTexture.prototype.clone = function () {
  10645. var textureSize = this.getSize();
  10646. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  10647. newTexture.hasAlpha = this.hasAlpha;
  10648. newTexture.level = this.level;
  10649. newTexture.coordinatesMode = this.coordinatesMode;
  10650. return newTexture;
  10651. };
  10652. ProceduralTexture.prototype.dispose = function () {
  10653. var index = this.getScene()._proceduralTextures.indexOf(this);
  10654. if (index >= 0) {
  10655. this.getScene()._proceduralTextures.splice(index, 1);
  10656. }
  10657. _super.prototype.dispose.call(this);
  10658. };
  10659. return ProceduralTexture;
  10660. })(BABYLON.Texture);
  10661. BABYLON.ProceduralTexture = ProceduralTexture;
  10662. })(BABYLON || (BABYLON = {}));
  10663. var __extends = this.__extends || function (d, b) {
  10664. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10665. function __() { this.constructor = d; }
  10666. __.prototype = b.prototype;
  10667. d.prototype = new __();
  10668. };
  10669. var BABYLON;
  10670. (function (BABYLON) {
  10671. var WoodProceduralTexture = (function (_super) {
  10672. __extends(WoodProceduralTexture, _super);
  10673. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10674. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  10675. this._ampScale = 100.0;
  10676. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  10677. this.updateShaderUniforms();
  10678. this.refreshRate = 0;
  10679. }
  10680. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  10681. this.setFloat("ampScale", this._ampScale);
  10682. this.setColor3("woodColor", this._woodColor);
  10683. };
  10684. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  10685. get: function () {
  10686. return this._ampScale;
  10687. },
  10688. set: function (value) {
  10689. this._ampScale = value;
  10690. this.updateShaderUniforms();
  10691. },
  10692. enumerable: true,
  10693. configurable: true
  10694. });
  10695. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  10696. get: function () {
  10697. return this._woodColor;
  10698. },
  10699. set: function (value) {
  10700. this._woodColor = value;
  10701. this.updateShaderUniforms();
  10702. },
  10703. enumerable: true,
  10704. configurable: true
  10705. });
  10706. return WoodProceduralTexture;
  10707. })(BABYLON.ProceduralTexture);
  10708. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  10709. var FireProceduralTexture = (function (_super) {
  10710. __extends(FireProceduralTexture, _super);
  10711. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10712. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  10713. this._time = 0.0;
  10714. this._speed = new BABYLON.Vector2(0.5, 0.3);
  10715. this._shift = 1.6;
  10716. this._autoGenerateTime = true;
  10717. this._alphaThreshold = 0.5;
  10718. this._fireColors = FireProceduralTexture.RedFireColors;
  10719. this.updateShaderUniforms();
  10720. this.refreshRate = 1;
  10721. }
  10722. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  10723. this.setFloat("time", this._time);
  10724. this.setVector2("speed", this._speed);
  10725. this.setFloat("shift", this._shift);
  10726. this.setColor3("c1", this._fireColors[0]);
  10727. this.setColor3("c2", this._fireColors[1]);
  10728. this.setColor3("c3", this._fireColors[2]);
  10729. this.setColor3("c4", this._fireColors[3]);
  10730. this.setColor3("c5", this._fireColors[4]);
  10731. this.setColor3("c6", this._fireColors[5]);
  10732. this.setFloat("alphaThreshold", this._alphaThreshold);
  10733. };
  10734. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  10735. if (this._autoGenerateTime) {
  10736. this._time += this.getScene().getAnimationRatio() * 0.03;
  10737. this.updateShaderUniforms();
  10738. }
  10739. _super.prototype.render.call(this, useCameraPostProcess);
  10740. };
  10741. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  10742. get: function () {
  10743. return [
  10744. new BABYLON.Color3(0.5, 0.0, 1.0),
  10745. new BABYLON.Color3(0.9, 0.0, 1.0),
  10746. new BABYLON.Color3(0.2, 0.0, 1.0),
  10747. new BABYLON.Color3(1.0, 0.9, 1.0),
  10748. new BABYLON.Color3(0.1, 0.1, 1.0),
  10749. new BABYLON.Color3(0.9, 0.9, 1.0)
  10750. ];
  10751. },
  10752. enumerable: true,
  10753. configurable: true
  10754. });
  10755. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  10756. get: function () {
  10757. return [
  10758. new BABYLON.Color3(0.5, 1.0, 0.0),
  10759. new BABYLON.Color3(0.5, 1.0, 0.0),
  10760. new BABYLON.Color3(0.3, 0.4, 0.0),
  10761. new BABYLON.Color3(0.5, 1.0, 0.0),
  10762. new BABYLON.Color3(0.2, 0.0, 0.0),
  10763. new BABYLON.Color3(0.5, 1.0, 0.0)
  10764. ];
  10765. },
  10766. enumerable: true,
  10767. configurable: true
  10768. });
  10769. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  10770. get: function () {
  10771. return [
  10772. new BABYLON.Color3(0.5, 0.0, 0.1),
  10773. new BABYLON.Color3(0.9, 0.0, 0.0),
  10774. new BABYLON.Color3(0.2, 0.0, 0.0),
  10775. new BABYLON.Color3(1.0, 0.9, 0.0),
  10776. new BABYLON.Color3(0.1, 0.1, 0.1),
  10777. new BABYLON.Color3(0.9, 0.9, 0.9)
  10778. ];
  10779. },
  10780. enumerable: true,
  10781. configurable: true
  10782. });
  10783. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  10784. get: function () {
  10785. return [
  10786. new BABYLON.Color3(0.1, 0.0, 0.5),
  10787. new BABYLON.Color3(0.0, 0.0, 0.5),
  10788. new BABYLON.Color3(0.1, 0.0, 0.2),
  10789. new BABYLON.Color3(0.0, 0.0, 1.0),
  10790. new BABYLON.Color3(0.1, 0.2, 0.3),
  10791. new BABYLON.Color3(0.0, 0.2, 0.9)
  10792. ];
  10793. },
  10794. enumerable: true,
  10795. configurable: true
  10796. });
  10797. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  10798. get: function () {
  10799. return this._fireColors;
  10800. },
  10801. set: function (value) {
  10802. this._fireColors = value;
  10803. this.updateShaderUniforms();
  10804. },
  10805. enumerable: true,
  10806. configurable: true
  10807. });
  10808. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  10809. get: function () {
  10810. return this._time;
  10811. },
  10812. set: function (value) {
  10813. this._time = value;
  10814. this.updateShaderUniforms();
  10815. },
  10816. enumerable: true,
  10817. configurable: true
  10818. });
  10819. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  10820. get: function () {
  10821. return this._speed;
  10822. },
  10823. set: function (value) {
  10824. this._speed = value;
  10825. this.updateShaderUniforms();
  10826. },
  10827. enumerable: true,
  10828. configurable: true
  10829. });
  10830. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  10831. get: function () {
  10832. return this._shift;
  10833. },
  10834. set: function (value) {
  10835. this._shift = value;
  10836. this.updateShaderUniforms();
  10837. },
  10838. enumerable: true,
  10839. configurable: true
  10840. });
  10841. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  10842. get: function () {
  10843. return this._alphaThreshold;
  10844. },
  10845. set: function (value) {
  10846. this._alphaThreshold = value;
  10847. this.updateShaderUniforms();
  10848. },
  10849. enumerable: true,
  10850. configurable: true
  10851. });
  10852. return FireProceduralTexture;
  10853. })(BABYLON.ProceduralTexture);
  10854. BABYLON.FireProceduralTexture = FireProceduralTexture;
  10855. var CloudProceduralTexture = (function (_super) {
  10856. __extends(CloudProceduralTexture, _super);
  10857. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10858. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  10859. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  10860. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  10861. this.updateShaderUniforms();
  10862. this.refreshRate = 0;
  10863. }
  10864. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  10865. this.setColor3("skyColor", this._skyColor);
  10866. this.setColor3("cloudColor", this._cloudColor);
  10867. };
  10868. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  10869. get: function () {
  10870. return this._skyColor;
  10871. },
  10872. set: function (value) {
  10873. this._skyColor = value;
  10874. this.updateShaderUniforms();
  10875. },
  10876. enumerable: true,
  10877. configurable: true
  10878. });
  10879. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  10880. get: function () {
  10881. return this._cloudColor;
  10882. },
  10883. set: function (value) {
  10884. this._cloudColor = value;
  10885. this.updateShaderUniforms();
  10886. },
  10887. enumerable: true,
  10888. configurable: true
  10889. });
  10890. return CloudProceduralTexture;
  10891. })(BABYLON.ProceduralTexture);
  10892. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  10893. var GrassProceduralTexture = (function (_super) {
  10894. __extends(GrassProceduralTexture, _super);
  10895. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10896. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  10897. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  10898. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  10899. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  10900. this._groundColor = new BABYLON.Color3(1, 1, 1);
  10901. this._grassColors = [
  10902. new BABYLON.Color3(0.29, 0.38, 0.02),
  10903. new BABYLON.Color3(0.36, 0.49, 0.09),
  10904. new BABYLON.Color3(0.51, 0.6, 0.28)
  10905. ];
  10906. this.updateShaderUniforms();
  10907. this.refreshRate = 0;
  10908. }
  10909. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  10910. this.setColor3("herb1Color", this._grassColors[0]);
  10911. this.setColor3("herb2Color", this._grassColors[1]);
  10912. this.setColor3("herb3Color", this._grassColors[2]);
  10913. this.setColor3("groundColor", this._groundColor);
  10914. };
  10915. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  10916. get: function () {
  10917. return this._grassColors;
  10918. },
  10919. set: function (value) {
  10920. this._grassColors = value;
  10921. this.updateShaderUniforms();
  10922. },
  10923. enumerable: true,
  10924. configurable: true
  10925. });
  10926. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  10927. get: function () {
  10928. return this._groundColor;
  10929. },
  10930. set: function (value) {
  10931. this.groundColor = value;
  10932. this.updateShaderUniforms();
  10933. },
  10934. enumerable: true,
  10935. configurable: true
  10936. });
  10937. return GrassProceduralTexture;
  10938. })(BABYLON.ProceduralTexture);
  10939. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  10940. var RoadProceduralTexture = (function (_super) {
  10941. __extends(RoadProceduralTexture, _super);
  10942. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10943. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  10944. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  10945. this.updateShaderUniforms();
  10946. this.refreshRate = 0;
  10947. }
  10948. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  10949. this.setColor3("roadColor", this._roadColor);
  10950. };
  10951. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  10952. get: function () {
  10953. return this._roadColor;
  10954. },
  10955. set: function (value) {
  10956. this._roadColor = value;
  10957. this.updateShaderUniforms();
  10958. },
  10959. enumerable: true,
  10960. configurable: true
  10961. });
  10962. return RoadProceduralTexture;
  10963. })(BABYLON.ProceduralTexture);
  10964. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  10965. var BrickProceduralTexture = (function (_super) {
  10966. __extends(BrickProceduralTexture, _super);
  10967. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10968. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  10969. this._numberOfBricksHeight = 15;
  10970. this._numberOfBricksWidth = 5;
  10971. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  10972. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  10973. this.updateShaderUniforms();
  10974. this.refreshRate = 0;
  10975. }
  10976. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  10977. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  10978. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  10979. this.setColor3("brickColor", this._brickColor);
  10980. this.setColor3("jointColor", this._jointColor);
  10981. };
  10982. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  10983. get: function () {
  10984. return this._numberOfBricksHeight;
  10985. },
  10986. enumerable: true,
  10987. configurable: true
  10988. });
  10989. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  10990. set: function (value) {
  10991. this._numberOfBricksHeight = value;
  10992. this.updateShaderUniforms();
  10993. },
  10994. enumerable: true,
  10995. configurable: true
  10996. });
  10997. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  10998. get: function () {
  10999. return this._numberOfBricksWidth;
  11000. },
  11001. set: function (value) {
  11002. this._numberOfBricksHeight = value;
  11003. this.updateShaderUniforms();
  11004. },
  11005. enumerable: true,
  11006. configurable: true
  11007. });
  11008. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  11009. get: function () {
  11010. return this._jointColor;
  11011. },
  11012. set: function (value) {
  11013. this._jointColor = value;
  11014. this.updateShaderUniforms();
  11015. },
  11016. enumerable: true,
  11017. configurable: true
  11018. });
  11019. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  11020. get: function () {
  11021. return this._brickColor;
  11022. },
  11023. set: function (value) {
  11024. this._brickColor = value;
  11025. this.updateShaderUniforms();
  11026. },
  11027. enumerable: true,
  11028. configurable: true
  11029. });
  11030. return BrickProceduralTexture;
  11031. })(BABYLON.ProceduralTexture);
  11032. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  11033. var MarbleProceduralTexture = (function (_super) {
  11034. __extends(MarbleProceduralTexture, _super);
  11035. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11036. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  11037. this._numberOfTilesHeight = 3;
  11038. this._numberOfTilesWidth = 3;
  11039. this._amplitude = 9.0;
  11040. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11041. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11042. this.updateShaderUniforms();
  11043. this.refreshRate = 0;
  11044. }
  11045. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  11046. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  11047. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  11048. this.setFloat("amplitude", this._amplitude);
  11049. this.setColor3("marbleColor", this._marbleColor);
  11050. this.setColor3("jointColor", this._jointColor);
  11051. };
  11052. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  11053. get: function () {
  11054. return this._numberOfTilesHeight;
  11055. },
  11056. set: function (value) {
  11057. this._numberOfTilesHeight = value;
  11058. this.updateShaderUniforms();
  11059. },
  11060. enumerable: true,
  11061. configurable: true
  11062. });
  11063. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  11064. get: function () {
  11065. return this._numberOfTilesWidth;
  11066. },
  11067. set: function (value) {
  11068. this._numberOfTilesWidth = value;
  11069. this.updateShaderUniforms();
  11070. },
  11071. enumerable: true,
  11072. configurable: true
  11073. });
  11074. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  11075. get: function () {
  11076. return this._jointColor;
  11077. },
  11078. set: function (value) {
  11079. this._jointColor = value;
  11080. this.updateShaderUniforms();
  11081. },
  11082. enumerable: true,
  11083. configurable: true
  11084. });
  11085. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  11086. get: function () {
  11087. return this._marbleColor;
  11088. },
  11089. set: function (value) {
  11090. this._marbleColor = value;
  11091. this.updateShaderUniforms();
  11092. },
  11093. enumerable: true,
  11094. configurable: true
  11095. });
  11096. return MarbleProceduralTexture;
  11097. })(BABYLON.ProceduralTexture);
  11098. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  11099. })(BABYLON || (BABYLON = {}));
  11100. var __extends = this.__extends || function (d, b) {
  11101. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11102. function __() { this.constructor = d; }
  11103. __.prototype = b.prototype;
  11104. d.prototype = new __();
  11105. };
  11106. var BABYLON;
  11107. (function (BABYLON) {
  11108. var CustomProceduralTexture = (function (_super) {
  11109. __extends(CustomProceduralTexture, _super);
  11110. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  11111. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  11112. this._animate = true;
  11113. this._time = 0;
  11114. this._texturePath = texturePath;
  11115. this.loadJson(texturePath);
  11116. this.refreshRate = 1;
  11117. }
  11118. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  11119. var _this = this;
  11120. var that = this;
  11121. function noConfigFile() {
  11122. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShaderStore or DOM element");
  11123. try {
  11124. that.setFragment(that._texturePath);
  11125. } catch (ex) {
  11126. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  11127. }
  11128. }
  11129. var configFileUrl = jsonUrl + "/config.json";
  11130. var xhr = new XMLHttpRequest();
  11131. xhr.open("GET", configFileUrl, true);
  11132. xhr.addEventListener("load", function () {
  11133. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  11134. try {
  11135. _this._config = JSON.parse(xhr.response);
  11136. _this.updateShaderUniforms();
  11137. _this.updateTextures();
  11138. _this.setFragment(_this._texturePath + "/custom");
  11139. _this._animate = _this._config.animate;
  11140. _this.refreshRate = _this._config.refreshrate;
  11141. } catch (ex) {
  11142. noConfigFile();
  11143. }
  11144. } else {
  11145. noConfigFile();
  11146. }
  11147. }, false);
  11148. xhr.addEventListener("error", function (event) {
  11149. noConfigFile();
  11150. }, false);
  11151. try {
  11152. xhr.send();
  11153. } catch (ex) {
  11154. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  11155. }
  11156. };
  11157. CustomProceduralTexture.prototype.isReady = function () {
  11158. if (!_super.prototype.isReady.call(this)) {
  11159. return false;
  11160. }
  11161. for (var name in this._textures) {
  11162. var texture = this._textures[name];
  11163. if (!texture.isReady()) {
  11164. return false;
  11165. }
  11166. }
  11167. return true;
  11168. };
  11169. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11170. if (this._animate) {
  11171. this._time += this.getScene().getAnimationRatio() * 0.03;
  11172. this.updateShaderUniforms();
  11173. }
  11174. _super.prototype.render.call(this, useCameraPostProcess);
  11175. };
  11176. CustomProceduralTexture.prototype.updateTextures = function () {
  11177. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  11178. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  11179. }
  11180. };
  11181. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  11182. if (this._config) {
  11183. for (var j = 0; j < this._config.uniforms.length; j++) {
  11184. var uniform = this._config.uniforms[j];
  11185. switch (uniform.type) {
  11186. case "float":
  11187. this.setFloat(uniform.name, uniform.value);
  11188. break;
  11189. case "color3":
  11190. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  11191. break;
  11192. case "color4":
  11193. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  11194. break;
  11195. case "vector2":
  11196. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  11197. break;
  11198. case "vector3":
  11199. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  11200. break;
  11201. }
  11202. }
  11203. }
  11204. this.setFloat("time", this._time);
  11205. };
  11206. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  11207. get: function () {
  11208. return this._animate;
  11209. },
  11210. set: function (value) {
  11211. this._animate = value;
  11212. },
  11213. enumerable: true,
  11214. configurable: true
  11215. });
  11216. return CustomProceduralTexture;
  11217. })(BABYLON.ProceduralTexture);
  11218. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  11219. })(BABYLON || (BABYLON = {}));
  11220. var __extends = this.__extends || function (d, b) {
  11221. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11222. function __() { this.constructor = d; }
  11223. __.prototype = b.prototype;
  11224. d.prototype = new __();
  11225. };
  11226. var BABYLON;
  11227. (function (BABYLON) {
  11228. var MirrorTexture = (function (_super) {
  11229. __extends(MirrorTexture, _super);
  11230. function MirrorTexture(name, size, scene, generateMipMaps) {
  11231. var _this = this;
  11232. _super.call(this, name, size, scene, generateMipMaps, true);
  11233. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  11234. this._transformMatrix = BABYLON.Matrix.Zero();
  11235. this._mirrorMatrix = BABYLON.Matrix.Zero();
  11236. this.onBeforeRender = function () {
  11237. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  11238. _this._savedViewMatrix = scene.getViewMatrix();
  11239. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  11240. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  11241. scene.clipPlane = _this.mirrorPlane;
  11242. scene.getEngine().cullBackFaces = false;
  11243. };
  11244. this.onAfterRender = function () {
  11245. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  11246. scene.getEngine().cullBackFaces = true;
  11247. delete scene.clipPlane;
  11248. };
  11249. }
  11250. MirrorTexture.prototype.clone = function () {
  11251. var textureSize = this.getSize();
  11252. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11253. newTexture.hasAlpha = this.hasAlpha;
  11254. newTexture.level = this.level;
  11255. newTexture.mirrorPlane = this.mirrorPlane.clone();
  11256. newTexture.renderList = this.renderList.slice(0);
  11257. return newTexture;
  11258. };
  11259. return MirrorTexture;
  11260. })(BABYLON.RenderTargetTexture);
  11261. BABYLON.MirrorTexture = MirrorTexture;
  11262. })(BABYLON || (BABYLON = {}));
  11263. var __extends = this.__extends || function (d, b) {
  11264. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11265. function __() { this.constructor = d; }
  11266. __.prototype = b.prototype;
  11267. d.prototype = new __();
  11268. };
  11269. var BABYLON;
  11270. (function (BABYLON) {
  11271. var DynamicTexture = (function (_super) {
  11272. __extends(DynamicTexture, _super);
  11273. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  11274. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11275. _super.call(this, null, scene, !generateMipMaps);
  11276. this.name = name;
  11277. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11278. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11279. this._generateMipMaps = generateMipMaps;
  11280. if (options.getContext) {
  11281. this._canvas = options;
  11282. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  11283. } else {
  11284. this._canvas = document.createElement("canvas");
  11285. if (options.width) {
  11286. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  11287. } else {
  11288. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  11289. }
  11290. }
  11291. var textureSize = this.getSize();
  11292. this._canvas.width = textureSize.width;
  11293. this._canvas.height = textureSize.height;
  11294. this._context = this._canvas.getContext("2d");
  11295. }
  11296. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  11297. get: function () {
  11298. return true;
  11299. },
  11300. enumerable: true,
  11301. configurable: true
  11302. });
  11303. DynamicTexture.prototype.scale = function (ratio) {
  11304. var textureSize = this.getSize();
  11305. textureSize.width *= ratio;
  11306. textureSize.height *= ratio;
  11307. this._canvas.width = textureSize.width;
  11308. this._canvas.height = textureSize.height;
  11309. this.releaseInternalTexture();
  11310. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  11311. };
  11312. DynamicTexture.prototype.getContext = function () {
  11313. return this._context;
  11314. };
  11315. DynamicTexture.prototype.update = function (invertY) {
  11316. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  11317. };
  11318. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  11319. var size = this.getSize();
  11320. if (clearColor) {
  11321. this._context.fillStyle = clearColor;
  11322. this._context.fillRect(0, 0, size.width, size.height);
  11323. }
  11324. this._context.font = font;
  11325. if (x === null) {
  11326. var textSize = this._context.measureText(text);
  11327. x = (size.width - textSize.width) / 2;
  11328. }
  11329. this._context.fillStyle = color;
  11330. this._context.fillText(text, x, y);
  11331. this.update(invertY);
  11332. };
  11333. DynamicTexture.prototype.clone = function () {
  11334. var textureSize = this.getSize();
  11335. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11336. newTexture.hasAlpha = this.hasAlpha;
  11337. newTexture.level = this.level;
  11338. newTexture.wrapU = this.wrapU;
  11339. newTexture.wrapV = this.wrapV;
  11340. return newTexture;
  11341. };
  11342. return DynamicTexture;
  11343. })(BABYLON.Texture);
  11344. BABYLON.DynamicTexture = DynamicTexture;
  11345. })(BABYLON || (BABYLON = {}));
  11346. var __extends = this.__extends || function (d, b) {
  11347. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11348. function __() { this.constructor = d; }
  11349. __.prototype = b.prototype;
  11350. d.prototype = new __();
  11351. };
  11352. var BABYLON;
  11353. (function (BABYLON) {
  11354. var VideoTexture = (function (_super) {
  11355. __extends(VideoTexture, _super);
  11356. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  11357. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11358. var _this = this;
  11359. _super.call(this, null, scene, !generateMipMaps, invertY);
  11360. this._autoLaunch = true;
  11361. this.name = name;
  11362. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11363. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11364. var requiredWidth = size.width || size;
  11365. var requiredHeight = size.height || size;
  11366. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  11367. var textureSize = this.getSize();
  11368. this.video = document.createElement("video");
  11369. this.video.width = textureSize.width;
  11370. this.video.height = textureSize.height;
  11371. this.video.autoplay = false;
  11372. this.video.loop = true;
  11373. this.video.addEventListener("canplaythrough", function () {
  11374. if (_this._texture) {
  11375. _this._texture.isReady = true;
  11376. }
  11377. });
  11378. urls.forEach(function (url) {
  11379. var source = document.createElement("source");
  11380. source.src = url;
  11381. _this.video.appendChild(source);
  11382. });
  11383. this._lastUpdate = BABYLON.Tools.Now;
  11384. }
  11385. VideoTexture.prototype.update = function () {
  11386. if (this._autoLaunch) {
  11387. this._autoLaunch = false;
  11388. this.video.play();
  11389. }
  11390. var now = BABYLON.Tools.Now;
  11391. if (now - this._lastUpdate < 15) {
  11392. return false;
  11393. }
  11394. this._lastUpdate = now;
  11395. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  11396. return true;
  11397. };
  11398. return VideoTexture;
  11399. })(BABYLON.Texture);
  11400. BABYLON.VideoTexture = VideoTexture;
  11401. })(BABYLON || (BABYLON = {}));
  11402. var BABYLON;
  11403. (function (BABYLON) {
  11404. var EffectFallbacks = (function () {
  11405. function EffectFallbacks() {
  11406. this._defines = {};
  11407. this._currentRank = 32;
  11408. this._maxRank = -1;
  11409. }
  11410. EffectFallbacks.prototype.addFallback = function (rank, define) {
  11411. if (!this._defines[rank]) {
  11412. if (rank < this._currentRank) {
  11413. this._currentRank = rank;
  11414. }
  11415. if (rank > this._maxRank) {
  11416. this._maxRank = rank;
  11417. }
  11418. this._defines[rank] = new Array();
  11419. }
  11420. this._defines[rank].push(define);
  11421. };
  11422. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  11423. get: function () {
  11424. return this._currentRank <= this._maxRank;
  11425. },
  11426. enumerable: true,
  11427. configurable: true
  11428. });
  11429. EffectFallbacks.prototype.reduce = function (currentDefines) {
  11430. var currentFallbacks = this._defines[this._currentRank];
  11431. for (var index = 0; index < currentFallbacks.length; index++) {
  11432. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  11433. }
  11434. this._currentRank++;
  11435. return currentDefines;
  11436. };
  11437. return EffectFallbacks;
  11438. })();
  11439. BABYLON.EffectFallbacks = EffectFallbacks;
  11440. var Effect = (function () {
  11441. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  11442. var _this = this;
  11443. this._isReady = false;
  11444. this._compilationError = "";
  11445. this._valueCache = [];
  11446. this._engine = engine;
  11447. this.name = baseName;
  11448. this.defines = defines;
  11449. this._uniformsNames = uniformsNames.concat(samplers);
  11450. this._samplers = samplers;
  11451. this._attributesNames = attributesNames;
  11452. this.onError = onError;
  11453. this.onCompiled = onCompiled;
  11454. var vertexSource;
  11455. var fragmentSource;
  11456. if (baseName.vertexElement) {
  11457. vertexSource = document.getElementById(baseName.vertexElement);
  11458. if (!vertexSource) {
  11459. vertexSource = baseName.vertexElement;
  11460. }
  11461. } else {
  11462. vertexSource = baseName.vertex || baseName;
  11463. }
  11464. if (baseName.fragmentElement) {
  11465. fragmentSource = document.getElementById(baseName.fragmentElement);
  11466. if (!fragmentSource) {
  11467. fragmentSource = baseName.fragmentElement;
  11468. }
  11469. } else {
  11470. fragmentSource = baseName.fragment || baseName;
  11471. }
  11472. this._loadVertexShader(vertexSource, function (vertexCode) {
  11473. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  11474. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  11475. });
  11476. });
  11477. }
  11478. Effect.prototype.isReady = function () {
  11479. return this._isReady;
  11480. };
  11481. Effect.prototype.getProgram = function () {
  11482. return this._program;
  11483. };
  11484. Effect.prototype.getAttributesNames = function () {
  11485. return this._attributesNames;
  11486. };
  11487. Effect.prototype.getAttributeLocation = function (index) {
  11488. return this._attributes[index];
  11489. };
  11490. Effect.prototype.getAttributeLocationByName = function (name) {
  11491. var index = this._attributesNames.indexOf(name);
  11492. return this._attributes[index];
  11493. };
  11494. Effect.prototype.getAttributesCount = function () {
  11495. return this._attributes.length;
  11496. };
  11497. Effect.prototype.getUniformIndex = function (uniformName) {
  11498. return this._uniformsNames.indexOf(uniformName);
  11499. };
  11500. Effect.prototype.getUniform = function (uniformName) {
  11501. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  11502. };
  11503. Effect.prototype.getSamplers = function () {
  11504. return this._samplers;
  11505. };
  11506. Effect.prototype.getCompilationError = function () {
  11507. return this._compilationError;
  11508. };
  11509. Effect.prototype._loadVertexShader = function (vertex, callback) {
  11510. if (vertex instanceof HTMLElement) {
  11511. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  11512. callback(vertexCode);
  11513. return;
  11514. }
  11515. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  11516. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  11517. return;
  11518. }
  11519. var vertexShaderUrl;
  11520. if (vertex[0] === ".") {
  11521. vertexShaderUrl = vertex;
  11522. } else {
  11523. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  11524. }
  11525. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  11526. };
  11527. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  11528. if (fragment instanceof HTMLElement) {
  11529. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  11530. callback(fragmentCode);
  11531. return;
  11532. }
  11533. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  11534. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  11535. return;
  11536. }
  11537. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  11538. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  11539. return;
  11540. }
  11541. var fragmentShaderUrl;
  11542. if (fragment[0] === ".") {
  11543. fragmentShaderUrl = fragment;
  11544. } else {
  11545. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  11546. }
  11547. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  11548. };
  11549. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  11550. try {
  11551. var engine = this._engine;
  11552. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  11553. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  11554. this._attributes = engine.getAttributes(this._program, attributesNames);
  11555. for (var index = 0; index < this._samplers.length; index++) {
  11556. var sampler = this.getUniform(this._samplers[index]);
  11557. if (sampler == null) {
  11558. this._samplers.splice(index, 1);
  11559. index--;
  11560. }
  11561. }
  11562. engine.bindSamplers(this);
  11563. this._isReady = true;
  11564. if (this.onCompiled) {
  11565. this.onCompiled(this);
  11566. }
  11567. } catch (e) {
  11568. if (e.message.indexOf("highp") !== -1) {
  11569. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  11570. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  11571. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  11572. return;
  11573. }
  11574. if (fallbacks && fallbacks.isMoreFallbacks) {
  11575. defines = fallbacks.reduce(defines);
  11576. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  11577. } else {
  11578. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  11579. BABYLON.Tools.Error("Defines: " + defines);
  11580. BABYLON.Tools.Error("Error: " + e.message);
  11581. this._compilationError = e.message;
  11582. if (this.onError) {
  11583. this.onError(this, this._compilationError);
  11584. }
  11585. }
  11586. }
  11587. };
  11588. Effect.prototype._bindTexture = function (channel, texture) {
  11589. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  11590. };
  11591. Effect.prototype.setTexture = function (channel, texture) {
  11592. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  11593. };
  11594. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11595. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  11596. };
  11597. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  11598. if (!this._valueCache[uniformName]) {
  11599. this._valueCache[uniformName] = [x, y];
  11600. return;
  11601. }
  11602. this._valueCache[uniformName][0] = x;
  11603. this._valueCache[uniformName][1] = y;
  11604. };
  11605. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  11606. if (!this._valueCache[uniformName]) {
  11607. this._valueCache[uniformName] = [x, y, z];
  11608. return;
  11609. }
  11610. this._valueCache[uniformName][0] = x;
  11611. this._valueCache[uniformName][1] = y;
  11612. this._valueCache[uniformName][2] = z;
  11613. };
  11614. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  11615. if (!this._valueCache[uniformName]) {
  11616. this._valueCache[uniformName] = [x, y, z, w];
  11617. return;
  11618. }
  11619. this._valueCache[uniformName][0] = x;
  11620. this._valueCache[uniformName][1] = y;
  11621. this._valueCache[uniformName][2] = z;
  11622. this._valueCache[uniformName][3] = w;
  11623. };
  11624. Effect.prototype.setArray = function (uniformName, array) {
  11625. this._engine.setArray(this.getUniform(uniformName), array);
  11626. return this;
  11627. };
  11628. Effect.prototype.setMatrices = function (uniformName, matrices) {
  11629. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  11630. return this;
  11631. };
  11632. Effect.prototype.setMatrix = function (uniformName, matrix) {
  11633. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  11634. return this;
  11635. };
  11636. Effect.prototype.setFloat = function (uniformName, value) {
  11637. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  11638. return this;
  11639. this._valueCache[uniformName] = value;
  11640. this._engine.setFloat(this.getUniform(uniformName), value);
  11641. return this;
  11642. };
  11643. Effect.prototype.setBool = function (uniformName, bool) {
  11644. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  11645. return this;
  11646. this._valueCache[uniformName] = bool;
  11647. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  11648. return this;
  11649. };
  11650. Effect.prototype.setVector2 = function (uniformName, vector2) {
  11651. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  11652. return this;
  11653. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  11654. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  11655. return this;
  11656. };
  11657. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  11658. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  11659. return this;
  11660. this._cacheFloat2(uniformName, x, y);
  11661. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  11662. return this;
  11663. };
  11664. Effect.prototype.setVector3 = function (uniformName, vector3) {
  11665. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  11666. return this;
  11667. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  11668. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  11669. return this;
  11670. };
  11671. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  11672. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  11673. return this;
  11674. this._cacheFloat3(uniformName, x, y, z);
  11675. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  11676. return this;
  11677. };
  11678. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  11679. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  11680. return this;
  11681. this._cacheFloat4(uniformName, x, y, z, w);
  11682. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  11683. return this;
  11684. };
  11685. Effect.prototype.setColor3 = function (uniformName, color3) {
  11686. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  11687. return this;
  11688. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  11689. this._engine.setColor3(this.getUniform(uniformName), color3);
  11690. return this;
  11691. };
  11692. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  11693. 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)
  11694. return this;
  11695. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  11696. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  11697. return this;
  11698. };
  11699. 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}",
  11700. 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}",
  11701. 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}",
  11702. brickPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfBricksHeight;\nuniform float numberOfBricksWidth;\nuniform vec3 brickColor;\nuniform vec3 jointColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\nvoid main(void)\n{\n float brickW = 1.0 / numberOfBricksWidth;\n float brickH = 1.0 / numberOfBricksHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.05;\n vec3 color = brickColor;\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n }\n else if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\n color = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n }\n else {\n float brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\n\n if (brickColorSwitch == 0.0)\n color = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\n else if (brickColorSwitch == 2.0)\n color = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\n }\n\n gl_FragColor = vec4(color, 1.0);\n}",
  11703. cloudPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\n\nuniform vec3 skyColor;\nuniform vec3 cloudColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main() {\n\n vec2 p = vUV * 12.0;\n vec3 c = mix(skyColor, cloudColor, fbm(p));\n gl_FragColor = vec4(c, 1);\n\n}",
  11704. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  11705. 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}",
  11706. 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}",
  11707. defaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform float darkness0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform float darkness1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform float darkness2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform float darkness3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / 1500.0)) < depth.z) visibility -= 0.2;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.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;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, darkness0);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, darkness1);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, darkness2);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, darkness3);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  11708. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef REFLECTION\n vPositionUVW = position;\n#endif \n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n finalWorld = world;\n#endif\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n\n // Point size\n#ifdef POINTSIZE\n gl_PointSize = pointSize;\n#endif\n}",
  11709. 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}",
  11710. 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}",
  11711. firePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform float time;\nuniform vec3 c1;\nuniform vec3 c2;\nuniform vec3 c3;\nuniform vec3 c4;\nuniform vec3 c5;\nuniform vec3 c6;\nuniform vec2 speed;\nuniform float shift;\nuniform float alphaThreshold;\n\nvarying vec2 vUV;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main() {\n vec2 p = vUV * 8.0;\n float q = fbm(p - time * 0.1);\n vec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\n vec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\n vec3 color = c * cos(shift * vUV.y);\n float luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\n\n gl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\n}",
  11712. 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}",
  11713. grassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform vec3 herb1Color;\nuniform vec3 herb2Color;\nuniform vec3 herb3Color;\nuniform vec3 groundColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n vec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\n color = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\n color = mix(color, herb3Color, rand(gl_FragCoord.xy));\n color = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\n gl_FragColor = vec4(color, 1.0);\n}",
  11714. 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}",
  11715. 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}",
  11716. legacydefaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_PROJECTION 4.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return 0.;\n }\n return 1.;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW;\n if (lightData.w == 0.)\n {\n lightVectorW = normalize(lightData.xyz - vPositionW);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\n result[0] = ndl * diffuseColor.rgb;\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = ndl * spotAtten * diffuseColor.rgb;\n result[1] = specComp * specularColor * spotAtten;\n result[2] = vec3(0.);\n\n return result;\n }\n\n result[0] = vec3(0.);\n result[1] = vec3(0.);\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\n mat3 result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = mix(groundColor, diffuseColor.rgb, ndl);\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n mat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\n mat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n mat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  11717. legacydefaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return position;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n finalWorld = world;\n#endif\n\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef REFLECTION\n vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}",
  11718. 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}",
  11719. 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}",
  11720. marblePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfTilesHeight;\nuniform float numberOfTilesWidth;\nuniform float amplitude;\nuniform vec3 brickColor;\nuniform vec3 jointColor;\n\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat turbulence(vec2 P)\n{\n float val = 0.0;\n float freq = 1.0;\n for (int i = 0; i < 4; i++)\n {\n val += abs(noise(P*freq) / freq);\n freq *= 2.07;\n }\n return val;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\nvec3 marble_color(float x)\n{\n vec3 col;\n x = 0.5*(x + 1.);\n x = sqrt(x); \n x = sqrt(x);\n x = sqrt(x);\n col = vec3(.2 + .75*x); \n col.b *= 0.95; \n return col;\n}\n\nvoid main()\n{\n float brickW = 1.0 / numberOfTilesWidth;\n float brickH = 1.0 / numberOfTilesHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.01;\n vec3 color = brickColor;\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n }\n else if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\n color = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n }\n else {\n float t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\n t += amplitude * turbulence(brickvUV.xy);\n t = sin(t);\n color = marble_color(t);\n }\n\n gl_FragColor = vec4(color, 0.0);\n}",
  11721. 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}",
  11722. outlinePixelShader:"precision highp float;\n\nuniform vec4 color;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void) {\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n gl_FragColor = color;\n}",
  11723. 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}",
  11724. 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}",
  11725. 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}",
  11726. 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}",
  11727. 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}",
  11728. 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}",
  11729. 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}",
  11730. roadPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV; \nuniform vec3 roadColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n float ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\n vec3 color = roadColor * ratioy;\n gl_FragColor = vec4(color, 1.0);\n}",
  11731. 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}",
  11732. 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}",
  11733. 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}",
  11734. 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}",
  11735. woodPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float ampScale;\nuniform vec3 woodColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n float ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\n vec3 wood = woodColor * ratioy;\n gl_FragColor = vec4(wood, 1.0);\n}",
  11736. };
  11737. return Effect;
  11738. })();
  11739. BABYLON.Effect = Effect;
  11740. })(BABYLON || (BABYLON = {}));
  11741. var BABYLON;
  11742. (function (BABYLON) {
  11743. var Material = (function () {
  11744. function Material(name, scene, doNotAdd) {
  11745. this.name = name;
  11746. this.checkReadyOnEveryCall = true;
  11747. this.checkReadyOnlyOnce = false;
  11748. this.state = "";
  11749. this.alpha = 1.0;
  11750. this.backFaceCulling = true;
  11751. this._wasPreviouslyReady = false;
  11752. this._fillMode = Material.TriangleFillMode;
  11753. this.pointSize = 1.0;
  11754. this.id = name;
  11755. this._scene = scene;
  11756. if (!doNotAdd) {
  11757. scene.materials.push(this);
  11758. }
  11759. }
  11760. Object.defineProperty(Material, "TriangleFillMode", {
  11761. get: function () {
  11762. return Material._TriangleFillMode;
  11763. },
  11764. enumerable: true,
  11765. configurable: true
  11766. });
  11767. Object.defineProperty(Material, "WireFrameFillMode", {
  11768. get: function () {
  11769. return Material._WireFrameFillMode;
  11770. },
  11771. enumerable: true,
  11772. configurable: true
  11773. });
  11774. Object.defineProperty(Material, "PointFillMode", {
  11775. get: function () {
  11776. return Material._PointFillMode;
  11777. },
  11778. enumerable: true,
  11779. configurable: true
  11780. });
  11781. Object.defineProperty(Material.prototype, "wireframe", {
  11782. get: function () {
  11783. return this._fillMode === Material.WireFrameFillMode;
  11784. },
  11785. set: function (value) {
  11786. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  11787. },
  11788. enumerable: true,
  11789. configurable: true
  11790. });
  11791. Object.defineProperty(Material.prototype, "pointsCloud", {
  11792. get: function () {
  11793. return this._fillMode === Material.PointFillMode;
  11794. },
  11795. set: function (value) {
  11796. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  11797. },
  11798. enumerable: true,
  11799. configurable: true
  11800. });
  11801. Object.defineProperty(Material.prototype, "fillMode", {
  11802. get: function () {
  11803. return this._fillMode;
  11804. },
  11805. set: function (value) {
  11806. this._fillMode = value;
  11807. },
  11808. enumerable: true,
  11809. configurable: true
  11810. });
  11811. Material.prototype.isReady = function (mesh, useInstances) {
  11812. return true;
  11813. };
  11814. Material.prototype.getEffect = function () {
  11815. return this._effect;
  11816. };
  11817. Material.prototype.getScene = function () {
  11818. return this._scene;
  11819. };
  11820. Material.prototype.needAlphaBlending = function () {
  11821. return (this.alpha < 1.0);
  11822. };
  11823. Material.prototype.needAlphaTesting = function () {
  11824. return false;
  11825. };
  11826. Material.prototype.getAlphaTestTexture = function () {
  11827. return null;
  11828. };
  11829. Material.prototype.trackCreation = function (onCompiled, onError) {
  11830. };
  11831. Material.prototype._preBind = function () {
  11832. var engine = this._scene.getEngine();
  11833. engine.enableEffect(this._effect);
  11834. engine.setState(this.backFaceCulling);
  11835. };
  11836. Material.prototype.bind = function (world, mesh) {
  11837. this._scene._cachedMaterial = this;
  11838. if (this.onBind) {
  11839. this.onBind(this);
  11840. }
  11841. };
  11842. Material.prototype.bindOnlyWorldMatrix = function (world) {
  11843. };
  11844. Material.prototype.unbind = function () {
  11845. };
  11846. Material.prototype.dispose = function (forceDisposeEffect) {
  11847. var index = this._scene.materials.indexOf(this);
  11848. this._scene.materials.splice(index, 1);
  11849. if (forceDisposeEffect && this._effect) {
  11850. this._scene.getEngine()._releaseEffect(this._effect);
  11851. this._effect = null;
  11852. }
  11853. if (this.onDispose) {
  11854. this.onDispose();
  11855. }
  11856. };
  11857. Material._TriangleFillMode = 0;
  11858. Material._WireFrameFillMode = 1;
  11859. Material._PointFillMode = 2;
  11860. return Material;
  11861. })();
  11862. BABYLON.Material = Material;
  11863. })(BABYLON || (BABYLON = {}));
  11864. var __extends = this.__extends || function (d, b) {
  11865. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11866. function __() { this.constructor = d; }
  11867. __.prototype = b.prototype;
  11868. d.prototype = new __();
  11869. };
  11870. var BABYLON;
  11871. (function (BABYLON) {
  11872. var maxSimultaneousLights = 4;
  11873. var FresnelParameters = (function () {
  11874. function FresnelParameters() {
  11875. this.isEnabled = true;
  11876. this.leftColor = BABYLON.Color3.White();
  11877. this.rightColor = BABYLON.Color3.Black();
  11878. this.bias = 0;
  11879. this.power = 1;
  11880. }
  11881. return FresnelParameters;
  11882. })();
  11883. BABYLON.FresnelParameters = FresnelParameters;
  11884. var StandardMaterial = (function (_super) {
  11885. __extends(StandardMaterial, _super);
  11886. function StandardMaterial(name, scene) {
  11887. var _this = this;
  11888. _super.call(this, name, scene);
  11889. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11890. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  11891. this.specularColor = new BABYLON.Color3(1, 1, 1);
  11892. this.specularPower = 64;
  11893. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  11894. this.useAlphaFromDiffuseTexture = false;
  11895. this.useSpecularOverAlpha = true;
  11896. this.fogEnabled = true;
  11897. this._cachedDefines = null;
  11898. this._renderTargets = new BABYLON.SmartArray(16);
  11899. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  11900. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  11901. this._scaledDiffuse = new BABYLON.Color3();
  11902. this._scaledSpecular = new BABYLON.Color3();
  11903. this.getRenderTargetTextures = function () {
  11904. _this._renderTargets.reset();
  11905. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  11906. _this._renderTargets.push(_this.reflectionTexture);
  11907. }
  11908. return _this._renderTargets;
  11909. };
  11910. }
  11911. StandardMaterial.prototype.needAlphaBlending = function () {
  11912. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  11913. };
  11914. StandardMaterial.prototype.needAlphaTesting = function () {
  11915. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  11916. };
  11917. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  11918. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  11919. };
  11920. StandardMaterial.prototype.getAlphaTestTexture = function () {
  11921. return this.diffuseTexture;
  11922. };
  11923. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  11924. if (this.checkReadyOnlyOnce) {
  11925. if (this._wasPreviouslyReady) {
  11926. return true;
  11927. }
  11928. }
  11929. var scene = this.getScene();
  11930. if (!this.checkReadyOnEveryCall) {
  11931. if (this._renderId === scene.getRenderId()) {
  11932. return true;
  11933. }
  11934. }
  11935. var engine = scene.getEngine();
  11936. var defines = [];
  11937. var fallbacks = new BABYLON.EffectFallbacks();
  11938. if (scene.texturesEnabled) {
  11939. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  11940. if (!this.diffuseTexture.isReady()) {
  11941. return false;
  11942. } else {
  11943. defines.push("#define DIFFUSE");
  11944. }
  11945. }
  11946. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  11947. if (!this.ambientTexture.isReady()) {
  11948. return false;
  11949. } else {
  11950. defines.push("#define AMBIENT");
  11951. }
  11952. }
  11953. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  11954. if (!this.opacityTexture.isReady()) {
  11955. return false;
  11956. } else {
  11957. defines.push("#define OPACITY");
  11958. if (this.opacityTexture.getAlphaFromRGB) {
  11959. defines.push("#define OPACITYRGB");
  11960. }
  11961. }
  11962. }
  11963. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  11964. if (!this.reflectionTexture.isReady()) {
  11965. return false;
  11966. } else {
  11967. defines.push("#define REFLECTION");
  11968. fallbacks.addFallback(0, "REFLECTION");
  11969. }
  11970. }
  11971. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  11972. if (!this.emissiveTexture.isReady()) {
  11973. return false;
  11974. } else {
  11975. defines.push("#define EMISSIVE");
  11976. }
  11977. }
  11978. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  11979. if (!this.specularTexture.isReady()) {
  11980. return false;
  11981. } else {
  11982. defines.push("#define SPECULAR");
  11983. fallbacks.addFallback(0, "SPECULAR");
  11984. }
  11985. }
  11986. }
  11987. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  11988. if (!this.bumpTexture.isReady()) {
  11989. return false;
  11990. } else {
  11991. defines.push("#define BUMP");
  11992. fallbacks.addFallback(0, "BUMP");
  11993. }
  11994. }
  11995. if (this.useSpecularOverAlpha) {
  11996. defines.push("#define SPECULAROVERALPHA");
  11997. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  11998. }
  11999. if (scene.clipPlane) {
  12000. defines.push("#define CLIPPLANE");
  12001. }
  12002. if (engine.getAlphaTesting()) {
  12003. defines.push("#define ALPHATEST");
  12004. }
  12005. if (this._shouldUseAlphaFromDiffuseTexture()) {
  12006. defines.push("#define ALPHAFROMDIFFUSE");
  12007. }
  12008. if (this.pointsCloud || scene.forcePointsCloud) {
  12009. defines.push("#define POINTSIZE");
  12010. }
  12011. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12012. defines.push("#define FOG");
  12013. fallbacks.addFallback(1, "FOG");
  12014. }
  12015. var shadowsActivated = false;
  12016. var lightIndex = 0;
  12017. if (scene.lightsEnabled) {
  12018. for (var index = 0; index < scene.lights.length; index++) {
  12019. var light = scene.lights[index];
  12020. if (!light.isEnabled()) {
  12021. continue;
  12022. }
  12023. if (light._excludedMeshesIds.length > 0) {
  12024. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  12025. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  12026. if (excludedMesh) {
  12027. light.excludedMeshes.push(excludedMesh);
  12028. }
  12029. }
  12030. light._excludedMeshesIds = [];
  12031. }
  12032. if (light._includedOnlyMeshesIds.length > 0) {
  12033. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  12034. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  12035. if (includedOnlyMesh) {
  12036. light.includedOnlyMeshes.push(includedOnlyMesh);
  12037. }
  12038. }
  12039. light._includedOnlyMeshesIds = [];
  12040. }
  12041. if (!light.canAffectMesh(mesh)) {
  12042. continue;
  12043. }
  12044. defines.push("#define LIGHT" + lightIndex);
  12045. if (lightIndex > 0) {
  12046. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  12047. }
  12048. var type;
  12049. if (light instanceof BABYLON.SpotLight) {
  12050. type = "#define SPOTLIGHT" + lightIndex;
  12051. } else if (light instanceof BABYLON.HemisphericLight) {
  12052. type = "#define HEMILIGHT" + lightIndex;
  12053. } else {
  12054. type = "#define POINTDIRLIGHT" + lightIndex;
  12055. }
  12056. defines.push(type);
  12057. if (lightIndex > 0) {
  12058. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  12059. }
  12060. if (scene.shadowsEnabled) {
  12061. var shadowGenerator = light.getShadowGenerator();
  12062. if (mesh && mesh.receiveShadows && shadowGenerator) {
  12063. defines.push("#define SHADOW" + lightIndex);
  12064. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  12065. if (!shadowsActivated) {
  12066. defines.push("#define SHADOWS");
  12067. shadowsActivated = true;
  12068. }
  12069. if (shadowGenerator.useVarianceShadowMap) {
  12070. defines.push("#define SHADOWVSM" + lightIndex);
  12071. if (lightIndex > 0) {
  12072. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  12073. }
  12074. }
  12075. if (shadowGenerator.usePoissonSampling) {
  12076. defines.push("#define SHADOWPCF" + lightIndex);
  12077. if (lightIndex > 0) {
  12078. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  12079. }
  12080. }
  12081. }
  12082. }
  12083. lightIndex++;
  12084. if (lightIndex === maxSimultaneousLights)
  12085. break;
  12086. }
  12087. }
  12088. if (StandardMaterial.FresnelEnabled) {
  12089. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12090. var fresnelRank = 1;
  12091. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  12092. defines.push("#define DIFFUSEFRESNEL");
  12093. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  12094. fresnelRank++;
  12095. }
  12096. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  12097. defines.push("#define OPACITYFRESNEL");
  12098. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  12099. fresnelRank++;
  12100. }
  12101. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12102. defines.push("#define REFLECTIONFRESNEL");
  12103. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  12104. fresnelRank++;
  12105. }
  12106. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  12107. defines.push("#define EMISSIVEFRESNEL");
  12108. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  12109. fresnelRank++;
  12110. }
  12111. defines.push("#define FRESNEL");
  12112. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  12113. }
  12114. }
  12115. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  12116. if (mesh) {
  12117. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12118. attribs.push(BABYLON.VertexBuffer.UVKind);
  12119. defines.push("#define UV1");
  12120. }
  12121. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  12122. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  12123. defines.push("#define UV2");
  12124. }
  12125. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  12126. attribs.push(BABYLON.VertexBuffer.ColorKind);
  12127. defines.push("#define VERTEXCOLOR");
  12128. if (mesh.hasVertexAlpha) {
  12129. defines.push("#define VERTEXALPHA");
  12130. }
  12131. }
  12132. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  12133. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  12134. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  12135. defines.push("#define BONES");
  12136. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  12137. defines.push("#define BONES4");
  12138. fallbacks.addFallback(0, "BONES4");
  12139. }
  12140. if (useInstances) {
  12141. defines.push("#define INSTANCES");
  12142. attribs.push("world0");
  12143. attribs.push("world1");
  12144. attribs.push("world2");
  12145. attribs.push("world3");
  12146. }
  12147. }
  12148. var join = defines.join("\n");
  12149. if (this._cachedDefines !== join) {
  12150. this._cachedDefines = join;
  12151. scene.resetCachedMaterial();
  12152. var shaderName = "default";
  12153. if (!scene.getEngine().getCaps().standardDerivatives) {
  12154. shaderName = "legacydefault";
  12155. }
  12156. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  12157. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  12158. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  12159. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  12160. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  12161. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  12162. "vFogInfos", "vFogColor", "pointSize",
  12163. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  12164. "mBones",
  12165. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  12166. "darkness0", "darkness1", "darkness2", "darkness3",
  12167. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  12168. ], [
  12169. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  12170. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  12171. ], join, fallbacks, this.onCompiled, this.onError);
  12172. }
  12173. if (!this._effect.isReady()) {
  12174. return false;
  12175. }
  12176. this._renderId = scene.getRenderId();
  12177. this._wasPreviouslyReady = true;
  12178. return true;
  12179. };
  12180. StandardMaterial.prototype.unbind = function () {
  12181. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  12182. this._effect.setTexture("reflection2DSampler", null);
  12183. }
  12184. };
  12185. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  12186. this._effect.setMatrix("world", world);
  12187. };
  12188. StandardMaterial.prototype.bind = function (world, mesh) {
  12189. var scene = this.getScene();
  12190. this.bindOnlyWorldMatrix(world);
  12191. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  12192. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  12193. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  12194. }
  12195. if (scene.getCachedMaterial() !== this) {
  12196. if (StandardMaterial.FresnelEnabled) {
  12197. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  12198. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  12199. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  12200. }
  12201. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  12202. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  12203. }
  12204. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12205. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  12206. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  12207. }
  12208. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  12209. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  12210. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  12211. }
  12212. }
  12213. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  12214. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  12215. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  12216. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  12217. }
  12218. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  12219. this._effect.setTexture("ambientSampler", this.ambientTexture);
  12220. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  12221. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  12222. }
  12223. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  12224. this._effect.setTexture("opacitySampler", this.opacityTexture);
  12225. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  12226. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  12227. }
  12228. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  12229. if (this.reflectionTexture.isCube) {
  12230. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  12231. } else {
  12232. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  12233. }
  12234. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  12235. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  12236. }
  12237. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  12238. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  12239. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  12240. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  12241. }
  12242. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  12243. this._effect.setTexture("specularSampler", this.specularTexture);
  12244. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  12245. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  12246. }
  12247. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  12248. this._effect.setTexture("bumpSampler", this.bumpTexture);
  12249. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  12250. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  12251. }
  12252. if (scene.clipPlane) {
  12253. var clipPlane = scene.clipPlane;
  12254. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  12255. }
  12256. if (this.pointsCloud) {
  12257. this._effect.setFloat("pointSize", this.pointSize);
  12258. }
  12259. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  12260. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  12261. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  12262. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  12263. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  12264. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  12265. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  12266. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  12267. }
  12268. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  12269. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  12270. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  12271. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  12272. if (scene.lightsEnabled) {
  12273. var lightIndex = 0;
  12274. for (var index = 0; index < scene.lights.length; index++) {
  12275. var light = scene.lights[index];
  12276. if (!light.isEnabled()) {
  12277. continue;
  12278. }
  12279. if (!light.canAffectMesh(mesh)) {
  12280. continue;
  12281. }
  12282. if (light instanceof BABYLON.PointLight) {
  12283. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  12284. } else if (light instanceof BABYLON.DirectionalLight) {
  12285. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  12286. } else if (light instanceof BABYLON.SpotLight) {
  12287. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  12288. } else if (light instanceof BABYLON.HemisphericLight) {
  12289. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  12290. }
  12291. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  12292. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  12293. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  12294. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  12295. if (scene.shadowsEnabled) {
  12296. var shadowGenerator = light.getShadowGenerator();
  12297. if (mesh.receiveShadows && shadowGenerator) {
  12298. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  12299. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  12300. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  12301. }
  12302. }
  12303. lightIndex++;
  12304. if (lightIndex === maxSimultaneousLights)
  12305. break;
  12306. }
  12307. }
  12308. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  12309. this._effect.setMatrix("view", scene.getViewMatrix());
  12310. }
  12311. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  12312. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  12313. this._effect.setColor3("vFogColor", scene.fogColor);
  12314. }
  12315. _super.prototype.bind.call(this, world, mesh);
  12316. };
  12317. StandardMaterial.prototype.getAnimatables = function () {
  12318. var results = [];
  12319. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  12320. results.push(this.diffuseTexture);
  12321. }
  12322. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  12323. results.push(this.ambientTexture);
  12324. }
  12325. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  12326. results.push(this.opacityTexture);
  12327. }
  12328. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  12329. results.push(this.reflectionTexture);
  12330. }
  12331. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  12332. results.push(this.emissiveTexture);
  12333. }
  12334. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  12335. results.push(this.specularTexture);
  12336. }
  12337. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  12338. results.push(this.bumpTexture);
  12339. }
  12340. return results;
  12341. };
  12342. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  12343. if (this.diffuseTexture) {
  12344. this.diffuseTexture.dispose();
  12345. }
  12346. if (this.ambientTexture) {
  12347. this.ambientTexture.dispose();
  12348. }
  12349. if (this.opacityTexture) {
  12350. this.opacityTexture.dispose();
  12351. }
  12352. if (this.reflectionTexture) {
  12353. this.reflectionTexture.dispose();
  12354. }
  12355. if (this.emissiveTexture) {
  12356. this.emissiveTexture.dispose();
  12357. }
  12358. if (this.specularTexture) {
  12359. this.specularTexture.dispose();
  12360. }
  12361. if (this.bumpTexture) {
  12362. this.bumpTexture.dispose();
  12363. }
  12364. _super.prototype.dispose.call(this, forceDisposeEffect);
  12365. };
  12366. StandardMaterial.prototype.clone = function (name) {
  12367. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  12368. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  12369. newStandardMaterial.alpha = this.alpha;
  12370. newStandardMaterial.fillMode = this.fillMode;
  12371. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  12372. if (this.diffuseTexture && this.diffuseTexture.clone) {
  12373. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  12374. }
  12375. if (this.ambientTexture && this.ambientTexture.clone) {
  12376. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  12377. }
  12378. if (this.opacityTexture && this.opacityTexture.clone) {
  12379. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  12380. }
  12381. if (this.reflectionTexture && this.reflectionTexture.clone) {
  12382. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  12383. }
  12384. if (this.emissiveTexture && this.emissiveTexture.clone) {
  12385. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  12386. }
  12387. if (this.specularTexture && this.specularTexture.clone) {
  12388. newStandardMaterial.specularTexture = this.specularTexture.clone();
  12389. }
  12390. if (this.bumpTexture && this.bumpTexture.clone) {
  12391. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  12392. }
  12393. newStandardMaterial.ambientColor = this.ambientColor.clone();
  12394. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  12395. newStandardMaterial.specularColor = this.specularColor.clone();
  12396. newStandardMaterial.specularPower = this.specularPower;
  12397. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  12398. return newStandardMaterial;
  12399. };
  12400. StandardMaterial.DiffuseTextureEnabled = true;
  12401. StandardMaterial.AmbientTextureEnabled = true;
  12402. StandardMaterial.OpacityTextureEnabled = true;
  12403. StandardMaterial.ReflectionTextureEnabled = true;
  12404. StandardMaterial.EmissiveTextureEnabled = true;
  12405. StandardMaterial.SpecularTextureEnabled = true;
  12406. StandardMaterial.BumpTextureEnabled = true;
  12407. StandardMaterial.FresnelEnabled = true;
  12408. return StandardMaterial;
  12409. })(BABYLON.Material);
  12410. BABYLON.StandardMaterial = StandardMaterial;
  12411. })(BABYLON || (BABYLON = {}));
  12412. var __extends = this.__extends || function (d, b) {
  12413. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12414. function __() { this.constructor = d; }
  12415. __.prototype = b.prototype;
  12416. d.prototype = new __();
  12417. };
  12418. var BABYLON;
  12419. (function (BABYLON) {
  12420. var MultiMaterial = (function (_super) {
  12421. __extends(MultiMaterial, _super);
  12422. function MultiMaterial(name, scene) {
  12423. _super.call(this, name, scene, true);
  12424. this.subMaterials = new Array();
  12425. scene.multiMaterials.push(this);
  12426. }
  12427. MultiMaterial.prototype.getSubMaterial = function (index) {
  12428. if (index < 0 || index >= this.subMaterials.length) {
  12429. return this.getScene().defaultMaterial;
  12430. }
  12431. return this.subMaterials[index];
  12432. };
  12433. MultiMaterial.prototype.isReady = function (mesh) {
  12434. for (var index = 0; index < this.subMaterials.length; index++) {
  12435. var subMaterial = this.subMaterials[index];
  12436. if (subMaterial) {
  12437. if (!this.subMaterials[index].isReady(mesh)) {
  12438. return false;
  12439. }
  12440. }
  12441. }
  12442. return true;
  12443. };
  12444. return MultiMaterial;
  12445. })(BABYLON.Material);
  12446. BABYLON.MultiMaterial = MultiMaterial;
  12447. })(BABYLON || (BABYLON = {}));
  12448. var BABYLON;
  12449. (function (BABYLON) {
  12450. var Database = (function () {
  12451. function Database(urlToScene, callbackManifestChecked) {
  12452. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  12453. this.callbackManifestChecked = callbackManifestChecked;
  12454. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  12455. this.db = null;
  12456. this.enableSceneOffline = false;
  12457. this.enableTexturesOffline = false;
  12458. this.manifestVersionFound = 0;
  12459. this.mustUpdateRessources = false;
  12460. this.hasReachedQuota = false;
  12461. this.checkManifestFile();
  12462. }
  12463. Database.prototype.checkManifestFile = function () {
  12464. var _this = this;
  12465. function noManifestFile() {
  12466. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  12467. that.enableSceneOffline = false;
  12468. that.enableTexturesOffline = false;
  12469. that.callbackManifestChecked(false);
  12470. }
  12471. var that = this;
  12472. var manifestURL = this.currentSceneUrl + ".manifest";
  12473. var xhr = new XMLHttpRequest();
  12474. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  12475. xhr.open("GET", manifestURLTimeStamped, true);
  12476. xhr.addEventListener("load", function () {
  12477. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  12478. try {
  12479. var manifestFile = JSON.parse(xhr.response);
  12480. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  12481. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  12482. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  12483. _this.manifestVersionFound = manifestFile.version;
  12484. }
  12485. if (_this.callbackManifestChecked) {
  12486. _this.callbackManifestChecked(true);
  12487. }
  12488. } catch (ex) {
  12489. noManifestFile();
  12490. }
  12491. } else {
  12492. noManifestFile();
  12493. }
  12494. }, false);
  12495. xhr.addEventListener("error", function (event) {
  12496. noManifestFile();
  12497. }, false);
  12498. try {
  12499. xhr.send();
  12500. } catch (ex) {
  12501. BABYLON.Tools.Error("Error on XHR send request.");
  12502. that.callbackManifestChecked(false);
  12503. }
  12504. };
  12505. Database.prototype.openAsync = function (successCallback, errorCallback) {
  12506. var _this = this;
  12507. function handleError() {
  12508. that.isSupported = false;
  12509. if (errorCallback)
  12510. errorCallback();
  12511. }
  12512. var that = this;
  12513. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  12514. this.isSupported = false;
  12515. if (errorCallback)
  12516. errorCallback();
  12517. } else {
  12518. if (!this.db) {
  12519. this.hasReachedQuota = false;
  12520. this.isSupported = true;
  12521. var request = this.idbFactory.open("babylonjs", 1);
  12522. request.onerror = function (event) {
  12523. handleError();
  12524. };
  12525. request.onblocked = function (event) {
  12526. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  12527. handleError();
  12528. };
  12529. request.onsuccess = function (event) {
  12530. _this.db = request.result;
  12531. successCallback();
  12532. };
  12533. request.onupgradeneeded = function (event) {
  12534. _this.db = (event.target).result;
  12535. try {
  12536. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  12537. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  12538. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  12539. } catch (ex) {
  12540. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  12541. handleError();
  12542. }
  12543. };
  12544. } else {
  12545. if (successCallback)
  12546. successCallback();
  12547. }
  12548. }
  12549. };
  12550. Database.prototype.loadImageFromDB = function (url, image) {
  12551. var _this = this;
  12552. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  12553. var saveAndLoadImage = function () {
  12554. if (!_this.hasReachedQuota && _this.db !== null) {
  12555. _this._saveImageIntoDBAsync(completeURL, image);
  12556. } else {
  12557. image.src = url;
  12558. }
  12559. };
  12560. if (!this.mustUpdateRessources) {
  12561. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  12562. } else {
  12563. saveAndLoadImage();
  12564. }
  12565. };
  12566. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  12567. if (this.isSupported && this.db !== null) {
  12568. var texture;
  12569. var transaction = this.db.transaction(["textures"]);
  12570. transaction.onabort = function (event) {
  12571. image.src = url;
  12572. };
  12573. transaction.oncomplete = function (event) {
  12574. var blobTextureURL;
  12575. if (texture) {
  12576. var URL = window.URL || window.webkitURL;
  12577. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  12578. image.onerror = function () {
  12579. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  12580. image.src = url;
  12581. };
  12582. image.src = blobTextureURL;
  12583. } else {
  12584. notInDBCallback();
  12585. }
  12586. };
  12587. var getRequest = transaction.objectStore("textures").get(url);
  12588. getRequest.onsuccess = function (event) {
  12589. texture = (event.target).result;
  12590. };
  12591. getRequest.onerror = function (event) {
  12592. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  12593. image.src = url;
  12594. };
  12595. } else {
  12596. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12597. image.src = url;
  12598. }
  12599. };
  12600. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  12601. var _this = this;
  12602. if (this.isSupported) {
  12603. var generateBlobUrl = function () {
  12604. var blobTextureURL;
  12605. if (blob) {
  12606. var URL = window.URL || window.webkitURL;
  12607. try {
  12608. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  12609. } catch (ex) {
  12610. blobTextureURL = URL.createObjectURL(blob);
  12611. }
  12612. }
  12613. image.src = blobTextureURL;
  12614. };
  12615. if (BABYLON.Database.isUASupportingBlobStorage) {
  12616. var xhr = new XMLHttpRequest(), blob;
  12617. xhr.open("GET", url, true);
  12618. xhr.responseType = "blob";
  12619. xhr.addEventListener("load", function () {
  12620. if (xhr.status === 200) {
  12621. blob = xhr.response;
  12622. var transaction = _this.db.transaction(["textures"], "readwrite");
  12623. transaction.onabort = function (event) {
  12624. try {
  12625. if (event.srcElement.error.name === "QuotaExceededError") {
  12626. this.hasReachedQuota = true;
  12627. }
  12628. } catch (ex) {
  12629. }
  12630. generateBlobUrl();
  12631. };
  12632. transaction.oncomplete = function (event) {
  12633. generateBlobUrl();
  12634. };
  12635. var newTexture = { textureUrl: url, data: blob };
  12636. try {
  12637. var addRequest = transaction.objectStore("textures").put(newTexture);
  12638. addRequest.onsuccess = function (event) {
  12639. };
  12640. addRequest.onerror = function (event) {
  12641. generateBlobUrl();
  12642. };
  12643. } catch (ex) {
  12644. if (ex.code === 25) {
  12645. BABYLON.Database.isUASupportingBlobStorage = false;
  12646. }
  12647. image.src = url;
  12648. }
  12649. } else {
  12650. image.src = url;
  12651. }
  12652. }, false);
  12653. xhr.addEventListener("error", function (event) {
  12654. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  12655. image.src = url;
  12656. }, false);
  12657. xhr.send();
  12658. } else {
  12659. image.src = url;
  12660. }
  12661. } else {
  12662. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12663. image.src = url;
  12664. }
  12665. };
  12666. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  12667. var _this = this;
  12668. var updateVersion = function (event) {
  12669. _this._saveVersionIntoDBAsync(url, versionLoaded);
  12670. };
  12671. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  12672. };
  12673. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  12674. var _this = this;
  12675. if (this.isSupported) {
  12676. var version;
  12677. try {
  12678. var transaction = this.db.transaction(["versions"]);
  12679. transaction.oncomplete = function (event) {
  12680. if (version) {
  12681. if (_this.manifestVersionFound > version.data) {
  12682. _this.mustUpdateRessources = true;
  12683. updateInDBCallback();
  12684. } else {
  12685. callback(version.data);
  12686. }
  12687. } else {
  12688. _this.mustUpdateRessources = true;
  12689. updateInDBCallback();
  12690. }
  12691. };
  12692. transaction.onabort = function (event) {
  12693. callback(-1);
  12694. };
  12695. var getRequest = transaction.objectStore("versions").get(url);
  12696. getRequest.onsuccess = function (event) {
  12697. version = (event.target).result;
  12698. };
  12699. getRequest.onerror = function (event) {
  12700. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  12701. callback(-1);
  12702. };
  12703. } catch (ex) {
  12704. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  12705. callback(-1);
  12706. }
  12707. } else {
  12708. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12709. callback(-1);
  12710. }
  12711. };
  12712. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  12713. var _this = this;
  12714. if (this.isSupported && !this.hasReachedQuota) {
  12715. try {
  12716. var transaction = this.db.transaction(["versions"], "readwrite");
  12717. transaction.onabort = function (event) {
  12718. try {
  12719. if (event.srcElement.error.name === "QuotaExceededError") {
  12720. _this.hasReachedQuota = true;
  12721. }
  12722. } catch (ex) {
  12723. }
  12724. callback(-1);
  12725. };
  12726. transaction.oncomplete = function (event) {
  12727. callback(_this.manifestVersionFound);
  12728. };
  12729. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  12730. var addRequest = transaction.objectStore("versions").put(newVersion);
  12731. addRequest.onsuccess = function (event) {
  12732. };
  12733. addRequest.onerror = function (event) {
  12734. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  12735. };
  12736. } catch (ex) {
  12737. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  12738. callback(-1);
  12739. }
  12740. } else {
  12741. callback(-1);
  12742. }
  12743. };
  12744. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  12745. var _this = this;
  12746. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  12747. var saveAndLoadFile = function (event) {
  12748. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  12749. };
  12750. this._checkVersionFromDB(completeUrl, function (version) {
  12751. if (version !== -1) {
  12752. if (!_this.mustUpdateRessources) {
  12753. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  12754. } else {
  12755. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  12756. }
  12757. } else {
  12758. errorCallback();
  12759. }
  12760. });
  12761. };
  12762. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  12763. if (this.isSupported) {
  12764. var targetStore;
  12765. if (url.indexOf(".babylon") !== -1) {
  12766. targetStore = "scenes";
  12767. } else {
  12768. targetStore = "textures";
  12769. }
  12770. var file;
  12771. var transaction = this.db.transaction([targetStore]);
  12772. transaction.oncomplete = function (event) {
  12773. if (file) {
  12774. callback(file.data);
  12775. } else {
  12776. notInDBCallback();
  12777. }
  12778. };
  12779. transaction.onabort = function (event) {
  12780. notInDBCallback();
  12781. };
  12782. var getRequest = transaction.objectStore(targetStore).get(url);
  12783. getRequest.onsuccess = function (event) {
  12784. file = (event.target).result;
  12785. };
  12786. getRequest.onerror = function (event) {
  12787. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  12788. notInDBCallback();
  12789. };
  12790. } else {
  12791. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12792. callback();
  12793. }
  12794. };
  12795. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  12796. var _this = this;
  12797. if (this.isSupported) {
  12798. var targetStore;
  12799. if (url.indexOf(".babylon") !== -1) {
  12800. targetStore = "scenes";
  12801. } else {
  12802. targetStore = "textures";
  12803. }
  12804. var xhr = new XMLHttpRequest(), fileData;
  12805. xhr.open("GET", url, true);
  12806. if (useArrayBuffer) {
  12807. xhr.responseType = "arraybuffer";
  12808. }
  12809. xhr.onprogress = progressCallback;
  12810. xhr.addEventListener("load", function () {
  12811. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  12812. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  12813. if (!_this.hasReachedQuota) {
  12814. var transaction = _this.db.transaction([targetStore], "readwrite");
  12815. transaction.onabort = function (event) {
  12816. try {
  12817. if (event.srcElement.error.name === "QuotaExceededError") {
  12818. this.hasReachedQuota = true;
  12819. }
  12820. } catch (ex) {
  12821. }
  12822. callback(fileData);
  12823. };
  12824. transaction.oncomplete = function (event) {
  12825. callback(fileData);
  12826. };
  12827. var newFile;
  12828. if (targetStore === "scenes") {
  12829. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  12830. } else {
  12831. newFile = { textureUrl: url, data: fileData };
  12832. }
  12833. try {
  12834. var addRequest = transaction.objectStore(targetStore).put(newFile);
  12835. addRequest.onsuccess = function (event) {
  12836. };
  12837. addRequest.onerror = function (event) {
  12838. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  12839. };
  12840. } catch (ex) {
  12841. callback(fileData);
  12842. }
  12843. } else {
  12844. callback(fileData);
  12845. }
  12846. } else {
  12847. callback();
  12848. }
  12849. }, false);
  12850. xhr.addEventListener("error", function (event) {
  12851. BABYLON.Tools.Error("error on XHR request.");
  12852. callback();
  12853. }, false);
  12854. xhr.send();
  12855. } else {
  12856. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12857. callback();
  12858. }
  12859. };
  12860. Database.isUASupportingBlobStorage = true;
  12861. Database.parseURL = function (url) {
  12862. var a = document.createElement('a');
  12863. a.href = url;
  12864. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  12865. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  12866. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  12867. return absLocation;
  12868. };
  12869. Database.ReturnFullUrlLocation = function (url) {
  12870. if (url.indexOf("http:/") === -1) {
  12871. return (BABYLON.Database.parseURL(window.location.href) + url);
  12872. } else {
  12873. return url;
  12874. }
  12875. };
  12876. return Database;
  12877. })();
  12878. BABYLON.Database = Database;
  12879. })(BABYLON || (BABYLON = {}));
  12880. var BABYLON;
  12881. (function (BABYLON) {
  12882. var SpriteManager = (function () {
  12883. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  12884. this.name = name;
  12885. this.cellSize = cellSize;
  12886. this.sprites = new Array();
  12887. this.renderingGroupId = 0;
  12888. this.fogEnabled = true;
  12889. this._vertexDeclaration = [3, 4, 4, 4];
  12890. this._vertexStrideSize = 15 * 4;
  12891. this._capacity = capacity;
  12892. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  12893. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12894. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12895. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  12896. this._scene = scene;
  12897. this._scene.spriteManagers.push(this);
  12898. this._vertexDeclaration = [3, 4, 4, 4];
  12899. this._vertexStrideSize = 15 * 4;
  12900. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  12901. var indices = [];
  12902. var index = 0;
  12903. for (var count = 0; count < capacity; count++) {
  12904. indices.push(index);
  12905. indices.push(index + 1);
  12906. indices.push(index + 2);
  12907. indices.push(index);
  12908. indices.push(index + 2);
  12909. indices.push(index + 3);
  12910. index += 4;
  12911. }
  12912. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12913. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  12914. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  12915. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  12916. }
  12917. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  12918. var arrayOffset = index * 15;
  12919. if (offsetX == 0)
  12920. offsetX = this._epsilon;
  12921. else if (offsetX == 1)
  12922. offsetX = 1 - this._epsilon;
  12923. if (offsetY == 0)
  12924. offsetY = this._epsilon;
  12925. else if (offsetY == 1)
  12926. offsetY = 1 - this._epsilon;
  12927. this._vertices[arrayOffset] = sprite.position.x;
  12928. this._vertices[arrayOffset + 1] = sprite.position.y;
  12929. this._vertices[arrayOffset + 2] = sprite.position.z;
  12930. this._vertices[arrayOffset + 3] = sprite.angle;
  12931. this._vertices[arrayOffset + 4] = sprite.size;
  12932. this._vertices[arrayOffset + 5] = offsetX;
  12933. this._vertices[arrayOffset + 6] = offsetY;
  12934. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  12935. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  12936. var offset = (sprite.cellIndex / rowSize) >> 0;
  12937. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  12938. this._vertices[arrayOffset + 10] = offset;
  12939. this._vertices[arrayOffset + 11] = sprite.color.r;
  12940. this._vertices[arrayOffset + 12] = sprite.color.g;
  12941. this._vertices[arrayOffset + 13] = sprite.color.b;
  12942. this._vertices[arrayOffset + 14] = sprite.color.a;
  12943. };
  12944. SpriteManager.prototype.render = function () {
  12945. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  12946. return;
  12947. var engine = this._scene.getEngine();
  12948. var baseSize = this._spriteTexture.getBaseSize();
  12949. var deltaTime = BABYLON.Tools.GetDeltaTime();
  12950. var max = Math.min(this._capacity, this.sprites.length);
  12951. var rowSize = baseSize.width / this.cellSize;
  12952. var offset = 0;
  12953. for (var index = 0; index < max; index++) {
  12954. var sprite = this.sprites[index];
  12955. if (!sprite) {
  12956. continue;
  12957. }
  12958. sprite._animate(deltaTime);
  12959. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  12960. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  12961. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  12962. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  12963. }
  12964. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  12965. var effect = this._effectBase;
  12966. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12967. effect = this._effectFog;
  12968. }
  12969. engine.enableEffect(effect);
  12970. var viewMatrix = this._scene.getViewMatrix();
  12971. effect.setTexture("diffuseSampler", this._spriteTexture);
  12972. effect.setMatrix("view", viewMatrix);
  12973. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  12974. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  12975. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12976. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  12977. effect.setColor3("vFogColor", this._scene.fogColor);
  12978. }
  12979. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12980. effect.setBool("alphaTest", true);
  12981. engine.setColorWrite(false);
  12982. engine.draw(true, 0, max * 6);
  12983. engine.setColorWrite(true);
  12984. effect.setBool("alphaTest", false);
  12985. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12986. engine.draw(true, 0, max * 6);
  12987. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12988. };
  12989. SpriteManager.prototype.dispose = function () {
  12990. if (this._vertexBuffer) {
  12991. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12992. this._vertexBuffer = null;
  12993. }
  12994. if (this._indexBuffer) {
  12995. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12996. this._indexBuffer = null;
  12997. }
  12998. if (this._spriteTexture) {
  12999. this._spriteTexture.dispose();
  13000. this._spriteTexture = null;
  13001. }
  13002. var index = this._scene.spriteManagers.indexOf(this);
  13003. this._scene.spriteManagers.splice(index, 1);
  13004. if (this.onDispose) {
  13005. this.onDispose();
  13006. }
  13007. };
  13008. return SpriteManager;
  13009. })();
  13010. BABYLON.SpriteManager = SpriteManager;
  13011. })(BABYLON || (BABYLON = {}));
  13012. var BABYLON;
  13013. (function (BABYLON) {
  13014. var Sprite = (function () {
  13015. function Sprite(name, manager) {
  13016. this.name = name;
  13017. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13018. this.size = 1.0;
  13019. this.angle = 0;
  13020. this.cellIndex = 0;
  13021. this.invertU = 0;
  13022. this.invertV = 0;
  13023. this.animations = new Array();
  13024. this._animationStarted = false;
  13025. this._loopAnimation = false;
  13026. this._fromIndex = 0;
  13027. this._toIndex = 0;
  13028. this._delay = 0;
  13029. this._direction = 1;
  13030. this._frameCount = 0;
  13031. this._time = 0;
  13032. this._manager = manager;
  13033. this._manager.sprites.push(this);
  13034. this.position = BABYLON.Vector3.Zero();
  13035. }
  13036. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  13037. this._fromIndex = from;
  13038. this._toIndex = to;
  13039. this._loopAnimation = loop;
  13040. this._delay = delay;
  13041. this._animationStarted = true;
  13042. this._direction = from < to ? 1 : -1;
  13043. this.cellIndex = from;
  13044. this._time = 0;
  13045. };
  13046. Sprite.prototype.stopAnimation = function () {
  13047. this._animationStarted = false;
  13048. };
  13049. Sprite.prototype._animate = function (deltaTime) {
  13050. if (!this._animationStarted)
  13051. return;
  13052. this._time += deltaTime;
  13053. if (this._time > this._delay) {
  13054. this._time = this._time % this._delay;
  13055. this.cellIndex += this._direction;
  13056. if (this.cellIndex == this._toIndex) {
  13057. if (this._loopAnimation) {
  13058. this.cellIndex = this._fromIndex;
  13059. } else {
  13060. this._animationStarted = false;
  13061. if (this.disposeWhenFinishedAnimating) {
  13062. this.dispose();
  13063. }
  13064. }
  13065. }
  13066. }
  13067. };
  13068. Sprite.prototype.dispose = function () {
  13069. for (var i = 0; i < this._manager.sprites.length; i++) {
  13070. if (this._manager.sprites[i] == this) {
  13071. this._manager.sprites.splice(i, 1);
  13072. }
  13073. }
  13074. };
  13075. return Sprite;
  13076. })();
  13077. BABYLON.Sprite = Sprite;
  13078. })(BABYLON || (BABYLON = {}));
  13079. var BABYLON;
  13080. (function (BABYLON) {
  13081. var Layer = (function () {
  13082. function Layer(name, imgUrl, scene, isBackground, color) {
  13083. this.name = name;
  13084. this._vertexDeclaration = [2];
  13085. this._vertexStrideSize = 2 * 4;
  13086. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  13087. this.isBackground = isBackground === undefined ? true : isBackground;
  13088. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  13089. this._scene = scene;
  13090. this._scene.layers.push(this);
  13091. var vertices = [];
  13092. vertices.push(1, 1);
  13093. vertices.push(-1, 1);
  13094. vertices.push(-1, -1);
  13095. vertices.push(1, -1);
  13096. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13097. var indices = [];
  13098. indices.push(0);
  13099. indices.push(1);
  13100. indices.push(2);
  13101. indices.push(0);
  13102. indices.push(2);
  13103. indices.push(3);
  13104. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13105. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  13106. }
  13107. Layer.prototype.render = function () {
  13108. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  13109. return;
  13110. var engine = this._scene.getEngine();
  13111. engine.enableEffect(this._effect);
  13112. engine.setState(false);
  13113. this._effect.setTexture("textureSampler", this.texture);
  13114. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  13115. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  13116. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13117. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13118. engine.draw(true, 0, 6);
  13119. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13120. };
  13121. Layer.prototype.dispose = function () {
  13122. if (this._vertexBuffer) {
  13123. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13124. this._vertexBuffer = null;
  13125. }
  13126. if (this._indexBuffer) {
  13127. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13128. this._indexBuffer = null;
  13129. }
  13130. if (this.texture) {
  13131. this.texture.dispose();
  13132. this.texture = null;
  13133. }
  13134. var index = this._scene.layers.indexOf(this);
  13135. this._scene.layers.splice(index, 1);
  13136. if (this.onDispose) {
  13137. this.onDispose();
  13138. }
  13139. };
  13140. return Layer;
  13141. })();
  13142. BABYLON.Layer = Layer;
  13143. })(BABYLON || (BABYLON = {}));
  13144. var BABYLON;
  13145. (function (BABYLON) {
  13146. var Particle = (function () {
  13147. function Particle() {
  13148. this.position = BABYLON.Vector3.Zero();
  13149. this.direction = BABYLON.Vector3.Zero();
  13150. this.color = new BABYLON.Color4(0, 0, 0, 0);
  13151. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  13152. this.lifeTime = 1.0;
  13153. this.age = 0;
  13154. this.size = 0;
  13155. this.angle = 0;
  13156. this.angularSpeed = 0;
  13157. }
  13158. return Particle;
  13159. })();
  13160. BABYLON.Particle = Particle;
  13161. })(BABYLON || (BABYLON = {}));
  13162. var BABYLON;
  13163. (function (BABYLON) {
  13164. var randomNumber = function (min, max) {
  13165. if (min === max) {
  13166. return (min);
  13167. }
  13168. var random = Math.random();
  13169. return ((random * (max - min)) + min);
  13170. };
  13171. var ParticleSystem = (function () {
  13172. function ParticleSystem(name, capacity, scene, customEffect) {
  13173. var _this = this;
  13174. this.name = name;
  13175. this.renderingGroupId = 0;
  13176. this.emitter = null;
  13177. this.emitRate = 10;
  13178. this.manualEmitCount = -1;
  13179. this.updateSpeed = 0.01;
  13180. this.targetStopDuration = 0;
  13181. this.disposeOnStop = false;
  13182. this.minEmitPower = 1;
  13183. this.maxEmitPower = 1;
  13184. this.minLifeTime = 1;
  13185. this.maxLifeTime = 1;
  13186. this.minSize = 1;
  13187. this.maxSize = 1;
  13188. this.minAngularSpeed = 0;
  13189. this.maxAngularSpeed = 0;
  13190. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  13191. this.forceDepthWrite = false;
  13192. this.gravity = BABYLON.Vector3.Zero();
  13193. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  13194. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  13195. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  13196. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13197. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13198. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13199. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  13200. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13201. this.particles = new Array();
  13202. this._vertexDeclaration = [3, 4, 4];
  13203. this._vertexStrideSize = 11 * 4;
  13204. this._stockParticles = new Array();
  13205. this._newPartsExcess = 0;
  13206. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  13207. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  13208. this._scaledDirection = BABYLON.Vector3.Zero();
  13209. this._scaledGravity = BABYLON.Vector3.Zero();
  13210. this._currentRenderId = -1;
  13211. this._started = false;
  13212. this._stopped = false;
  13213. this._actualFrame = 0;
  13214. this.id = name;
  13215. this._capacity = capacity;
  13216. this._scene = scene;
  13217. this._customEffect = customEffect;
  13218. scene.particleSystems.push(this);
  13219. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  13220. var indices = [];
  13221. var index = 0;
  13222. for (var count = 0; count < capacity; count++) {
  13223. indices.push(index);
  13224. indices.push(index + 1);
  13225. indices.push(index + 2);
  13226. indices.push(index);
  13227. indices.push(index + 2);
  13228. indices.push(index + 3);
  13229. index += 4;
  13230. }
  13231. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13232. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  13233. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  13234. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  13235. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  13236. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  13237. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  13238. };
  13239. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  13240. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  13241. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  13242. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  13243. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  13244. };
  13245. }
  13246. ParticleSystem.prototype.getCapacity = function () {
  13247. return this._capacity;
  13248. };
  13249. ParticleSystem.prototype.isAlive = function () {
  13250. return this._alive;
  13251. };
  13252. ParticleSystem.prototype.isStarted = function () {
  13253. return this._started;
  13254. };
  13255. ParticleSystem.prototype.start = function () {
  13256. this._started = true;
  13257. this._stopped = false;
  13258. this._actualFrame = 0;
  13259. };
  13260. ParticleSystem.prototype.stop = function () {
  13261. this._stopped = true;
  13262. };
  13263. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  13264. var offset = index * 11;
  13265. this._vertices[offset] = particle.position.x;
  13266. this._vertices[offset + 1] = particle.position.y;
  13267. this._vertices[offset + 2] = particle.position.z;
  13268. this._vertices[offset + 3] = particle.color.r;
  13269. this._vertices[offset + 4] = particle.color.g;
  13270. this._vertices[offset + 5] = particle.color.b;
  13271. this._vertices[offset + 6] = particle.color.a;
  13272. this._vertices[offset + 7] = particle.angle;
  13273. this._vertices[offset + 8] = particle.size;
  13274. this._vertices[offset + 9] = offsetX;
  13275. this._vertices[offset + 10] = offsetY;
  13276. };
  13277. ParticleSystem.prototype._update = function (newParticles) {
  13278. this._alive = this.particles.length > 0;
  13279. for (var index = 0; index < this.particles.length; index++) {
  13280. var particle = this.particles[index];
  13281. particle.age += this._scaledUpdateSpeed;
  13282. if (particle.age >= particle.lifeTime) {
  13283. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  13284. index--;
  13285. continue;
  13286. } else {
  13287. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  13288. particle.color.addInPlace(this._scaledColorStep);
  13289. if (particle.color.a < 0)
  13290. particle.color.a = 0;
  13291. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  13292. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  13293. particle.position.addInPlace(this._scaledDirection);
  13294. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  13295. particle.direction.addInPlace(this._scaledGravity);
  13296. }
  13297. }
  13298. if (this.customUpdateFunction) {
  13299. this.customUpdateFunction(this.particles);
  13300. }
  13301. var worldMatrix;
  13302. if (this.emitter.position) {
  13303. worldMatrix = this.emitter.getWorldMatrix();
  13304. } else {
  13305. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  13306. }
  13307. for (index = 0; index < newParticles; index++) {
  13308. if (this.particles.length === this._capacity) {
  13309. break;
  13310. }
  13311. if (this._stockParticles.length !== 0) {
  13312. particle = this._stockParticles.pop();
  13313. particle.age = 0;
  13314. } else {
  13315. particle = new BABYLON.Particle();
  13316. }
  13317. this.particles.push(particle);
  13318. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  13319. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  13320. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  13321. particle.size = randomNumber(this.minSize, this.maxSize);
  13322. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  13323. this.startPositionFunction(worldMatrix, particle.position);
  13324. var step = randomNumber(0, 1.0);
  13325. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  13326. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  13327. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  13328. }
  13329. };
  13330. ParticleSystem.prototype._getEffect = function () {
  13331. if (this._customEffect) {
  13332. return this._customEffect;
  13333. }
  13334. ;
  13335. var defines = [];
  13336. if (this._scene.clipPlane) {
  13337. defines.push("#define CLIPPLANE");
  13338. }
  13339. var join = defines.join("\n");
  13340. if (this._cachedDefines !== join) {
  13341. this._cachedDefines = join;
  13342. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  13343. }
  13344. return this._effect;
  13345. };
  13346. ParticleSystem.prototype.animate = function () {
  13347. if (!this._started)
  13348. return;
  13349. var effect = this._getEffect();
  13350. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  13351. return;
  13352. if (this._currentRenderId === this._scene.getRenderId()) {
  13353. return;
  13354. }
  13355. this._currentRenderId = this._scene.getRenderId();
  13356. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  13357. var emitCout;
  13358. if (this.manualEmitCount > -1) {
  13359. emitCout = this.manualEmitCount;
  13360. this.manualEmitCount = 0;
  13361. } else {
  13362. emitCout = this.emitRate;
  13363. }
  13364. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  13365. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  13366. if (this._newPartsExcess > 1.0) {
  13367. newParticles += this._newPartsExcess >> 0;
  13368. this._newPartsExcess -= this._newPartsExcess >> 0;
  13369. }
  13370. this._alive = false;
  13371. if (!this._stopped) {
  13372. this._actualFrame += this._scaledUpdateSpeed;
  13373. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  13374. this.stop();
  13375. } else {
  13376. newParticles = 0;
  13377. }
  13378. this._update(newParticles);
  13379. if (this._stopped) {
  13380. if (!this._alive) {
  13381. this._started = false;
  13382. if (this.disposeOnStop) {
  13383. this._scene._toBeDisposed.push(this);
  13384. }
  13385. }
  13386. }
  13387. var offset = 0;
  13388. for (var index = 0; index < this.particles.length; index++) {
  13389. var particle = this.particles[index];
  13390. this._appendParticleVertex(offset++, particle, 0, 0);
  13391. this._appendParticleVertex(offset++, particle, 1, 0);
  13392. this._appendParticleVertex(offset++, particle, 1, 1);
  13393. this._appendParticleVertex(offset++, particle, 0, 1);
  13394. }
  13395. var engine = this._scene.getEngine();
  13396. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  13397. };
  13398. ParticleSystem.prototype.render = function () {
  13399. var effect = this._getEffect();
  13400. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  13401. return 0;
  13402. var engine = this._scene.getEngine();
  13403. engine.enableEffect(effect);
  13404. engine.setState(false);
  13405. var viewMatrix = this._scene.getViewMatrix();
  13406. effect.setTexture("diffuseSampler", this.particleTexture);
  13407. effect.setMatrix("view", viewMatrix);
  13408. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  13409. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  13410. if (this._scene.clipPlane) {
  13411. var clipPlane = this._scene.clipPlane;
  13412. var invView = viewMatrix.clone();
  13413. invView.invert();
  13414. effect.setMatrix("invView", invView);
  13415. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  13416. }
  13417. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13418. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  13419. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  13420. } else {
  13421. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13422. }
  13423. if (this.forceDepthWrite) {
  13424. engine.setDepthWrite(true);
  13425. }
  13426. engine.draw(true, 0, this.particles.length * 6);
  13427. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13428. return this.particles.length;
  13429. };
  13430. ParticleSystem.prototype.dispose = function () {
  13431. if (this._vertexBuffer) {
  13432. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13433. this._vertexBuffer = null;
  13434. }
  13435. if (this._indexBuffer) {
  13436. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13437. this._indexBuffer = null;
  13438. }
  13439. if (this.particleTexture) {
  13440. this.particleTexture.dispose();
  13441. this.particleTexture = null;
  13442. }
  13443. var index = this._scene.particleSystems.indexOf(this);
  13444. this._scene.particleSystems.splice(index, 1);
  13445. if (this.onDispose) {
  13446. this.onDispose();
  13447. }
  13448. };
  13449. ParticleSystem.prototype.clone = function (name, newEmitter) {
  13450. var result = new ParticleSystem(name, this._capacity, this._scene);
  13451. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  13452. if (newEmitter === undefined) {
  13453. newEmitter = this.emitter;
  13454. }
  13455. result.emitter = newEmitter;
  13456. if (this.particleTexture) {
  13457. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  13458. }
  13459. result.start();
  13460. return result;
  13461. };
  13462. ParticleSystem.BLENDMODE_ONEONE = 0;
  13463. ParticleSystem.BLENDMODE_STANDARD = 1;
  13464. return ParticleSystem;
  13465. })();
  13466. BABYLON.ParticleSystem = ParticleSystem;
  13467. })(BABYLON || (BABYLON = {}));
  13468. var BABYLON;
  13469. (function (BABYLON) {
  13470. var Animation = (function () {
  13471. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  13472. this.name = name;
  13473. this.targetProperty = targetProperty;
  13474. this.framePerSecond = framePerSecond;
  13475. this.dataType = dataType;
  13476. this.loopMode = loopMode;
  13477. this._offsetsCache = {};
  13478. this._highLimitsCache = {};
  13479. this._stopped = false;
  13480. this.targetPropertyPath = targetProperty.split(".");
  13481. this.dataType = dataType;
  13482. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  13483. }
  13484. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  13485. var dataType = undefined;
  13486. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  13487. dataType = Animation.ANIMATIONTYPE_FLOAT;
  13488. } else if (from instanceof BABYLON.Quaternion) {
  13489. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  13490. } else if (from instanceof BABYLON.Vector3) {
  13491. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  13492. } else if (from instanceof BABYLON.Vector2) {
  13493. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  13494. } else if (from instanceof BABYLON.Color3) {
  13495. dataType = Animation.ANIMATIONTYPE_COLOR3;
  13496. }
  13497. if (dataType == undefined) {
  13498. return;
  13499. }
  13500. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  13501. var keys = [];
  13502. keys.push({ frame: 0, value: from });
  13503. keys.push({ frame: totalFrame, value: to });
  13504. animation.setKeys(keys);
  13505. mesh.animations.push(animation);
  13506. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode == 1));
  13507. };
  13508. Animation.prototype.isStopped = function () {
  13509. return this._stopped;
  13510. };
  13511. Animation.prototype.getKeys = function () {
  13512. return this._keys;
  13513. };
  13514. Animation.prototype.getEasingFunction = function () {
  13515. return this._easingFunction;
  13516. };
  13517. Animation.prototype.setEasingFunction = function (easingFunction) {
  13518. this._easingFunction = easingFunction;
  13519. };
  13520. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  13521. return startValue + (endValue - startValue) * gradient;
  13522. };
  13523. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  13524. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  13525. };
  13526. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  13527. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  13528. };
  13529. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  13530. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  13531. };
  13532. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  13533. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  13534. };
  13535. Animation.prototype.clone = function () {
  13536. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  13537. clone.setKeys(this._keys);
  13538. return clone;
  13539. };
  13540. Animation.prototype.setKeys = function (values) {
  13541. this._keys = values.slice(0);
  13542. this._offsetsCache = {};
  13543. this._highLimitsCache = {};
  13544. };
  13545. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  13546. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  13547. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  13548. }
  13549. this.currentFrame = currentFrame;
  13550. for (var key = 0; key < this._keys.length; key++) {
  13551. if (this._keys[key + 1].frame >= currentFrame) {
  13552. var startValue = this._keys[key].value;
  13553. var endValue = this._keys[key + 1].value;
  13554. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  13555. if (this._easingFunction != null) {
  13556. gradient = this._easingFunction.ease(gradient);
  13557. }
  13558. switch (this.dataType) {
  13559. case Animation.ANIMATIONTYPE_FLOAT:
  13560. switch (loopMode) {
  13561. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13562. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13563. return this.floatInterpolateFunction(startValue, endValue, gradient);
  13564. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13565. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  13566. }
  13567. break;
  13568. case Animation.ANIMATIONTYPE_QUATERNION:
  13569. var quaternion = null;
  13570. switch (loopMode) {
  13571. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13572. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13573. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  13574. break;
  13575. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13576. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  13577. break;
  13578. }
  13579. return quaternion;
  13580. case Animation.ANIMATIONTYPE_VECTOR3:
  13581. switch (loopMode) {
  13582. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13583. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13584. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  13585. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13586. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  13587. }
  13588. case Animation.ANIMATIONTYPE_VECTOR2:
  13589. switch (loopMode) {
  13590. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13591. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13592. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  13593. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13594. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  13595. }
  13596. case Animation.ANIMATIONTYPE_COLOR3:
  13597. switch (loopMode) {
  13598. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13599. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13600. return this.color3InterpolateFunction(startValue, endValue, gradient);
  13601. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13602. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  13603. }
  13604. case Animation.ANIMATIONTYPE_MATRIX:
  13605. switch (loopMode) {
  13606. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13607. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13608. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13609. return startValue;
  13610. }
  13611. default:
  13612. break;
  13613. }
  13614. break;
  13615. }
  13616. }
  13617. return this._keys[this._keys.length - 1].value;
  13618. };
  13619. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  13620. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  13621. this._stopped = true;
  13622. return false;
  13623. }
  13624. var returnValue = true;
  13625. if (this._keys[0].frame != 0) {
  13626. var newKey = { frame: 0, value: this._keys[0].value };
  13627. this._keys.splice(0, 0, newKey);
  13628. }
  13629. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  13630. from = this._keys[0].frame;
  13631. }
  13632. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  13633. to = this._keys[this._keys.length - 1].frame;
  13634. }
  13635. var range = to - from;
  13636. var offsetValue;
  13637. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  13638. if (ratio > range && !loop) {
  13639. returnValue = false;
  13640. highLimitValue = this._keys[this._keys.length - 1].value;
  13641. } else {
  13642. var highLimitValue = 0;
  13643. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  13644. var keyOffset = to.toString() + from.toString();
  13645. if (!this._offsetsCache[keyOffset]) {
  13646. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  13647. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  13648. switch (this.dataType) {
  13649. case Animation.ANIMATIONTYPE_FLOAT:
  13650. this._offsetsCache[keyOffset] = toValue - fromValue;
  13651. break;
  13652. case Animation.ANIMATIONTYPE_QUATERNION:
  13653. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  13654. break;
  13655. case Animation.ANIMATIONTYPE_VECTOR3:
  13656. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  13657. case Animation.ANIMATIONTYPE_VECTOR2:
  13658. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  13659. case Animation.ANIMATIONTYPE_COLOR3:
  13660. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  13661. default:
  13662. break;
  13663. }
  13664. this._highLimitsCache[keyOffset] = toValue;
  13665. }
  13666. highLimitValue = this._highLimitsCache[keyOffset];
  13667. offsetValue = this._offsetsCache[keyOffset];
  13668. }
  13669. }
  13670. if (offsetValue === undefined) {
  13671. switch (this.dataType) {
  13672. case Animation.ANIMATIONTYPE_FLOAT:
  13673. offsetValue = 0;
  13674. break;
  13675. case Animation.ANIMATIONTYPE_QUATERNION:
  13676. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  13677. break;
  13678. case Animation.ANIMATIONTYPE_VECTOR3:
  13679. offsetValue = BABYLON.Vector3.Zero();
  13680. break;
  13681. case Animation.ANIMATIONTYPE_VECTOR2:
  13682. offsetValue = BABYLON.Vector2.Zero();
  13683. break;
  13684. case Animation.ANIMATIONTYPE_COLOR3:
  13685. offsetValue = BABYLON.Color3.Black();
  13686. }
  13687. }
  13688. var repeatCount = (ratio / range) >> 0;
  13689. var currentFrame = returnValue ? from + ratio % range : to;
  13690. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  13691. if (this.targetPropertyPath.length > 1) {
  13692. var property = this._target[this.targetPropertyPath[0]];
  13693. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  13694. property = property[this.targetPropertyPath[index]];
  13695. }
  13696. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  13697. } else {
  13698. this._target[this.targetPropertyPath[0]] = currentValue;
  13699. }
  13700. if (this._target.markAsDirty) {
  13701. this._target.markAsDirty(this.targetProperty);
  13702. }
  13703. if (!returnValue) {
  13704. this._stopped = true;
  13705. }
  13706. return returnValue;
  13707. };
  13708. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  13709. get: function () {
  13710. return Animation._ANIMATIONTYPE_FLOAT;
  13711. },
  13712. enumerable: true,
  13713. configurable: true
  13714. });
  13715. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  13716. get: function () {
  13717. return Animation._ANIMATIONTYPE_VECTOR3;
  13718. },
  13719. enumerable: true,
  13720. configurable: true
  13721. });
  13722. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  13723. get: function () {
  13724. return Animation._ANIMATIONTYPE_VECTOR2;
  13725. },
  13726. enumerable: true,
  13727. configurable: true
  13728. });
  13729. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  13730. get: function () {
  13731. return Animation._ANIMATIONTYPE_QUATERNION;
  13732. },
  13733. enumerable: true,
  13734. configurable: true
  13735. });
  13736. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  13737. get: function () {
  13738. return Animation._ANIMATIONTYPE_MATRIX;
  13739. },
  13740. enumerable: true,
  13741. configurable: true
  13742. });
  13743. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  13744. get: function () {
  13745. return Animation._ANIMATIONTYPE_COLOR3;
  13746. },
  13747. enumerable: true,
  13748. configurable: true
  13749. });
  13750. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  13751. get: function () {
  13752. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  13753. },
  13754. enumerable: true,
  13755. configurable: true
  13756. });
  13757. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  13758. get: function () {
  13759. return Animation._ANIMATIONLOOPMODE_CYCLE;
  13760. },
  13761. enumerable: true,
  13762. configurable: true
  13763. });
  13764. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  13765. get: function () {
  13766. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  13767. },
  13768. enumerable: true,
  13769. configurable: true
  13770. });
  13771. Animation._ANIMATIONTYPE_FLOAT = 0;
  13772. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  13773. Animation._ANIMATIONTYPE_QUATERNION = 2;
  13774. Animation._ANIMATIONTYPE_MATRIX = 3;
  13775. Animation._ANIMATIONTYPE_COLOR3 = 4;
  13776. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  13777. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  13778. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  13779. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  13780. return Animation;
  13781. })();
  13782. BABYLON.Animation = Animation;
  13783. })(BABYLON || (BABYLON = {}));
  13784. var BABYLON;
  13785. (function (BABYLON) {
  13786. var Animatable = (function () {
  13787. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  13788. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  13789. if (typeof toFrame === "undefined") { toFrame = 100; }
  13790. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  13791. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  13792. this.target = target;
  13793. this.fromFrame = fromFrame;
  13794. this.toFrame = toFrame;
  13795. this.loopAnimation = loopAnimation;
  13796. this.speedRatio = speedRatio;
  13797. this.onAnimationEnd = onAnimationEnd;
  13798. this._animations = new Array();
  13799. this._paused = false;
  13800. this.animationStarted = false;
  13801. if (animations) {
  13802. this.appendAnimations(target, animations);
  13803. }
  13804. this._scene = scene;
  13805. scene._activeAnimatables.push(this);
  13806. }
  13807. Animatable.prototype.appendAnimations = function (target, animations) {
  13808. for (var index = 0; index < animations.length; index++) {
  13809. var animation = animations[index];
  13810. animation._target = target;
  13811. this._animations.push(animation);
  13812. }
  13813. };
  13814. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  13815. var animations = this._animations;
  13816. for (var index = 0; index < animations.length; index++) {
  13817. if (animations[index].targetProperty === property) {
  13818. return animations[index];
  13819. }
  13820. }
  13821. return null;
  13822. };
  13823. Animatable.prototype.pause = function () {
  13824. if (this._paused) {
  13825. return;
  13826. }
  13827. this._paused = true;
  13828. };
  13829. Animatable.prototype.restart = function () {
  13830. this._paused = false;
  13831. };
  13832. Animatable.prototype.stop = function () {
  13833. var index = this._scene._activeAnimatables.indexOf(this);
  13834. if (index > -1) {
  13835. this._scene._activeAnimatables.splice(index, 1);
  13836. }
  13837. if (this.onAnimationEnd) {
  13838. this.onAnimationEnd();
  13839. }
  13840. };
  13841. Animatable.prototype._animate = function (delay) {
  13842. if (this._paused) {
  13843. if (!this._pausedDelay) {
  13844. this._pausedDelay = delay;
  13845. }
  13846. return true;
  13847. }
  13848. if (!this._localDelayOffset) {
  13849. this._localDelayOffset = delay;
  13850. } else if (this._pausedDelay) {
  13851. this._localDelayOffset += delay - this._pausedDelay;
  13852. this._pausedDelay = null;
  13853. }
  13854. var running = false;
  13855. var animations = this._animations;
  13856. for (var index = 0; index < animations.length; index++) {
  13857. var animation = animations[index];
  13858. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  13859. running = running || isRunning;
  13860. }
  13861. if (!running && this.onAnimationEnd) {
  13862. this.onAnimationEnd();
  13863. }
  13864. return running;
  13865. };
  13866. return Animatable;
  13867. })();
  13868. BABYLON.Animatable = Animatable;
  13869. })(BABYLON || (BABYLON = {}));
  13870. var __extends = this.__extends || function (d, b) {
  13871. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13872. function __() { this.constructor = d; }
  13873. __.prototype = b.prototype;
  13874. d.prototype = new __();
  13875. };
  13876. var BABYLON;
  13877. (function (BABYLON) {
  13878. var EasingFunction = (function () {
  13879. function EasingFunction() {
  13880. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  13881. }
  13882. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  13883. get: function () {
  13884. return EasingFunction._EASINGMODE_EASEIN;
  13885. },
  13886. enumerable: true,
  13887. configurable: true
  13888. });
  13889. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  13890. get: function () {
  13891. return EasingFunction._EASINGMODE_EASEOUT;
  13892. },
  13893. enumerable: true,
  13894. configurable: true
  13895. });
  13896. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  13897. get: function () {
  13898. return EasingFunction._EASINGMODE_EASEINOUT;
  13899. },
  13900. enumerable: true,
  13901. configurable: true
  13902. });
  13903. EasingFunction.prototype.setEasingMode = function (easingMode) {
  13904. var n = Math.min(Math.max(easingMode, 0), 2);
  13905. this._easingMode = n;
  13906. };
  13907. EasingFunction.prototype.getEasingMode = function () {
  13908. return this._easingMode;
  13909. };
  13910. EasingFunction.prototype.easeInCore = function (gradient) {
  13911. throw new Error('You must implement this method');
  13912. };
  13913. EasingFunction.prototype.ease = function (gradient) {
  13914. switch (this._easingMode) {
  13915. case EasingFunction.EASINGMODE_EASEIN:
  13916. return this.easeInCore(gradient);
  13917. case EasingFunction.EASINGMODE_EASEOUT:
  13918. return (1 - this.easeInCore(1 - gradient));
  13919. }
  13920. if (gradient >= 0.5) {
  13921. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  13922. }
  13923. return (this.easeInCore(gradient * 2) * 0.5);
  13924. };
  13925. EasingFunction._EASINGMODE_EASEIN = 0;
  13926. EasingFunction._EASINGMODE_EASEOUT = 1;
  13927. EasingFunction._EASINGMODE_EASEINOUT = 2;
  13928. return EasingFunction;
  13929. })();
  13930. BABYLON.EasingFunction = EasingFunction;
  13931. var CircleEase = (function (_super) {
  13932. __extends(CircleEase, _super);
  13933. function CircleEase() {
  13934. _super.apply(this, arguments);
  13935. }
  13936. CircleEase.prototype.easeInCore = function (gradient) {
  13937. gradient = Math.max(0, Math.min(1, gradient));
  13938. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  13939. };
  13940. return CircleEase;
  13941. })(EasingFunction);
  13942. BABYLON.CircleEase = CircleEase;
  13943. var BackEase = (function (_super) {
  13944. __extends(BackEase, _super);
  13945. function BackEase(amplitude) {
  13946. if (typeof amplitude === "undefined") { amplitude = 1; }
  13947. _super.call(this);
  13948. this.amplitude = amplitude;
  13949. }
  13950. BackEase.prototype.easeInCore = function (gradient) {
  13951. var num = Math.max(0, this.amplitude);
  13952. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  13953. };
  13954. return BackEase;
  13955. })(EasingFunction);
  13956. BABYLON.BackEase = BackEase;
  13957. var BounceEase = (function (_super) {
  13958. __extends(BounceEase, _super);
  13959. function BounceEase(bounces, bounciness) {
  13960. if (typeof bounces === "undefined") { bounces = 3; }
  13961. if (typeof bounciness === "undefined") { bounciness = 2; }
  13962. _super.call(this);
  13963. this.bounces = bounces;
  13964. this.bounciness = bounciness;
  13965. }
  13966. BounceEase.prototype.easeInCore = function (gradient) {
  13967. var y = Math.max(0.0, this.bounces);
  13968. var bounciness = this.bounciness;
  13969. if (bounciness <= 1.0) {
  13970. bounciness = 1.001;
  13971. }
  13972. var num9 = Math.pow(bounciness, y);
  13973. var num5 = 1.0 - bounciness;
  13974. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  13975. var num15 = gradient * num4;
  13976. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  13977. var num3 = Math.floor(num65);
  13978. var num13 = num3 + 1.0;
  13979. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  13980. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  13981. var num7 = (num8 + num12) * 0.5;
  13982. var num6 = gradient - num7;
  13983. var num2 = num7 - num8;
  13984. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  13985. };
  13986. return BounceEase;
  13987. })(EasingFunction);
  13988. BABYLON.BounceEase = BounceEase;
  13989. var CubicEase = (function (_super) {
  13990. __extends(CubicEase, _super);
  13991. function CubicEase() {
  13992. _super.apply(this, arguments);
  13993. }
  13994. CubicEase.prototype.easeInCore = function (gradient) {
  13995. return (gradient * gradient * gradient);
  13996. };
  13997. return CubicEase;
  13998. })(EasingFunction);
  13999. BABYLON.CubicEase = CubicEase;
  14000. var ElasticEase = (function (_super) {
  14001. __extends(ElasticEase, _super);
  14002. function ElasticEase(oscillations, springiness) {
  14003. if (typeof oscillations === "undefined") { oscillations = 3; }
  14004. if (typeof springiness === "undefined") { springiness = 3; }
  14005. _super.call(this);
  14006. this.oscillations = oscillations;
  14007. this.springiness = springiness;
  14008. }
  14009. ElasticEase.prototype.easeInCore = function (gradient) {
  14010. var num2;
  14011. var num3 = Math.max(0.0, this.oscillations);
  14012. var num = Math.max(0.0, this.springiness);
  14013. if (num == 0) {
  14014. num2 = gradient;
  14015. } else {
  14016. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  14017. }
  14018. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  14019. };
  14020. return ElasticEase;
  14021. })(EasingFunction);
  14022. BABYLON.ElasticEase = ElasticEase;
  14023. var ExponentialEase = (function (_super) {
  14024. __extends(ExponentialEase, _super);
  14025. function ExponentialEase(exponent) {
  14026. if (typeof exponent === "undefined") { exponent = 2; }
  14027. _super.call(this);
  14028. this.exponent = exponent;
  14029. }
  14030. ExponentialEase.prototype.easeInCore = function (gradient) {
  14031. if (this.exponent <= 0) {
  14032. return gradient;
  14033. }
  14034. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  14035. };
  14036. return ExponentialEase;
  14037. })(EasingFunction);
  14038. BABYLON.ExponentialEase = ExponentialEase;
  14039. var PowerEase = (function (_super) {
  14040. __extends(PowerEase, _super);
  14041. function PowerEase(power) {
  14042. if (typeof power === "undefined") { power = 2; }
  14043. _super.call(this);
  14044. this.power = power;
  14045. }
  14046. PowerEase.prototype.easeInCore = function (gradient) {
  14047. var y = Math.max(0.0, this.power);
  14048. return Math.pow(gradient, y);
  14049. };
  14050. return PowerEase;
  14051. })(EasingFunction);
  14052. BABYLON.PowerEase = PowerEase;
  14053. var QuadraticEase = (function (_super) {
  14054. __extends(QuadraticEase, _super);
  14055. function QuadraticEase() {
  14056. _super.apply(this, arguments);
  14057. }
  14058. QuadraticEase.prototype.easeInCore = function (gradient) {
  14059. return (gradient * gradient);
  14060. };
  14061. return QuadraticEase;
  14062. })(EasingFunction);
  14063. BABYLON.QuadraticEase = QuadraticEase;
  14064. var QuarticEase = (function (_super) {
  14065. __extends(QuarticEase, _super);
  14066. function QuarticEase() {
  14067. _super.apply(this, arguments);
  14068. }
  14069. QuarticEase.prototype.easeInCore = function (gradient) {
  14070. return (gradient * gradient * gradient * gradient);
  14071. };
  14072. return QuarticEase;
  14073. })(EasingFunction);
  14074. BABYLON.QuarticEase = QuarticEase;
  14075. var QuinticEase = (function (_super) {
  14076. __extends(QuinticEase, _super);
  14077. function QuinticEase() {
  14078. _super.apply(this, arguments);
  14079. }
  14080. QuinticEase.prototype.easeInCore = function (gradient) {
  14081. return (gradient * gradient * gradient * gradient * gradient);
  14082. };
  14083. return QuinticEase;
  14084. })(EasingFunction);
  14085. BABYLON.QuinticEase = QuinticEase;
  14086. var SineEase = (function (_super) {
  14087. __extends(SineEase, _super);
  14088. function SineEase() {
  14089. _super.apply(this, arguments);
  14090. }
  14091. SineEase.prototype.easeInCore = function (gradient) {
  14092. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  14093. };
  14094. return SineEase;
  14095. })(EasingFunction);
  14096. BABYLON.SineEase = SineEase;
  14097. var BezierCurveEase = (function (_super) {
  14098. __extends(BezierCurveEase, _super);
  14099. function BezierCurveEase(x1, y1, x2, y2) {
  14100. if (typeof x1 === "undefined") { x1 = 0; }
  14101. if (typeof y1 === "undefined") { y1 = 0; }
  14102. if (typeof x2 === "undefined") { x2 = 1; }
  14103. if (typeof y2 === "undefined") { y2 = 1; }
  14104. _super.call(this);
  14105. this.x1 = x1;
  14106. this.y1 = y1;
  14107. this.x2 = x2;
  14108. this.y2 = y2;
  14109. }
  14110. BezierCurveEase.prototype.easeInCore = function (gradient) {
  14111. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  14112. };
  14113. return BezierCurveEase;
  14114. })(EasingFunction);
  14115. BABYLON.BezierCurveEase = BezierCurveEase;
  14116. })(BABYLON || (BABYLON = {}));
  14117. var BABYLON;
  14118. (function (BABYLON) {
  14119. var Octree = (function () {
  14120. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  14121. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  14122. this.maxDepth = maxDepth;
  14123. this.dynamicContent = new Array();
  14124. this._maxBlockCapacity = maxBlockCapacity || 64;
  14125. this._selectionContent = new BABYLON.SmartArray(1024);
  14126. this._creationFunc = creationFunc;
  14127. }
  14128. Octree.prototype.update = function (worldMin, worldMax, entries) {
  14129. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  14130. };
  14131. Octree.prototype.addMesh = function (entry) {
  14132. for (var index = 0; index < this.blocks.length; index++) {
  14133. var block = this.blocks[index];
  14134. block.addEntry(entry);
  14135. }
  14136. };
  14137. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  14138. this._selectionContent.reset();
  14139. for (var index = 0; index < this.blocks.length; index++) {
  14140. var block = this.blocks[index];
  14141. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  14142. }
  14143. if (allowDuplicate) {
  14144. this._selectionContent.concat(this.dynamicContent);
  14145. } else {
  14146. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14147. }
  14148. return this._selectionContent;
  14149. };
  14150. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  14151. this._selectionContent.reset();
  14152. for (var index = 0; index < this.blocks.length; index++) {
  14153. var block = this.blocks[index];
  14154. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  14155. }
  14156. if (allowDuplicate) {
  14157. this._selectionContent.concat(this.dynamicContent);
  14158. } else {
  14159. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14160. }
  14161. return this._selectionContent;
  14162. };
  14163. Octree.prototype.intersectsRay = function (ray) {
  14164. this._selectionContent.reset();
  14165. for (var index = 0; index < this.blocks.length; index++) {
  14166. var block = this.blocks[index];
  14167. block.intersectsRay(ray, this._selectionContent);
  14168. }
  14169. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14170. return this._selectionContent;
  14171. };
  14172. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  14173. target.blocks = new Array();
  14174. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  14175. for (var x = 0; x < 2; x++) {
  14176. for (var y = 0; y < 2; y++) {
  14177. for (var z = 0; z < 2; z++) {
  14178. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  14179. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  14180. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  14181. block.addEntries(entries);
  14182. target.blocks.push(block);
  14183. }
  14184. }
  14185. }
  14186. };
  14187. Octree.CreationFuncForMeshes = function (entry, block) {
  14188. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  14189. block.entries.push(entry);
  14190. }
  14191. };
  14192. Octree.CreationFuncForSubMeshes = function (entry, block) {
  14193. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  14194. block.entries.push(entry);
  14195. }
  14196. };
  14197. return Octree;
  14198. })();
  14199. BABYLON.Octree = Octree;
  14200. })(BABYLON || (BABYLON = {}));
  14201. var BABYLON;
  14202. (function (BABYLON) {
  14203. var OctreeBlock = (function () {
  14204. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  14205. this.entries = new Array();
  14206. this._boundingVectors = new Array();
  14207. this._capacity = capacity;
  14208. this._depth = depth;
  14209. this._maxDepth = maxDepth;
  14210. this._creationFunc = creationFunc;
  14211. this._minPoint = minPoint;
  14212. this._maxPoint = maxPoint;
  14213. this._boundingVectors.push(minPoint.clone());
  14214. this._boundingVectors.push(maxPoint.clone());
  14215. this._boundingVectors.push(minPoint.clone());
  14216. this._boundingVectors[2].x = maxPoint.x;
  14217. this._boundingVectors.push(minPoint.clone());
  14218. this._boundingVectors[3].y = maxPoint.y;
  14219. this._boundingVectors.push(minPoint.clone());
  14220. this._boundingVectors[4].z = maxPoint.z;
  14221. this._boundingVectors.push(maxPoint.clone());
  14222. this._boundingVectors[5].z = minPoint.z;
  14223. this._boundingVectors.push(maxPoint.clone());
  14224. this._boundingVectors[6].x = minPoint.x;
  14225. this._boundingVectors.push(maxPoint.clone());
  14226. this._boundingVectors[7].y = minPoint.y;
  14227. }
  14228. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  14229. get: function () {
  14230. return this._capacity;
  14231. },
  14232. enumerable: true,
  14233. configurable: true
  14234. });
  14235. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  14236. get: function () {
  14237. return this._minPoint;
  14238. },
  14239. enumerable: true,
  14240. configurable: true
  14241. });
  14242. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  14243. get: function () {
  14244. return this._maxPoint;
  14245. },
  14246. enumerable: true,
  14247. configurable: true
  14248. });
  14249. OctreeBlock.prototype.addEntry = function (entry) {
  14250. if (this.blocks) {
  14251. for (var index = 0; index < this.blocks.length; index++) {
  14252. var block = this.blocks[index];
  14253. block.addEntry(entry);
  14254. }
  14255. return;
  14256. }
  14257. this._creationFunc(entry, this);
  14258. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  14259. this.createInnerBlocks();
  14260. }
  14261. };
  14262. OctreeBlock.prototype.addEntries = function (entries) {
  14263. for (var index = 0; index < entries.length; index++) {
  14264. var mesh = entries[index];
  14265. this.addEntry(mesh);
  14266. }
  14267. };
  14268. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  14269. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  14270. if (this.blocks) {
  14271. for (var index = 0; index < this.blocks.length; index++) {
  14272. var block = this.blocks[index];
  14273. block.select(frustumPlanes, selection, allowDuplicate);
  14274. }
  14275. return;
  14276. }
  14277. if (allowDuplicate) {
  14278. selection.concat(this.entries);
  14279. } else {
  14280. selection.concatWithNoDuplicate(this.entries);
  14281. }
  14282. }
  14283. };
  14284. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  14285. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  14286. if (this.blocks) {
  14287. for (var index = 0; index < this.blocks.length; index++) {
  14288. var block = this.blocks[index];
  14289. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  14290. }
  14291. return;
  14292. }
  14293. if (allowDuplicate) {
  14294. selection.concat(this.entries);
  14295. } else {
  14296. selection.concatWithNoDuplicate(this.entries);
  14297. }
  14298. }
  14299. };
  14300. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  14301. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  14302. if (this.blocks) {
  14303. for (var index = 0; index < this.blocks.length; index++) {
  14304. var block = this.blocks[index];
  14305. block.intersectsRay(ray, selection);
  14306. }
  14307. return;
  14308. }
  14309. selection.concatWithNoDuplicate(this.entries);
  14310. }
  14311. };
  14312. OctreeBlock.prototype.createInnerBlocks = function () {
  14313. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  14314. };
  14315. return OctreeBlock;
  14316. })();
  14317. BABYLON.OctreeBlock = OctreeBlock;
  14318. })(BABYLON || (BABYLON = {}));
  14319. var BABYLON;
  14320. (function (BABYLON) {
  14321. var Bone = (function () {
  14322. function Bone(name, skeleton, parentBone, matrix) {
  14323. this.name = name;
  14324. this.children = new Array();
  14325. this.animations = new Array();
  14326. this._worldTransform = new BABYLON.Matrix();
  14327. this._absoluteTransform = new BABYLON.Matrix();
  14328. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  14329. this._skeleton = skeleton;
  14330. this._matrix = matrix;
  14331. this._baseMatrix = matrix;
  14332. skeleton.bones.push(this);
  14333. if (parentBone) {
  14334. this._parent = parentBone;
  14335. parentBone.children.push(this);
  14336. } else {
  14337. this._parent = null;
  14338. }
  14339. this._updateDifferenceMatrix();
  14340. }
  14341. Bone.prototype.getParent = function () {
  14342. return this._parent;
  14343. };
  14344. Bone.prototype.getLocalMatrix = function () {
  14345. return this._matrix;
  14346. };
  14347. Bone.prototype.getBaseMatrix = function () {
  14348. return this._baseMatrix;
  14349. };
  14350. Bone.prototype.getWorldMatrix = function () {
  14351. return this._worldTransform;
  14352. };
  14353. Bone.prototype.getInvertedAbsoluteTransform = function () {
  14354. return this._invertedAbsoluteTransform;
  14355. };
  14356. Bone.prototype.getAbsoluteMatrix = function () {
  14357. var matrix = this._matrix.clone();
  14358. var parent = this._parent;
  14359. while (parent) {
  14360. matrix = matrix.multiply(parent.getLocalMatrix());
  14361. parent = parent.getParent();
  14362. }
  14363. return matrix;
  14364. };
  14365. Bone.prototype.updateMatrix = function (matrix) {
  14366. this._matrix = matrix;
  14367. this._skeleton._markAsDirty();
  14368. this._updateDifferenceMatrix();
  14369. };
  14370. Bone.prototype._updateDifferenceMatrix = function () {
  14371. if (this._parent) {
  14372. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  14373. } else {
  14374. this._absoluteTransform.copyFrom(this._matrix);
  14375. }
  14376. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  14377. for (var index = 0; index < this.children.length; index++) {
  14378. this.children[index]._updateDifferenceMatrix();
  14379. }
  14380. };
  14381. Bone.prototype.markAsDirty = function () {
  14382. this._skeleton._markAsDirty();
  14383. };
  14384. return Bone;
  14385. })();
  14386. BABYLON.Bone = Bone;
  14387. })(BABYLON || (BABYLON = {}));
  14388. var BABYLON;
  14389. (function (BABYLON) {
  14390. var Skeleton = (function () {
  14391. function Skeleton(name, id, scene) {
  14392. this.name = name;
  14393. this.id = id;
  14394. this.bones = new Array();
  14395. this._isDirty = true;
  14396. this._identity = BABYLON.Matrix.Identity();
  14397. this.bones = [];
  14398. this._scene = scene;
  14399. scene.skeletons.push(this);
  14400. }
  14401. Skeleton.prototype.getTransformMatrices = function () {
  14402. return this._transformMatrices;
  14403. };
  14404. Skeleton.prototype._markAsDirty = function () {
  14405. this._isDirty = true;
  14406. };
  14407. Skeleton.prototype.prepare = function () {
  14408. if (!this._isDirty) {
  14409. return;
  14410. }
  14411. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  14412. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  14413. }
  14414. for (var index = 0; index < this.bones.length; index++) {
  14415. var bone = this.bones[index];
  14416. var parentBone = bone.getParent();
  14417. if (parentBone) {
  14418. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  14419. } else {
  14420. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  14421. }
  14422. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  14423. }
  14424. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  14425. this._isDirty = false;
  14426. };
  14427. Skeleton.prototype.getAnimatables = function () {
  14428. if (!this._animatables || this._animatables.length != this.bones.length) {
  14429. this._animatables = [];
  14430. for (var index = 0; index < this.bones.length; index++) {
  14431. this._animatables.push(this.bones[index]);
  14432. }
  14433. }
  14434. return this._animatables;
  14435. };
  14436. Skeleton.prototype.clone = function (name, id) {
  14437. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  14438. for (var index = 0; index < this.bones.length; index++) {
  14439. var source = this.bones[index];
  14440. var parentBone = null;
  14441. if (source.getParent()) {
  14442. var parentIndex = this.bones.indexOf(source.getParent());
  14443. parentBone = result.bones[parentIndex];
  14444. }
  14445. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  14446. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  14447. }
  14448. return result;
  14449. };
  14450. return Skeleton;
  14451. })();
  14452. BABYLON.Skeleton = Skeleton;
  14453. })(BABYLON || (BABYLON = {}));
  14454. var BABYLON;
  14455. (function (BABYLON) {
  14456. var PostProcess = (function () {
  14457. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  14458. this.name = name;
  14459. this.width = -1;
  14460. this.height = -1;
  14461. this._reusable = false;
  14462. this._textures = new BABYLON.SmartArray(2);
  14463. this._currentRenderTextureInd = 0;
  14464. if (camera != null) {
  14465. this._camera = camera;
  14466. this._scene = camera.getScene();
  14467. camera.attachPostProcess(this);
  14468. this._engine = this._scene.getEngine();
  14469. } else {
  14470. this._engine = engine;
  14471. }
  14472. this._renderRatio = ratio;
  14473. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14474. this._reusable = reusable || false;
  14475. samplers = samplers || [];
  14476. samplers.push("textureSampler");
  14477. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  14478. }
  14479. PostProcess.prototype.isReusable = function () {
  14480. return this._reusable;
  14481. };
  14482. PostProcess.prototype.activate = function (camera, sourceTexture) {
  14483. camera = camera || this._camera;
  14484. var scene = camera.getScene();
  14485. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  14486. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  14487. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  14488. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  14489. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  14490. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  14491. if (this._textures.length > 0) {
  14492. for (var i = 0; i < this._textures.length; i++) {
  14493. this._engine._releaseTexture(this._textures.data[i]);
  14494. }
  14495. this._textures.reset();
  14496. }
  14497. this.width = desiredWidth;
  14498. this.height = desiredHeight;
  14499. 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 }));
  14500. if (this._reusable) {
  14501. 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 }));
  14502. }
  14503. if (this.onSizeChanged) {
  14504. this.onSizeChanged();
  14505. }
  14506. }
  14507. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  14508. if (this.onActivate) {
  14509. this.onActivate(camera);
  14510. }
  14511. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  14512. if (this._reusable) {
  14513. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  14514. }
  14515. };
  14516. PostProcess.prototype.apply = function () {
  14517. if (!this._effect.isReady())
  14518. return null;
  14519. this._engine.enableEffect(this._effect);
  14520. this._engine.setState(false);
  14521. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14522. this._engine.setDepthBuffer(false);
  14523. this._engine.setDepthWrite(false);
  14524. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  14525. if (this.onApply) {
  14526. this.onApply(this._effect);
  14527. }
  14528. return this._effect;
  14529. };
  14530. PostProcess.prototype.dispose = function (camera) {
  14531. camera = camera || this._camera;
  14532. if (this._textures.length > 0) {
  14533. for (var i = 0; i < this._textures.length; i++) {
  14534. this._engine._releaseTexture(this._textures.data[i]);
  14535. }
  14536. this._textures.reset();
  14537. }
  14538. camera.detachPostProcess(this);
  14539. var index = camera._postProcesses.indexOf(this);
  14540. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  14541. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  14542. }
  14543. };
  14544. return PostProcess;
  14545. })();
  14546. BABYLON.PostProcess = PostProcess;
  14547. })(BABYLON || (BABYLON = {}));
  14548. var BABYLON;
  14549. (function (BABYLON) {
  14550. var PostProcessManager = (function () {
  14551. function PostProcessManager(scene) {
  14552. this._vertexDeclaration = [2];
  14553. this._vertexStrideSize = 2 * 4;
  14554. this._scene = scene;
  14555. var vertices = [];
  14556. vertices.push(1, 1);
  14557. vertices.push(-1, 1);
  14558. vertices.push(-1, -1);
  14559. vertices.push(1, -1);
  14560. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14561. var indices = [];
  14562. indices.push(0);
  14563. indices.push(1);
  14564. indices.push(2);
  14565. indices.push(0);
  14566. indices.push(2);
  14567. indices.push(3);
  14568. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14569. }
  14570. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  14571. var postProcesses = this._scene.activeCamera._postProcesses;
  14572. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  14573. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  14574. return false;
  14575. }
  14576. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  14577. return true;
  14578. };
  14579. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  14580. var postProcesses = this._scene.activeCamera._postProcesses;
  14581. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  14582. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  14583. return;
  14584. }
  14585. var engine = this._scene.getEngine();
  14586. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  14587. if (index < postProcessesTakenIndices.length - 1) {
  14588. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  14589. } else {
  14590. if (targetTexture) {
  14591. engine.bindFramebuffer(targetTexture);
  14592. } else {
  14593. engine.restoreDefaultFramebuffer();
  14594. }
  14595. }
  14596. if (doNotPresent) {
  14597. break;
  14598. }
  14599. var pp = postProcesses[postProcessesTakenIndices[index]];
  14600. var effect = pp.apply();
  14601. if (effect) {
  14602. if (pp.onBeforeRender) {
  14603. pp.onBeforeRender(effect);
  14604. }
  14605. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14606. engine.draw(true, 0, 6);
  14607. }
  14608. }
  14609. engine.setDepthBuffer(true);
  14610. engine.setDepthWrite(true);
  14611. };
  14612. PostProcessManager.prototype.dispose = function () {
  14613. if (this._vertexBuffer) {
  14614. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14615. this._vertexBuffer = null;
  14616. }
  14617. if (this._indexBuffer) {
  14618. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14619. this._indexBuffer = null;
  14620. }
  14621. };
  14622. return PostProcessManager;
  14623. })();
  14624. BABYLON.PostProcessManager = PostProcessManager;
  14625. })(BABYLON || (BABYLON = {}));
  14626. var __extends = this.__extends || function (d, b) {
  14627. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14628. function __() { this.constructor = d; }
  14629. __.prototype = b.prototype;
  14630. d.prototype = new __();
  14631. };
  14632. var BABYLON;
  14633. (function (BABYLON) {
  14634. var PassPostProcess = (function (_super) {
  14635. __extends(PassPostProcess, _super);
  14636. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  14637. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  14638. }
  14639. return PassPostProcess;
  14640. })(BABYLON.PostProcess);
  14641. BABYLON.PassPostProcess = PassPostProcess;
  14642. })(BABYLON || (BABYLON = {}));
  14643. var __extends = this.__extends || function (d, b) {
  14644. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14645. function __() { this.constructor = d; }
  14646. __.prototype = b.prototype;
  14647. d.prototype = new __();
  14648. };
  14649. var BABYLON;
  14650. (function (BABYLON) {
  14651. var BlurPostProcess = (function (_super) {
  14652. __extends(BlurPostProcess, _super);
  14653. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  14654. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  14655. var _this = this;
  14656. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  14657. this.direction = direction;
  14658. this.blurWidth = blurWidth;
  14659. this.onApply = function (effect) {
  14660. effect.setFloat2("screenSize", _this.width, _this.height);
  14661. effect.setVector2("direction", _this.direction);
  14662. effect.setFloat("blurWidth", _this.blurWidth);
  14663. };
  14664. }
  14665. return BlurPostProcess;
  14666. })(BABYLON.PostProcess);
  14667. BABYLON.BlurPostProcess = BlurPostProcess;
  14668. })(BABYLON || (BABYLON = {}));
  14669. var __extends = this.__extends || function (d, b) {
  14670. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14671. function __() { this.constructor = d; }
  14672. __.prototype = b.prototype;
  14673. d.prototype = new __();
  14674. };
  14675. var BABYLON;
  14676. (function (BABYLON) {
  14677. var FilterPostProcess = (function (_super) {
  14678. __extends(FilterPostProcess, _super);
  14679. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  14680. var _this = this;
  14681. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  14682. this.kernelMatrix = kernelMatrix;
  14683. this.onApply = function (effect) {
  14684. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  14685. };
  14686. }
  14687. return FilterPostProcess;
  14688. })(BABYLON.PostProcess);
  14689. BABYLON.FilterPostProcess = FilterPostProcess;
  14690. })(BABYLON || (BABYLON = {}));
  14691. var __extends = this.__extends || function (d, b) {
  14692. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14693. function __() { this.constructor = d; }
  14694. __.prototype = b.prototype;
  14695. d.prototype = new __();
  14696. };
  14697. var BABYLON;
  14698. (function (BABYLON) {
  14699. var RefractionPostProcess = (function (_super) {
  14700. __extends(RefractionPostProcess, _super);
  14701. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  14702. var _this = this;
  14703. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  14704. this.color = color;
  14705. this.depth = depth;
  14706. this.colorLevel = colorLevel;
  14707. this.onActivate = function (cam) {
  14708. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  14709. };
  14710. this.onApply = function (effect) {
  14711. effect.setColor3("baseColor", _this.color);
  14712. effect.setFloat("depth", _this.depth);
  14713. effect.setFloat("colorLevel", _this.colorLevel);
  14714. effect.setTexture("refractionSampler", _this._refRexture);
  14715. };
  14716. }
  14717. RefractionPostProcess.prototype.dispose = function (camera) {
  14718. if (this._refRexture) {
  14719. this._refRexture.dispose();
  14720. }
  14721. _super.prototype.dispose.call(this, camera);
  14722. };
  14723. return RefractionPostProcess;
  14724. })(BABYLON.PostProcess);
  14725. BABYLON.RefractionPostProcess = RefractionPostProcess;
  14726. })(BABYLON || (BABYLON = {}));
  14727. var __extends = this.__extends || function (d, b) {
  14728. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14729. function __() { this.constructor = d; }
  14730. __.prototype = b.prototype;
  14731. d.prototype = new __();
  14732. };
  14733. var BABYLON;
  14734. (function (BABYLON) {
  14735. var BlackAndWhitePostProcess = (function (_super) {
  14736. __extends(BlackAndWhitePostProcess, _super);
  14737. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  14738. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  14739. }
  14740. return BlackAndWhitePostProcess;
  14741. })(BABYLON.PostProcess);
  14742. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  14743. })(BABYLON || (BABYLON = {}));
  14744. var __extends = this.__extends || function (d, b) {
  14745. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14746. function __() { this.constructor = d; }
  14747. __.prototype = b.prototype;
  14748. d.prototype = new __();
  14749. };
  14750. var BABYLON;
  14751. (function (BABYLON) {
  14752. var ConvolutionPostProcess = (function (_super) {
  14753. __extends(ConvolutionPostProcess, _super);
  14754. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  14755. var _this = this;
  14756. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  14757. this.kernel = kernel;
  14758. this.onApply = function (effect) {
  14759. effect.setFloat2("screenSize", _this.width, _this.height);
  14760. effect.setArray("kernel", _this.kernel);
  14761. };
  14762. }
  14763. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  14764. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  14765. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  14766. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  14767. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  14768. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  14769. return ConvolutionPostProcess;
  14770. })(BABYLON.PostProcess);
  14771. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  14772. })(BABYLON || (BABYLON = {}));
  14773. var __extends = this.__extends || function (d, b) {
  14774. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14775. function __() { this.constructor = d; }
  14776. __.prototype = b.prototype;
  14777. d.prototype = new __();
  14778. };
  14779. var BABYLON;
  14780. (function (BABYLON) {
  14781. var FxaaPostProcess = (function (_super) {
  14782. __extends(FxaaPostProcess, _super);
  14783. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  14784. var _this = this;
  14785. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  14786. this.onSizeChanged = function () {
  14787. _this.texelWidth = 1.0 / _this.width;
  14788. _this.texelHeight = 1.0 / _this.height;
  14789. };
  14790. this.onApply = function (effect) {
  14791. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  14792. };
  14793. }
  14794. return FxaaPostProcess;
  14795. })(BABYLON.PostProcess);
  14796. BABYLON.FxaaPostProcess = FxaaPostProcess;
  14797. })(BABYLON || (BABYLON = {}));
  14798. var BABYLON;
  14799. (function (BABYLON) {
  14800. var LensFlare = (function () {
  14801. function LensFlare(size, position, color, imgUrl, system) {
  14802. this.size = size;
  14803. this.position = position;
  14804. this.dispose = function () {
  14805. if (this.texture) {
  14806. this.texture.dispose();
  14807. }
  14808. var index = this._system.lensFlares.indexOf(this);
  14809. this._system.lensFlares.splice(index, 1);
  14810. };
  14811. this.color = color || new BABYLON.Color3(1, 1, 1);
  14812. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  14813. this._system = system;
  14814. system.lensFlares.push(this);
  14815. }
  14816. return LensFlare;
  14817. })();
  14818. BABYLON.LensFlare = LensFlare;
  14819. })(BABYLON || (BABYLON = {}));
  14820. var BABYLON;
  14821. (function (BABYLON) {
  14822. var LensFlareSystem = (function () {
  14823. function LensFlareSystem(name, emitter, scene) {
  14824. this.name = name;
  14825. this.lensFlares = new Array();
  14826. this.borderLimit = 300;
  14827. this._vertexDeclaration = [2];
  14828. this._vertexStrideSize = 2 * 4;
  14829. this._isEnabled = true;
  14830. this._scene = scene;
  14831. this._emitter = emitter;
  14832. scene.lensFlareSystems.push(this);
  14833. this.meshesSelectionPredicate = function (m) {
  14834. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  14835. };
  14836. var vertices = [];
  14837. vertices.push(1, 1);
  14838. vertices.push(-1, 1);
  14839. vertices.push(-1, -1);
  14840. vertices.push(1, -1);
  14841. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14842. var indices = [];
  14843. indices.push(0);
  14844. indices.push(1);
  14845. indices.push(2);
  14846. indices.push(0);
  14847. indices.push(2);
  14848. indices.push(3);
  14849. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14850. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  14851. }
  14852. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  14853. get: function () {
  14854. return this._isEnabled;
  14855. },
  14856. set: function (value) {
  14857. this._isEnabled = value;
  14858. },
  14859. enumerable: true,
  14860. configurable: true
  14861. });
  14862. LensFlareSystem.prototype.getScene = function () {
  14863. return this._scene;
  14864. };
  14865. LensFlareSystem.prototype.getEmitter = function () {
  14866. return this._emitter;
  14867. };
  14868. LensFlareSystem.prototype.getEmitterPosition = function () {
  14869. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  14870. };
  14871. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  14872. var position = this.getEmitterPosition();
  14873. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  14874. this._positionX = position.x;
  14875. this._positionY = position.y;
  14876. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  14877. if (position.z > 0) {
  14878. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  14879. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  14880. return true;
  14881. }
  14882. }
  14883. return false;
  14884. };
  14885. LensFlareSystem.prototype._isVisible = function () {
  14886. if (!this._isEnabled) {
  14887. return false;
  14888. }
  14889. var emitterPosition = this.getEmitterPosition();
  14890. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  14891. var distance = direction.length();
  14892. direction.normalize();
  14893. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  14894. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  14895. return !pickInfo.hit || pickInfo.distance > distance;
  14896. };
  14897. LensFlareSystem.prototype.render = function () {
  14898. if (!this._effect.isReady())
  14899. return false;
  14900. var engine = this._scene.getEngine();
  14901. var viewport = this._scene.activeCamera.viewport;
  14902. var globalViewport = viewport.toGlobal(engine);
  14903. if (!this.computeEffectivePosition(globalViewport)) {
  14904. return false;
  14905. }
  14906. if (!this._isVisible()) {
  14907. return false;
  14908. }
  14909. var awayX;
  14910. var awayY;
  14911. if (this._positionX < this.borderLimit + globalViewport.x) {
  14912. awayX = this.borderLimit + globalViewport.x - this._positionX;
  14913. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  14914. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  14915. } else {
  14916. awayX = 0;
  14917. }
  14918. if (this._positionY < this.borderLimit + globalViewport.y) {
  14919. awayY = this.borderLimit + globalViewport.y - this._positionY;
  14920. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  14921. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  14922. } else {
  14923. awayY = 0;
  14924. }
  14925. var away = (awayX > awayY) ? awayX : awayY;
  14926. if (away > this.borderLimit) {
  14927. away = this.borderLimit;
  14928. }
  14929. var intensity = 1.0 - (away / this.borderLimit);
  14930. if (intensity < 0) {
  14931. return false;
  14932. }
  14933. if (intensity > 1.0) {
  14934. intensity = 1.0;
  14935. }
  14936. var centerX = globalViewport.x + globalViewport.width / 2;
  14937. var centerY = globalViewport.y + globalViewport.height / 2;
  14938. var distX = centerX - this._positionX;
  14939. var distY = centerY - this._positionY;
  14940. engine.enableEffect(this._effect);
  14941. engine.setState(false);
  14942. engine.setDepthBuffer(false);
  14943. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  14944. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  14945. for (var index = 0; index < this.lensFlares.length; index++) {
  14946. var flare = this.lensFlares[index];
  14947. var x = centerX - (distX * flare.position);
  14948. var y = centerY - (distY * flare.position);
  14949. var cw = flare.size;
  14950. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  14951. var cx = 2 * (x / globalViewport.width) - 1.0;
  14952. var cy = 1.0 - 2 * (y / globalViewport.height);
  14953. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  14954. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  14955. this._effect.setTexture("textureSampler", flare.texture);
  14956. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  14957. engine.draw(true, 0, 6);
  14958. }
  14959. engine.setDepthBuffer(true);
  14960. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14961. return true;
  14962. };
  14963. LensFlareSystem.prototype.dispose = function () {
  14964. if (this._vertexBuffer) {
  14965. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14966. this._vertexBuffer = null;
  14967. }
  14968. if (this._indexBuffer) {
  14969. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14970. this._indexBuffer = null;
  14971. }
  14972. while (this.lensFlares.length) {
  14973. this.lensFlares[0].dispose();
  14974. }
  14975. var index = this._scene.lensFlareSystems.indexOf(this);
  14976. this._scene.lensFlareSystems.splice(index, 1);
  14977. };
  14978. return LensFlareSystem;
  14979. })();
  14980. BABYLON.LensFlareSystem = LensFlareSystem;
  14981. })(BABYLON || (BABYLON = {}));
  14982. var BABYLON;
  14983. (function (BABYLON) {
  14984. var IntersectionInfo = (function () {
  14985. function IntersectionInfo(bu, bv, distance) {
  14986. this.bu = bu;
  14987. this.bv = bv;
  14988. this.distance = distance;
  14989. this.faceId = 0;
  14990. }
  14991. return IntersectionInfo;
  14992. })();
  14993. BABYLON.IntersectionInfo = IntersectionInfo;
  14994. var PickingInfo = (function () {
  14995. function PickingInfo() {
  14996. this.hit = false;
  14997. this.distance = 0;
  14998. this.pickedPoint = null;
  14999. this.pickedMesh = null;
  15000. this.bu = 0;
  15001. this.bv = 0;
  15002. this.faceId = -1;
  15003. }
  15004. PickingInfo.prototype.getNormal = function () {
  15005. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15006. return null;
  15007. }
  15008. var indices = this.pickedMesh.getIndices();
  15009. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15010. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  15011. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  15012. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  15013. normal0 = normal0.scale(this.bu);
  15014. normal1 = normal1.scale(this.bv);
  15015. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  15016. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  15017. };
  15018. PickingInfo.prototype.getTextureCoordinates = function () {
  15019. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15020. return null;
  15021. }
  15022. var indices = this.pickedMesh.getIndices();
  15023. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15024. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  15025. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  15026. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  15027. uv0 = uv0.scale(this.bu);
  15028. uv1 = uv1.scale(this.bv);
  15029. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  15030. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  15031. };
  15032. return PickingInfo;
  15033. })();
  15034. BABYLON.PickingInfo = PickingInfo;
  15035. })(BABYLON || (BABYLON = {}));
  15036. var BABYLON;
  15037. (function (BABYLON) {
  15038. var FilesInput = (function () {
  15039. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  15040. this.engine = p_engine;
  15041. this.canvas = p_canvas;
  15042. this.currentScene = p_scene;
  15043. this.sceneLoadedCallback = p_sceneLoadedCallback;
  15044. this.progressCallback = p_progressCallback;
  15045. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  15046. this.textureLoadingCallback = p_textureLoadingCallback;
  15047. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  15048. }
  15049. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  15050. var _this = this;
  15051. if (p_elementToMonitor) {
  15052. this.elementToMonitor = p_elementToMonitor;
  15053. this.elementToMonitor.addEventListener("dragenter", function (e) {
  15054. _this.drag(e);
  15055. }, false);
  15056. this.elementToMonitor.addEventListener("dragover", function (e) {
  15057. _this.drag(e);
  15058. }, false);
  15059. this.elementToMonitor.addEventListener("drop", function (e) {
  15060. _this.drop(e);
  15061. }, false);
  15062. }
  15063. };
  15064. FilesInput.prototype.renderFunction = function () {
  15065. if (this.additionnalRenderLoopLogicCallback) {
  15066. this.additionnalRenderLoopLogicCallback();
  15067. }
  15068. if (this.currentScene) {
  15069. if (this.textureLoadingCallback) {
  15070. var remaining = this.currentScene.getWaitingItemsCount();
  15071. if (remaining > 0) {
  15072. this.textureLoadingCallback(remaining);
  15073. }
  15074. }
  15075. this.currentScene.render();
  15076. }
  15077. };
  15078. FilesInput.prototype.drag = function (e) {
  15079. e.stopPropagation();
  15080. e.preventDefault();
  15081. };
  15082. FilesInput.prototype.drop = function (eventDrop) {
  15083. eventDrop.stopPropagation();
  15084. eventDrop.preventDefault();
  15085. this.loadFiles(eventDrop);
  15086. };
  15087. FilesInput.prototype.loadFiles = function (event) {
  15088. var _this = this;
  15089. var that = this;
  15090. if (this.startingProcessingFilesCallback)
  15091. this.startingProcessingFilesCallback();
  15092. var sceneFileToLoad;
  15093. var filesToLoad;
  15094. if (event && event.dataTransfer && event.dataTransfer.files) {
  15095. filesToLoad = event.dataTransfer.files;
  15096. }
  15097. if (event && event.target && event.target.files) {
  15098. filesToLoad = event.target.files;
  15099. }
  15100. if (filesToLoad && filesToLoad.length > 0) {
  15101. for (var i = 0; i < filesToLoad.length; i++) {
  15102. switch (filesToLoad[i].type) {
  15103. case "image/jpeg":
  15104. case "image/png":
  15105. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  15106. break;
  15107. case "image/targa":
  15108. case "image/vnd.ms-dds":
  15109. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  15110. break;
  15111. default:
  15112. 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) {
  15113. sceneFileToLoad = filesToLoad[i];
  15114. }
  15115. break;
  15116. }
  15117. }
  15118. if (sceneFileToLoad) {
  15119. if (this.currentScene) {
  15120. this.engine.stopRenderLoop();
  15121. this.currentScene.dispose();
  15122. }
  15123. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  15124. that.currentScene = newScene;
  15125. that.currentScene.executeWhenReady(function () {
  15126. if (that.currentScene.activeCamera) {
  15127. that.currentScene.activeCamera.attachControl(that.canvas);
  15128. }
  15129. if (that.sceneLoadedCallback) {
  15130. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  15131. }
  15132. that.engine.runRenderLoop(function () {
  15133. that.renderFunction();
  15134. });
  15135. });
  15136. }, function (progress) {
  15137. if (_this.progressCallback) {
  15138. _this.progressCallback(progress);
  15139. }
  15140. });
  15141. } else {
  15142. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  15143. }
  15144. }
  15145. };
  15146. FilesInput.FilesTextures = new Array();
  15147. FilesInput.FilesToLoad = new Array();
  15148. return FilesInput;
  15149. })();
  15150. BABYLON.FilesInput = FilesInput;
  15151. })(BABYLON || (BABYLON = {}));
  15152. var BABYLON;
  15153. (function (BABYLON) {
  15154. var OimoJSPlugin = (function () {
  15155. function OimoJSPlugin() {
  15156. this._registeredMeshes = [];
  15157. /**
  15158. * Update the body position according to the mesh position
  15159. * @param mesh
  15160. */
  15161. this.updateBodyPosition = function (mesh) {
  15162. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15163. var registeredMesh = this._registeredMeshes[index];
  15164. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  15165. var body = registeredMesh.body.body;
  15166. mesh.computeWorldMatrix(true);
  15167. var center = mesh.getBoundingInfo().boundingBox.center;
  15168. body.setPosition(center.x, center.y, center.z);
  15169. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  15170. return;
  15171. }
  15172. if (registeredMesh.mesh.parent === mesh) {
  15173. mesh.computeWorldMatrix(true);
  15174. registeredMesh.mesh.computeWorldMatrix(true);
  15175. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  15176. var absoluteRotation = mesh.rotation;
  15177. body = registeredMesh.body.body;
  15178. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  15179. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  15180. return;
  15181. }
  15182. }
  15183. };
  15184. }
  15185. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  15186. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  15187. };
  15188. OimoJSPlugin.prototype.initialize = function (iterations) {
  15189. this._world = new OIMO.World();
  15190. this._world.clear();
  15191. };
  15192. OimoJSPlugin.prototype.setGravity = function (gravity) {
  15193. this._world.gravity = gravity;
  15194. };
  15195. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  15196. var body = null;
  15197. this.unregisterMesh(mesh);
  15198. mesh.computeWorldMatrix(true);
  15199. switch (impostor) {
  15200. case BABYLON.PhysicsEngine.SphereImpostor:
  15201. var bbox = mesh.getBoundingInfo().boundingBox;
  15202. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  15203. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  15204. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  15205. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  15206. var deltaPosition = mesh.position.subtract(bbox.center);
  15207. body = new OIMO.Body({
  15208. type: 'sphere',
  15209. size: [size],
  15210. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  15211. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  15212. move: options.mass != 0,
  15213. config: [options.mass, options.friction, options.restitution],
  15214. world: this._world
  15215. });
  15216. this._registeredMeshes.push({
  15217. mesh: mesh,
  15218. body: body,
  15219. delta: deltaPosition
  15220. });
  15221. break;
  15222. case BABYLON.PhysicsEngine.PlaneImpostor:
  15223. case BABYLON.PhysicsEngine.BoxImpostor:
  15224. bbox = mesh.getBoundingInfo().boundingBox;
  15225. var min = bbox.minimumWorld;
  15226. var max = bbox.maximumWorld;
  15227. var box = max.subtract(min);
  15228. var sizeX = this._checkWithEpsilon(box.x);
  15229. var sizeY = this._checkWithEpsilon(box.y);
  15230. var sizeZ = this._checkWithEpsilon(box.z);
  15231. var deltaPosition = mesh.position.subtract(bbox.center);
  15232. body = new OIMO.Body({
  15233. type: 'box',
  15234. size: [sizeX, sizeY, sizeZ],
  15235. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  15236. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  15237. move: options.mass != 0,
  15238. config: [options.mass, options.friction, options.restitution],
  15239. world: this._world
  15240. });
  15241. this._registeredMeshes.push({
  15242. mesh: mesh,
  15243. body: body,
  15244. delta: deltaPosition
  15245. });
  15246. break;
  15247. }
  15248. return body;
  15249. };
  15250. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  15251. var types = [], sizes = [], positions = [], rotations = [];
  15252. var initialMesh = parts[0].mesh;
  15253. for (var index = 0; index < parts.length; index++) {
  15254. var part = parts[index];
  15255. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  15256. types.push(bodyParameters.type);
  15257. sizes.push.apply(sizes, bodyParameters.size);
  15258. positions.push.apply(positions, bodyParameters.pos);
  15259. rotations.push.apply(rotations, bodyParameters.rot);
  15260. }
  15261. var body = new OIMO.Body({
  15262. type: types,
  15263. size: sizes,
  15264. pos: positions,
  15265. rot: rotations,
  15266. move: options.mass != 0,
  15267. config: [options.mass, options.friction, options.restitution],
  15268. world: this._world
  15269. });
  15270. this._registeredMeshes.push({
  15271. mesh: initialMesh,
  15272. body: body
  15273. });
  15274. return body;
  15275. };
  15276. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  15277. var bodyParameters = null;
  15278. var mesh = part.mesh;
  15279. switch (part.impostor) {
  15280. case BABYLON.PhysicsEngine.SphereImpostor:
  15281. var bbox = mesh.getBoundingInfo().boundingBox;
  15282. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  15283. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  15284. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  15285. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  15286. bodyParameters = {
  15287. type: 'sphere',
  15288. /* bug with oimo : sphere needs 3 sizes in this case */
  15289. size: [size, -1, -1],
  15290. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  15291. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  15292. };
  15293. break;
  15294. case BABYLON.PhysicsEngine.PlaneImpostor:
  15295. case BABYLON.PhysicsEngine.BoxImpostor:
  15296. bbox = mesh.getBoundingInfo().boundingBox;
  15297. var min = bbox.minimumWorld;
  15298. var max = bbox.maximumWorld;
  15299. var box = max.subtract(min);
  15300. var sizeX = this._checkWithEpsilon(box.x);
  15301. var sizeY = this._checkWithEpsilon(box.y);
  15302. var sizeZ = this._checkWithEpsilon(box.z);
  15303. var relativePosition = mesh.position;
  15304. bodyParameters = {
  15305. type: 'box',
  15306. size: [sizeX, sizeY, sizeZ],
  15307. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  15308. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  15309. };
  15310. break;
  15311. }
  15312. return bodyParameters;
  15313. };
  15314. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  15315. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15316. var registeredMesh = this._registeredMeshes[index];
  15317. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  15318. if (registeredMesh.body) {
  15319. this._world.removeRigidBody(registeredMesh.body.body);
  15320. this._unbindBody(registeredMesh.body);
  15321. }
  15322. this._registeredMeshes.splice(index, 1);
  15323. return;
  15324. }
  15325. }
  15326. };
  15327. OimoJSPlugin.prototype._unbindBody = function (body) {
  15328. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15329. var registeredMesh = this._registeredMeshes[index];
  15330. if (registeredMesh.body === body) {
  15331. registeredMesh.body = null;
  15332. }
  15333. }
  15334. };
  15335. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  15336. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15337. var registeredMesh = this._registeredMeshes[index];
  15338. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  15339. var mass = registeredMesh.body.body.massInfo.mass;
  15340. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  15341. return;
  15342. }
  15343. }
  15344. };
  15345. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  15346. var body1 = null, body2 = null;
  15347. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15348. var registeredMesh = this._registeredMeshes[index];
  15349. if (registeredMesh.mesh === mesh1) {
  15350. body1 = registeredMesh.body.body;
  15351. } else if (registeredMesh.mesh === mesh2) {
  15352. body2 = registeredMesh.body.body;
  15353. }
  15354. }
  15355. if (!body1 || !body2) {
  15356. return false;
  15357. }
  15358. if (!options) {
  15359. options = {};
  15360. }
  15361. new OIMO.Link({
  15362. type: options.type,
  15363. body1: body1,
  15364. body2: body2,
  15365. min: options.min,
  15366. max: options.max,
  15367. axe1: options.axe1,
  15368. axe2: options.axe2,
  15369. pos1: [pivot1.x, pivot1.y, pivot1.z],
  15370. pos2: [pivot2.x, pivot2.y, pivot2.z],
  15371. collision: options.collision,
  15372. spring: options.spring,
  15373. world: this._world
  15374. });
  15375. return true;
  15376. };
  15377. OimoJSPlugin.prototype.dispose = function () {
  15378. this._world.clear();
  15379. while (this._registeredMeshes.length) {
  15380. this.unregisterMesh(this._registeredMeshes[0].mesh);
  15381. }
  15382. };
  15383. OimoJSPlugin.prototype.isSupported = function () {
  15384. return OIMO !== undefined;
  15385. };
  15386. OimoJSPlugin.prototype._getLastShape = function (body) {
  15387. var lastShape = body.shapes;
  15388. while (lastShape.next) {
  15389. lastShape = lastShape.next;
  15390. }
  15391. return lastShape;
  15392. };
  15393. OimoJSPlugin.prototype.runOneStep = function (time) {
  15394. this._world.step();
  15395. var i = this._registeredMeshes.length;
  15396. var m;
  15397. while (i--) {
  15398. var body = this._registeredMeshes[i].body.body;
  15399. var mesh = this._registeredMeshes[i].mesh;
  15400. var delta = this._registeredMeshes[i].delta;
  15401. if (!body.sleeping) {
  15402. if (body.shapes.next) {
  15403. var parentShape = this._getLastShape(body);
  15404. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  15405. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  15406. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  15407. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  15408. if (!mesh.rotationQuaternion) {
  15409. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  15410. }
  15411. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  15412. mesh.computeWorldMatrix();
  15413. } else {
  15414. m = body.getMatrix();
  15415. mtx = BABYLON.Matrix.FromArray(m);
  15416. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  15417. if (!delta) {
  15418. mesh.position.x = bodyX;
  15419. mesh.position.y = bodyY;
  15420. mesh.position.z = bodyZ;
  15421. } else {
  15422. mesh.position.x = bodyX + delta.x;
  15423. mesh.position.y = bodyY + delta.y;
  15424. mesh.position.z = bodyZ + delta.z;
  15425. }
  15426. if (!mesh.rotationQuaternion) {
  15427. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  15428. }
  15429. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  15430. mesh.computeWorldMatrix();
  15431. }
  15432. }
  15433. }
  15434. };
  15435. return OimoJSPlugin;
  15436. })();
  15437. BABYLON.OimoJSPlugin = OimoJSPlugin;
  15438. })(BABYLON || (BABYLON = {}));
  15439. var BABYLON;
  15440. (function (BABYLON) {
  15441. var PhysicsEngine = (function () {
  15442. function PhysicsEngine(plugin) {
  15443. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  15444. }
  15445. PhysicsEngine.prototype._initialize = function (gravity) {
  15446. this._currentPlugin.initialize();
  15447. this._setGravity(gravity);
  15448. };
  15449. PhysicsEngine.prototype._runOneStep = function (delta) {
  15450. if (delta > 0.1) {
  15451. delta = 0.1;
  15452. } else if (delta <= 0) {
  15453. delta = 1.0 / 60.0;
  15454. }
  15455. this._currentPlugin.runOneStep(delta);
  15456. };
  15457. PhysicsEngine.prototype._setGravity = function (gravity) {
  15458. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  15459. this._currentPlugin.setGravity(this.gravity);
  15460. };
  15461. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  15462. return this._currentPlugin.registerMesh(mesh, impostor, options);
  15463. };
  15464. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  15465. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  15466. };
  15467. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  15468. this._currentPlugin.unregisterMesh(mesh);
  15469. };
  15470. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  15471. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  15472. };
  15473. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  15474. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  15475. };
  15476. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  15477. this._currentPlugin.updateBodyPosition(mesh);
  15478. };
  15479. PhysicsEngine.prototype.dispose = function () {
  15480. this._currentPlugin.dispose();
  15481. };
  15482. PhysicsEngine.prototype.isSupported = function () {
  15483. return this._currentPlugin.isSupported();
  15484. };
  15485. PhysicsEngine.NoImpostor = 0;
  15486. PhysicsEngine.SphereImpostor = 1;
  15487. PhysicsEngine.BoxImpostor = 2;
  15488. PhysicsEngine.PlaneImpostor = 3;
  15489. PhysicsEngine.MeshImpostor = 4;
  15490. PhysicsEngine.CapsuleImpostor = 5;
  15491. PhysicsEngine.ConeImpostor = 6;
  15492. PhysicsEngine.CylinderImpostor = 7;
  15493. PhysicsEngine.ConvexHullImpostor = 8;
  15494. PhysicsEngine.Epsilon = 0.001;
  15495. return PhysicsEngine;
  15496. })();
  15497. BABYLON.PhysicsEngine = PhysicsEngine;
  15498. })(BABYLON || (BABYLON = {}));
  15499. var BABYLON;
  15500. (function (BABYLON) {
  15501. var serializeLight = function (light) {
  15502. var serializationObject = {};
  15503. serializationObject.name = light.name;
  15504. serializationObject.id = light.id;
  15505. serializationObject.tags = BABYLON.Tags.GetTags(light);
  15506. if (light instanceof BABYLON.PointLight) {
  15507. serializationObject.type = 0;
  15508. serializationObject.position = light.position.asArray();
  15509. } else if (light instanceof BABYLON.DirectionalLight) {
  15510. serializationObject.type = 1;
  15511. var directionalLight = light;
  15512. serializationObject.position = directionalLight.position.asArray();
  15513. serializationObject.direction = directionalLight.direction.asArray();
  15514. } else if (light instanceof BABYLON.SpotLight) {
  15515. serializationObject.type = 2;
  15516. var spotLight = light;
  15517. serializationObject.position = spotLight.position.asArray();
  15518. serializationObject.direction = spotLight.position.asArray();
  15519. serializationObject.angle = spotLight.angle;
  15520. serializationObject.exponent = spotLight.exponent;
  15521. } else if (light instanceof BABYLON.HemisphericLight) {
  15522. serializationObject.type = 3;
  15523. var hemisphericLight = light;
  15524. serializationObject.direction = hemisphericLight.direction.asArray();
  15525. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  15526. }
  15527. if (light.intensity) {
  15528. serializationObject.intensity = light.intensity;
  15529. }
  15530. serializationObject.range = light.range;
  15531. serializationObject.diffuse = light.diffuse.asArray();
  15532. serializationObject.specular = light.specular.asArray();
  15533. return serializationObject;
  15534. };
  15535. var serializeFresnelParameter = function (fresnelParameter) {
  15536. var serializationObject = {};
  15537. serializationObject.isEnabled = fresnelParameter.isEnabled;
  15538. serializationObject.leftColor = fresnelParameter.leftColor;
  15539. serializationObject.rightColor = fresnelParameter.rightColor;
  15540. serializationObject.bias = fresnelParameter.bias;
  15541. serializationObject.power = fresnelParameter.power;
  15542. return serializationObject;
  15543. };
  15544. var serializeCamera = function (camera) {
  15545. var serializationObject = {};
  15546. serializationObject.name = camera.name;
  15547. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  15548. serializationObject.id = camera.id;
  15549. serializationObject.position = camera.position.asArray();
  15550. if (camera.parent) {
  15551. serializationObject.parentId = camera.parent.id;
  15552. }
  15553. serializationObject.rotation = camera.rotation.asArray();
  15554. if (camera.lockedTarget && camera.lockedTarget.id) {
  15555. serializationObject.lockedTargetId = camera.lockedTarget.id;
  15556. }
  15557. serializationObject.fov = camera.fov;
  15558. serializationObject.minZ = camera.minZ;
  15559. serializationObject.maxZ = camera.maxZ;
  15560. serializationObject.speed = camera.speed;
  15561. serializationObject.inertia = camera.inertia;
  15562. serializationObject.checkCollisions = camera.checkCollisions;
  15563. serializationObject.applyGravity = camera.applyGravity;
  15564. if (camera.ellipsoid) {
  15565. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  15566. }
  15567. appendAnimations(camera, serializationObject);
  15568. serializationObject.layerMask = camera.layerMask;
  15569. return serializationObject;
  15570. };
  15571. var appendAnimations = function (source, destination) {
  15572. if (source.animations) {
  15573. destination.animations = [];
  15574. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  15575. var animation = source.animations[animationIndex];
  15576. destination.animations.push(serializeAnimation(animation));
  15577. }
  15578. }
  15579. };
  15580. var serializeAnimation = function (animation) {
  15581. var serializationObject = {};
  15582. serializationObject.name = animation.name;
  15583. serializationObject.property = animation.targetProperty;
  15584. serializationObject.framePerSecond = animation.framePerSecond;
  15585. serializationObject.dataType = animation.dataType;
  15586. serializationObject.loopBehavior = animation.loopMode;
  15587. var dataType = animation.dataType;
  15588. serializationObject.keys = [];
  15589. var keys = animation.getKeys();
  15590. for (var index = 0; index < keys.length; index++) {
  15591. var animationKey = keys[index];
  15592. var key = {};
  15593. key.frame = animationKey.frame;
  15594. switch (dataType) {
  15595. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  15596. key.values = [animationKey.value];
  15597. break;
  15598. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  15599. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  15600. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  15601. key.values = animationKey.value.asArray();
  15602. break;
  15603. }
  15604. serializationObject.keys.push(key);
  15605. }
  15606. return serializationObject;
  15607. };
  15608. var serializeMultiMaterial = function (material) {
  15609. var serializationObject = {};
  15610. serializationObject.name = material.name;
  15611. serializationObject.id = material.id;
  15612. serializationObject.tags = BABYLON.Tags.GetTags(material);
  15613. serializationObject.materials = [];
  15614. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  15615. var subMat = material.subMaterials[matIndex];
  15616. if (subMat) {
  15617. serializationObject.materials.push(subMat.id);
  15618. } else {
  15619. serializationObject.materials.push(null);
  15620. }
  15621. }
  15622. return serializationObject;
  15623. };
  15624. var serializeMaterial = function (material) {
  15625. var serializationObject = {};
  15626. serializationObject.name = material.name;
  15627. serializationObject.ambient = material.ambientColor.asArray();
  15628. serializationObject.diffuse = material.diffuseColor.asArray();
  15629. serializationObject.specular = material.specularColor.asArray();
  15630. serializationObject.specularPower = material.specularPower;
  15631. serializationObject.emissive = material.emissiveColor.asArray();
  15632. serializationObject.alpha = material.alpha;
  15633. serializationObject.id = material.id;
  15634. serializationObject.tags = BABYLON.Tags.GetTags(material);
  15635. serializationObject.backFaceCulling = material.backFaceCulling;
  15636. if (material.diffuseTexture) {
  15637. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  15638. }
  15639. if (material.diffuseFresnelParameters) {
  15640. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  15641. }
  15642. if (material.ambientTexture) {
  15643. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  15644. }
  15645. if (material.opacityTexture) {
  15646. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  15647. }
  15648. if (material.opacityFresnelParameters) {
  15649. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  15650. }
  15651. if (material.reflectionTexture) {
  15652. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  15653. }
  15654. if (material.reflectionFresnelParameters) {
  15655. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  15656. }
  15657. if (material.emissiveTexture) {
  15658. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  15659. }
  15660. if (material.emissiveFresnelParameters) {
  15661. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  15662. }
  15663. if (material.specularTexture) {
  15664. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  15665. }
  15666. if (material.bumpTexture) {
  15667. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  15668. }
  15669. return serializationObject;
  15670. };
  15671. var serializeTexture = function (texture) {
  15672. var serializationObject = {};
  15673. if (!texture.name) {
  15674. return null;
  15675. }
  15676. if (texture instanceof BABYLON.CubeTexture) {
  15677. serializationObject.name = texture.name;
  15678. serializationObject.hasAlpha = texture.hasAlpha;
  15679. serializationObject.level = texture.level;
  15680. serializationObject.coordinatesMode = texture.coordinatesMode;
  15681. return serializationObject;
  15682. }
  15683. if (texture instanceof BABYLON.MirrorTexture) {
  15684. var mirrorTexture = texture;
  15685. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  15686. serializationObject.renderList = [];
  15687. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  15688. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  15689. }
  15690. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  15691. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  15692. var renderTargetTexture = texture;
  15693. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  15694. serializationObject.renderList = [];
  15695. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  15696. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  15697. }
  15698. }
  15699. var regularTexture = texture;
  15700. serializationObject.name = texture.name;
  15701. serializationObject.hasAlpha = texture.hasAlpha;
  15702. serializationObject.level = texture.level;
  15703. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  15704. serializationObject.coordinatesMode = texture.coordinatesMode;
  15705. serializationObject.uOffset = regularTexture.uOffset;
  15706. serializationObject.vOffset = regularTexture.vOffset;
  15707. serializationObject.uScale = regularTexture.uScale;
  15708. serializationObject.vScale = regularTexture.vScale;
  15709. serializationObject.uAng = regularTexture.uAng;
  15710. serializationObject.vAng = regularTexture.vAng;
  15711. serializationObject.wAng = regularTexture.wAng;
  15712. serializationObject.wrapU = texture.wrapU;
  15713. serializationObject.wrapV = texture.wrapV;
  15714. appendAnimations(texture, serializationObject);
  15715. return serializationObject;
  15716. };
  15717. var serializeSkeleton = function (skeleton) {
  15718. var serializationObject = {};
  15719. serializationObject.name = skeleton.name;
  15720. serializationObject.id = skeleton.id;
  15721. serializationObject.bones = [];
  15722. for (var index = 0; index < skeleton.bones.length; index++) {
  15723. var bone = skeleton.bones[index];
  15724. var serializedBone = {
  15725. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  15726. name: bone.name,
  15727. matrix: bone.getLocalMatrix().toArray()
  15728. };
  15729. serializationObject.bones.push(serializedBone);
  15730. if (bone.animations && bone.animations.length > 0) {
  15731. serializedBone.animation = serializeAnimation(bone.animations[0]);
  15732. }
  15733. }
  15734. return serializationObject;
  15735. };
  15736. var serializeParticleSystem = function (particleSystem) {
  15737. var serializationObject = {};
  15738. serializationObject.emitterId = particleSystem.emitter.id;
  15739. serializationObject.capacity = particleSystem.getCapacity();
  15740. if (particleSystem.particleTexture) {
  15741. serializationObject.textureName = particleSystem.particleTexture.name;
  15742. }
  15743. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  15744. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  15745. serializationObject.minSize = particleSystem.minSize;
  15746. serializationObject.maxSize = particleSystem.maxSize;
  15747. serializationObject.minLifeTime = particleSystem.minLifeTime;
  15748. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  15749. serializationObject.emitRate = particleSystem.emitRate;
  15750. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  15751. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  15752. serializationObject.gravity = particleSystem.gravity.asArray();
  15753. serializationObject.direction1 = particleSystem.direction1.asArray();
  15754. serializationObject.direction2 = particleSystem.direction2.asArray();
  15755. serializationObject.color1 = particleSystem.color1.asArray();
  15756. serializationObject.color2 = particleSystem.color2.asArray();
  15757. serializationObject.colorDead = particleSystem.colorDead.asArray();
  15758. serializationObject.updateSpeed = particleSystem.updateSpeed;
  15759. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  15760. serializationObject.textureMask = particleSystem.textureMask.asArray();
  15761. serializationObject.blendMode = particleSystem.blendMode;
  15762. return serializationObject;
  15763. };
  15764. var serializeLensFlareSystem = function (lensFlareSystem) {
  15765. var serializationObject = {};
  15766. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  15767. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  15768. serializationObject.flares = [];
  15769. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  15770. var flare = lensFlareSystem.lensFlares[index];
  15771. serializationObject.flares.push({
  15772. size: flare.size,
  15773. position: flare.position,
  15774. color: flare.color.asArray(),
  15775. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  15776. });
  15777. }
  15778. return serializationObject;
  15779. };
  15780. var serializeShadowGenerator = function (light) {
  15781. var serializationObject = {};
  15782. var shadowGenerator = light.getShadowGenerator();
  15783. serializationObject.lightId = light.id;
  15784. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  15785. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  15786. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  15787. serializationObject.renderList = [];
  15788. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  15789. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  15790. serializationObject.renderList.push(mesh.id);
  15791. }
  15792. return serializationObject;
  15793. };
  15794. var serializedGeometries = [];
  15795. var serializeGeometry = function (geometry, serializationGeometries) {
  15796. if (serializedGeometries[geometry.id]) {
  15797. return;
  15798. }
  15799. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  15800. serializationGeometries.boxes.push(serializeBox(geometry));
  15801. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  15802. serializationGeometries.spheres.push(serializeSphere(geometry));
  15803. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  15804. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  15805. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  15806. serializationGeometries.toruses.push(serializeTorus(geometry));
  15807. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  15808. serializationGeometries.grounds.push(serializeGround(geometry));
  15809. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  15810. serializationGeometries.planes.push(serializePlane(geometry));
  15811. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  15812. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  15813. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  15814. throw new Error("Unknow primitive type");
  15815. } else {
  15816. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  15817. }
  15818. serializedGeometries[geometry.id] = true;
  15819. };
  15820. var serializeGeometryBase = function (geometry) {
  15821. var serializationObject = {};
  15822. serializationObject.id = geometry.id;
  15823. if (BABYLON.Tags.HasTags(geometry)) {
  15824. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  15825. }
  15826. return serializationObject;
  15827. };
  15828. var serializeVertexData = function (vertexData) {
  15829. var serializationObject = serializeGeometryBase(vertexData);
  15830. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15831. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15832. }
  15833. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15834. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15835. }
  15836. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15837. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15838. }
  15839. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  15840. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  15841. }
  15842. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  15843. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  15844. }
  15845. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15846. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15847. serializationObject.matricesIndices._isExpanded = true;
  15848. }
  15849. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15850. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  15851. }
  15852. serializationObject.indices = vertexData.getIndices();
  15853. return serializationObject;
  15854. };
  15855. var serializePrimitive = function (primitive) {
  15856. var serializationObject = serializeGeometryBase(primitive);
  15857. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  15858. return serializationObject;
  15859. };
  15860. var serializeBox = function (box) {
  15861. var serializationObject = serializePrimitive(box);
  15862. serializationObject.size = box.size;
  15863. return serializationObject;
  15864. };
  15865. var serializeSphere = function (sphere) {
  15866. var serializationObject = serializePrimitive(sphere);
  15867. serializationObject.segments = sphere.segments;
  15868. serializationObject.diameter = sphere.diameter;
  15869. return serializationObject;
  15870. };
  15871. var serializeCylinder = function (cylinder) {
  15872. var serializationObject = serializePrimitive(cylinder);
  15873. serializationObject.height = cylinder.height;
  15874. serializationObject.diameterTop = cylinder.diameterTop;
  15875. serializationObject.diameterBottom = cylinder.diameterBottom;
  15876. serializationObject.tessellation = cylinder.tessellation;
  15877. return serializationObject;
  15878. };
  15879. var serializeTorus = function (torus) {
  15880. var serializationObject = serializePrimitive(torus);
  15881. serializationObject.diameter = torus.diameter;
  15882. serializationObject.thickness = torus.thickness;
  15883. serializationObject.tessellation = torus.tessellation;
  15884. return serializationObject;
  15885. };
  15886. var serializeGround = function (ground) {
  15887. var serializationObject = serializePrimitive(ground);
  15888. serializationObject.width = ground.width;
  15889. serializationObject.height = ground.height;
  15890. serializationObject.subdivisions = ground.subdivisions;
  15891. return serializationObject;
  15892. };
  15893. var serializePlane = function (plane) {
  15894. var serializationObject = serializePrimitive(plane);
  15895. serializationObject.size = plane.size;
  15896. return serializationObject;
  15897. };
  15898. var serializeTorusKnot = function (torusKnot) {
  15899. var serializationObject = serializePrimitive(torusKnot);
  15900. serializationObject.radius = torusKnot.radius;
  15901. serializationObject.tube = torusKnot.tube;
  15902. serializationObject.radialSegments = torusKnot.radialSegments;
  15903. serializationObject.tubularSegments = torusKnot.tubularSegments;
  15904. serializationObject.p = torusKnot.p;
  15905. serializationObject.q = torusKnot.q;
  15906. return serializationObject;
  15907. };
  15908. var serializeMesh = function (mesh, serializationScene) {
  15909. var serializationObject = {};
  15910. serializationObject.name = mesh.name;
  15911. serializationObject.id = mesh.id;
  15912. if (BABYLON.Tags.HasTags(mesh)) {
  15913. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  15914. }
  15915. serializationObject.position = mesh.position.asArray();
  15916. if (mesh.rotationQuaternion) {
  15917. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  15918. } else if (mesh.rotation) {
  15919. serializationObject.rotation = mesh.rotation.asArray();
  15920. }
  15921. serializationObject.scaling = mesh.scaling.asArray();
  15922. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  15923. serializationObject.isEnabled = mesh.isEnabled();
  15924. serializationObject.isVisible = mesh.isVisible;
  15925. serializationObject.infiniteDistance = mesh.infiniteDistance;
  15926. serializationObject.pickable = mesh.isPickable;
  15927. serializationObject.receiveShadows = mesh.receiveShadows;
  15928. serializationObject.billboardMode = mesh.billboardMode;
  15929. serializationObject.visibility = mesh.visibility;
  15930. serializationObject.checkCollisions = mesh.checkCollisions;
  15931. if (mesh.parent) {
  15932. serializationObject.parentId = mesh.parent.id;
  15933. }
  15934. var geometry = mesh._geometry;
  15935. if (geometry) {
  15936. var geometryId = geometry.id;
  15937. serializationObject.geometryId = geometryId;
  15938. if (!mesh.getScene().getGeometryByID(geometryId)) {
  15939. serializeGeometry(geometry, serializationScene.geometries);
  15940. }
  15941. serializationObject.subMeshes = [];
  15942. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  15943. var subMesh = mesh.subMeshes[subIndex];
  15944. serializationObject.subMeshes.push({
  15945. materialIndex: subMesh.materialIndex,
  15946. verticesStart: subMesh.verticesStart,
  15947. verticesCount: subMesh.verticesCount,
  15948. indexStart: subMesh.indexStart,
  15949. indexCount: subMesh.indexCount
  15950. });
  15951. }
  15952. }
  15953. if (mesh.material) {
  15954. serializationObject.materialId = mesh.material.id;
  15955. } else {
  15956. mesh.material = null;
  15957. }
  15958. if (mesh.skeleton) {
  15959. serializationObject.skeletonId = mesh.skeleton.id;
  15960. }
  15961. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  15962. serializationObject.physicsMass = mesh.getPhysicsMass();
  15963. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  15964. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  15965. switch (mesh.getPhysicsImpostor()) {
  15966. case BABYLON.PhysicsEngine.BoxImpostor:
  15967. serializationObject.physicsImpostor = 1;
  15968. break;
  15969. case BABYLON.PhysicsEngine.SphereImpostor:
  15970. serializationObject.physicsImpostor = 2;
  15971. break;
  15972. }
  15973. }
  15974. serializationObject.instances = [];
  15975. for (var index = 0; index < mesh.instances.length; index++) {
  15976. var instance = mesh.instances[index];
  15977. var serializationInstance = {
  15978. name: instance.name,
  15979. position: instance.position,
  15980. rotation: instance.rotation,
  15981. rotationQuaternion: instance.rotationQuaternion,
  15982. scaling: instance.scaling
  15983. };
  15984. serializationObject.instances.push(serializationInstance);
  15985. appendAnimations(instance, serializationInstance);
  15986. }
  15987. appendAnimations(mesh, serializationObject);
  15988. serializationObject.layerMask = mesh.layerMask;
  15989. return serializationObject;
  15990. };
  15991. var SceneSerializer = (function () {
  15992. function SceneSerializer() {
  15993. }
  15994. SceneSerializer.Serialize = function (scene) {
  15995. var serializationObject = {};
  15996. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  15997. serializationObject.autoClear = scene.autoClear;
  15998. serializationObject.clearColor = scene.clearColor.asArray();
  15999. serializationObject.ambientColor = scene.ambientColor.asArray();
  16000. serializationObject.gravity = scene.gravity.asArray();
  16001. if (scene.fogMode && scene.fogMode !== 0) {
  16002. serializationObject.fogMode = scene.fogMode;
  16003. serializationObject.fogColor = scene.fogColor.asArray();
  16004. serializationObject.fogStart = scene.fogStart;
  16005. serializationObject.fogEnd = scene.fogEnd;
  16006. serializationObject.fogDensity = scene.fogDensity;
  16007. }
  16008. serializationObject.lights = [];
  16009. for (var index = 0; index < scene.lights.length; index++) {
  16010. var light = scene.lights[index];
  16011. serializationObject.lights.push(serializeLight(light));
  16012. }
  16013. serializationObject.cameras = [];
  16014. for (index = 0; index < scene.cameras.length; index++) {
  16015. var camera = scene.cameras[index];
  16016. if (camera instanceof BABYLON.FreeCamera) {
  16017. serializationObject.cameras.push(serializeCamera(camera));
  16018. }
  16019. }
  16020. if (scene.activeCamera) {
  16021. serializationObject.activeCameraID = scene.activeCamera.id;
  16022. }
  16023. serializationObject.materials = [];
  16024. serializationObject.multiMaterials = [];
  16025. for (index = 0; index < scene.materials.length; index++) {
  16026. var material = scene.materials[index];
  16027. if (material instanceof BABYLON.StandardMaterial) {
  16028. serializationObject.materials.push(serializeMaterial(material));
  16029. } else if (material instanceof BABYLON.MultiMaterial) {
  16030. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  16031. }
  16032. }
  16033. serializationObject.skeletons = [];
  16034. for (index = 0; index < scene.skeletons.length; index++) {
  16035. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  16036. }
  16037. serializationObject.geometries = {};
  16038. serializationObject.geometries.boxes = [];
  16039. serializationObject.geometries.spheres = [];
  16040. serializationObject.geometries.cylinders = [];
  16041. serializationObject.geometries.toruses = [];
  16042. serializationObject.geometries.grounds = [];
  16043. serializationObject.geometries.planes = [];
  16044. serializationObject.geometries.torusKnots = [];
  16045. serializationObject.geometries.vertexData = [];
  16046. serializedGeometries = [];
  16047. var geometries = scene.getGeometries();
  16048. for (var index = 0; index < geometries.length; index++) {
  16049. var geometry = geometries[index];
  16050. if (geometry.isReady()) {
  16051. serializeGeometry(geometry, serializationObject.geometries);
  16052. }
  16053. }
  16054. serializationObject.meshes = [];
  16055. for (index = 0; index < scene.meshes.length; index++) {
  16056. var abstractMesh = scene.meshes[index];
  16057. if (abstractMesh instanceof BABYLON.Mesh) {
  16058. var mesh = abstractMesh;
  16059. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  16060. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  16061. }
  16062. }
  16063. }
  16064. serializationObject.particleSystems = [];
  16065. for (index = 0; index < scene.particleSystems.length; index++) {
  16066. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  16067. }
  16068. serializationObject.lensFlareSystems = [];
  16069. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  16070. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  16071. }
  16072. serializationObject.shadowGenerators = [];
  16073. for (index = 0; index < scene.lights.length; index++) {
  16074. light = scene.lights[index];
  16075. if (light.getShadowGenerator()) {
  16076. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  16077. }
  16078. }
  16079. return serializationObject;
  16080. };
  16081. return SceneSerializer;
  16082. })();
  16083. BABYLON.SceneSerializer = SceneSerializer;
  16084. })(BABYLON || (BABYLON = {}));
  16085. var BABYLON;
  16086. (function (BABYLON) {
  16087. var SceneLoader = (function () {
  16088. function SceneLoader() {
  16089. }
  16090. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  16091. get: function () {
  16092. return SceneLoader._ForceFullSceneLoadingForIncremental;
  16093. },
  16094. set: function (value) {
  16095. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  16096. },
  16097. enumerable: true,
  16098. configurable: true
  16099. });
  16100. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  16101. get: function () {
  16102. return SceneLoader._ShowLoadingScreen;
  16103. },
  16104. set: function (value) {
  16105. SceneLoader._ShowLoadingScreen = value;
  16106. },
  16107. enumerable: true,
  16108. configurable: true
  16109. });
  16110. SceneLoader._getPluginForFilename = function (sceneFilename) {
  16111. var dotPosition = sceneFilename.lastIndexOf(".");
  16112. var queryStringPosition = sceneFilename.indexOf("?");
  16113. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  16114. for (var index = 0; index < this._registeredPlugins.length; index++) {
  16115. var plugin = this._registeredPlugins[index];
  16116. if (plugin.extensions.indexOf(extension) !== -1) {
  16117. return plugin;
  16118. }
  16119. }
  16120. return this._registeredPlugins[this._registeredPlugins.length - 1];
  16121. };
  16122. SceneLoader.RegisterPlugin = function (plugin) {
  16123. plugin.extensions = plugin.extensions.toLowerCase();
  16124. SceneLoader._registeredPlugins.push(plugin);
  16125. };
  16126. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  16127. var manifestChecked = function (success) {
  16128. scene.database = database;
  16129. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  16130. var importMeshFromData = function (data) {
  16131. var meshes = [];
  16132. var particleSystems = [];
  16133. var skeletons = [];
  16134. try {
  16135. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  16136. if (onerror) {
  16137. onerror(scene, 'unable to load the scene');
  16138. }
  16139. return;
  16140. }
  16141. } catch (e) {
  16142. if (onerror) {
  16143. onerror(scene, e);
  16144. }
  16145. return;
  16146. }
  16147. if (onsuccess) {
  16148. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  16149. onsuccess(meshes, particleSystems, skeletons);
  16150. }
  16151. };
  16152. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  16153. importMeshFromData(sceneFilename.substr(5));
  16154. return;
  16155. }
  16156. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  16157. importMeshFromData(data);
  16158. }, progressCallBack, database);
  16159. };
  16160. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  16161. };
  16162. /**
  16163. * Load a scene
  16164. * @param rootUrl a string that defines the root url for scene and resources
  16165. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  16166. * @param engine is the instance of BABYLON.Engine to use to create the scene
  16167. */
  16168. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  16169. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  16170. };
  16171. /**
  16172. * Append a scene
  16173. * @param rootUrl a string that defines the root url for scene and resources
  16174. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  16175. * @param scene is the instance of BABYLON.Scene to append to
  16176. */
  16177. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  16178. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  16179. var database;
  16180. if (SceneLoader.ShowLoadingScreen) {
  16181. scene.getEngine().displayLoadingUI();
  16182. }
  16183. var loadSceneFromData = function (data) {
  16184. scene.database = database;
  16185. if (!plugin.load(scene, data, rootUrl)) {
  16186. if (onerror) {
  16187. onerror(scene);
  16188. }
  16189. scene.getEngine().hideLoadingUI();
  16190. return;
  16191. }
  16192. if (onsuccess) {
  16193. onsuccess(scene);
  16194. }
  16195. if (SceneLoader.ShowLoadingScreen) {
  16196. scene.executeWhenReady(function () {
  16197. scene.getEngine().hideLoadingUI();
  16198. });
  16199. }
  16200. };
  16201. var manifestChecked = function (success) {
  16202. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  16203. };
  16204. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  16205. loadSceneFromData(sceneFilename.substr(5));
  16206. return;
  16207. }
  16208. if (rootUrl.indexOf("file:") === -1) {
  16209. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  16210. } else {
  16211. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  16212. }
  16213. };
  16214. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  16215. SceneLoader._ShowLoadingScreen = true;
  16216. SceneLoader._registeredPlugins = new Array();
  16217. return SceneLoader;
  16218. })();
  16219. BABYLON.SceneLoader = SceneLoader;
  16220. ;
  16221. })(BABYLON || (BABYLON = {}));
  16222. var BABYLON;
  16223. (function (BABYLON) {
  16224. (function (Internals) {
  16225. var checkColors4 = function (colors, count) {
  16226. if (colors.length === count * 3) {
  16227. var colors4 = [];
  16228. for (var index = 0; index < colors.length; index += 3) {
  16229. var newIndex = (index / 3) * 4;
  16230. colors4[newIndex] = colors[index];
  16231. colors4[newIndex + 1] = colors[index + 1];
  16232. colors4[newIndex + 2] = colors[index + 2];
  16233. colors4[newIndex + 3] = 1.0;
  16234. }
  16235. return colors4;
  16236. }
  16237. return colors;
  16238. };
  16239. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  16240. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  16241. texture.name = parsedTexture.name;
  16242. texture.hasAlpha = parsedTexture.hasAlpha;
  16243. texture.level = parsedTexture.level;
  16244. texture.coordinatesMode = parsedTexture.coordinatesMode;
  16245. return texture;
  16246. };
  16247. var loadTexture = function (rootUrl, parsedTexture, scene) {
  16248. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  16249. return null;
  16250. }
  16251. if (parsedTexture.isCube) {
  16252. return loadCubeTexture(rootUrl, parsedTexture, scene);
  16253. }
  16254. var texture;
  16255. if (parsedTexture.mirrorPlane) {
  16256. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  16257. texture._waitingRenderList = parsedTexture.renderList;
  16258. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  16259. } else if (parsedTexture.isRenderTarget) {
  16260. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  16261. texture._waitingRenderList = parsedTexture.renderList;
  16262. } else {
  16263. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  16264. }
  16265. texture.name = parsedTexture.name;
  16266. texture.hasAlpha = parsedTexture.hasAlpha;
  16267. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  16268. texture.level = parsedTexture.level;
  16269. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  16270. texture.coordinatesMode = parsedTexture.coordinatesMode;
  16271. texture.uOffset = parsedTexture.uOffset;
  16272. texture.vOffset = parsedTexture.vOffset;
  16273. texture.uScale = parsedTexture.uScale;
  16274. texture.vScale = parsedTexture.vScale;
  16275. texture.uAng = parsedTexture.uAng;
  16276. texture.vAng = parsedTexture.vAng;
  16277. texture.wAng = parsedTexture.wAng;
  16278. texture.wrapU = parsedTexture.wrapU;
  16279. texture.wrapV = parsedTexture.wrapV;
  16280. if (parsedTexture.animations) {
  16281. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  16282. var parsedAnimation = parsedTexture.animations[animationIndex];
  16283. texture.animations.push(parseAnimation(parsedAnimation));
  16284. }
  16285. }
  16286. return texture;
  16287. };
  16288. var parseSkeleton = function (parsedSkeleton, scene) {
  16289. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  16290. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  16291. var parsedBone = parsedSkeleton.bones[index];
  16292. var parentBone = null;
  16293. if (parsedBone.parentBoneIndex > -1) {
  16294. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  16295. }
  16296. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  16297. if (parsedBone.animation) {
  16298. bone.animations.push(parseAnimation(parsedBone.animation));
  16299. }
  16300. }
  16301. return skeleton;
  16302. };
  16303. var parseFresnelParameters = function (parsedFresnelParameters) {
  16304. var fresnelParameters = new BABYLON.FresnelParameters();
  16305. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  16306. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  16307. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  16308. fresnelParameters.bias = parsedFresnelParameters.bias;
  16309. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  16310. return fresnelParameters;
  16311. };
  16312. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  16313. var material;
  16314. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  16315. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  16316. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  16317. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  16318. material.specularPower = parsedMaterial.specularPower;
  16319. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  16320. material.alpha = parsedMaterial.alpha;
  16321. material.id = parsedMaterial.id;
  16322. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  16323. material.backFaceCulling = parsedMaterial.backFaceCulling;
  16324. material.wireframe = parsedMaterial.wireframe;
  16325. if (parsedMaterial.diffuseTexture) {
  16326. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  16327. }
  16328. if (parsedMaterial.diffuseFresnelParameters) {
  16329. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  16330. }
  16331. if (parsedMaterial.ambientTexture) {
  16332. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  16333. }
  16334. if (parsedMaterial.opacityTexture) {
  16335. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  16336. }
  16337. if (parsedMaterial.opacityFresnelParameters) {
  16338. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  16339. }
  16340. if (parsedMaterial.reflectionTexture) {
  16341. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  16342. }
  16343. if (parsedMaterial.reflectionFresnelParameters) {
  16344. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  16345. }
  16346. if (parsedMaterial.emissiveTexture) {
  16347. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  16348. }
  16349. if (parsedMaterial.emissiveFresnelParameters) {
  16350. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  16351. }
  16352. if (parsedMaterial.specularTexture) {
  16353. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  16354. }
  16355. if (parsedMaterial.bumpTexture) {
  16356. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  16357. }
  16358. return material;
  16359. };
  16360. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  16361. for (var index = 0; index < parsedData.materials.length; index++) {
  16362. var parsedMaterial = parsedData.materials[index];
  16363. if (parsedMaterial.id === id) {
  16364. return parseMaterial(parsedMaterial, scene, rootUrl);
  16365. }
  16366. }
  16367. return null;
  16368. };
  16369. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  16370. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  16371. multiMaterial.id = parsedMultiMaterial.id;
  16372. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  16373. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  16374. var subMatId = parsedMultiMaterial.materials[matIndex];
  16375. if (subMatId) {
  16376. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  16377. } else {
  16378. multiMaterial.subMaterials.push(null);
  16379. }
  16380. }
  16381. return multiMaterial;
  16382. };
  16383. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  16384. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  16385. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  16386. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  16387. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  16388. var parsedFlare = parsedLensFlareSystem.flares[index];
  16389. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  16390. }
  16391. return lensFlareSystem;
  16392. };
  16393. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  16394. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  16395. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  16396. if (parsedParticleSystem.textureName) {
  16397. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  16398. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  16399. }
  16400. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  16401. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  16402. particleSystem.minSize = parsedParticleSystem.minSize;
  16403. particleSystem.maxSize = parsedParticleSystem.maxSize;
  16404. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  16405. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  16406. particleSystem.emitter = emitter;
  16407. particleSystem.emitRate = parsedParticleSystem.emitRate;
  16408. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  16409. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  16410. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  16411. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  16412. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  16413. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  16414. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  16415. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  16416. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  16417. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  16418. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  16419. particleSystem.blendMode = parsedParticleSystem.blendMode;
  16420. particleSystem.start();
  16421. return particleSystem;
  16422. };
  16423. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  16424. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  16425. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  16426. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  16427. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  16428. shadowGenerator.getShadowMap().renderList.push(mesh);
  16429. }
  16430. if (parsedShadowGenerator.usePoissonSampling) {
  16431. shadowGenerator.usePoissonSampling = true;
  16432. } else {
  16433. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  16434. }
  16435. return shadowGenerator;
  16436. };
  16437. var parseAnimation = function (parsedAnimation) {
  16438. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  16439. var dataType = parsedAnimation.dataType;
  16440. var keys = [];
  16441. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  16442. var key = parsedAnimation.keys[index];
  16443. var data;
  16444. switch (dataType) {
  16445. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  16446. data = key.values[0];
  16447. break;
  16448. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  16449. data = BABYLON.Quaternion.FromArray(key.values);
  16450. break;
  16451. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  16452. data = BABYLON.Matrix.FromArray(key.values);
  16453. break;
  16454. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  16455. default:
  16456. data = BABYLON.Vector3.FromArray(key.values);
  16457. break;
  16458. }
  16459. keys.push({
  16460. frame: key.frame,
  16461. value: data
  16462. });
  16463. }
  16464. animation.setKeys(keys);
  16465. return animation;
  16466. };
  16467. var parseLight = function (parsedLight, scene) {
  16468. var light;
  16469. switch (parsedLight.type) {
  16470. case 0:
  16471. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  16472. break;
  16473. case 1:
  16474. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  16475. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  16476. break;
  16477. case 2:
  16478. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  16479. break;
  16480. case 3:
  16481. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  16482. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  16483. break;
  16484. }
  16485. light.id = parsedLight.id;
  16486. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  16487. if (parsedLight.intensity !== undefined) {
  16488. light.intensity = parsedLight.intensity;
  16489. }
  16490. if (parsedLight.range) {
  16491. light.range = parsedLight.range;
  16492. }
  16493. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  16494. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  16495. if (parsedLight.excludedMeshesIds) {
  16496. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  16497. }
  16498. if (parsedLight.parentId) {
  16499. light._waitingParentId = parsedLight.parentId;
  16500. }
  16501. if (parsedLight.includedOnlyMeshesIds) {
  16502. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  16503. }
  16504. if (parsedLight.animations) {
  16505. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  16506. var parsedAnimation = parsedLight.animations[animationIndex];
  16507. light.animations.push(parseAnimation(parsedAnimation));
  16508. }
  16509. }
  16510. if (parsedLight.autoAnimate) {
  16511. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  16512. }
  16513. };
  16514. var parseCamera = function (parsedCamera, scene) {
  16515. var camera;
  16516. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  16517. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  16518. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  16519. var alpha = parsedCamera.alpha;
  16520. var beta = parsedCamera.beta;
  16521. var radius = parsedCamera.radius;
  16522. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  16523. var eye_space = parsedCamera.eye_space;
  16524. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  16525. } else {
  16526. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  16527. }
  16528. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  16529. var eye_space = parsedCamera.eye_space;
  16530. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  16531. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  16532. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  16533. } else if (parsedCamera.type === "FollowCamera") {
  16534. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  16535. camera.heightOffset = parsedCamera.heightOffset;
  16536. camera.radius = parsedCamera.radius;
  16537. camera.rotationOffset = parsedCamera.rotationOffset;
  16538. if (lockedTargetMesh)
  16539. camera.target = lockedTargetMesh;
  16540. } else if (parsedCamera.type === "GamepadCamera") {
  16541. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  16542. } else if (parsedCamera.type === "OculusCamera") {
  16543. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  16544. } else if (parsedCamera.type === "OculusGamepadCamera") {
  16545. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  16546. } else if (parsedCamera.type === "TouchCamera") {
  16547. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  16548. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  16549. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  16550. } else if (parsedCamera.type === "WebVRCamera") {
  16551. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  16552. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  16553. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  16554. } else {
  16555. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  16556. }
  16557. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  16558. camera.lockedTarget = lockedTargetMesh;
  16559. }
  16560. camera.id = parsedCamera.id;
  16561. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  16562. if (parsedCamera.parentId) {
  16563. camera._waitingParentId = parsedCamera.parentId;
  16564. }
  16565. if (parsedCamera.target) {
  16566. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16567. } else {
  16568. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  16569. }
  16570. camera.fov = parsedCamera.fov;
  16571. camera.minZ = parsedCamera.minZ;
  16572. camera.maxZ = parsedCamera.maxZ;
  16573. camera.speed = parsedCamera.speed;
  16574. camera.inertia = parsedCamera.inertia;
  16575. camera.checkCollisions = parsedCamera.checkCollisions;
  16576. camera.applyGravity = parsedCamera.applyGravity;
  16577. if (parsedCamera.ellipsoid) {
  16578. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  16579. }
  16580. if (parsedCamera.animations) {
  16581. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16582. var parsedAnimation = parsedCamera.animations[animationIndex];
  16583. camera.animations.push(parseAnimation(parsedAnimation));
  16584. }
  16585. }
  16586. if (parsedCamera.autoAnimate) {
  16587. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  16588. }
  16589. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  16590. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  16591. } else {
  16592. camera.layerMask = 0xFFFFFFFF;
  16593. }
  16594. return camera;
  16595. };
  16596. var parseGeometry = function (parsedGeometry, scene) {
  16597. var id = parsedGeometry.id;
  16598. return scene.getGeometryByID(id);
  16599. };
  16600. var parseBox = function (parsedBox, scene) {
  16601. if (parseGeometry(parsedBox, scene)) {
  16602. return null;
  16603. }
  16604. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  16605. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  16606. scene.pushGeometry(box, true);
  16607. return box;
  16608. };
  16609. var parseSphere = function (parsedSphere, scene) {
  16610. if (parseGeometry(parsedSphere, scene)) {
  16611. return null;
  16612. }
  16613. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  16614. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  16615. scene.pushGeometry(sphere, true);
  16616. return sphere;
  16617. };
  16618. var parseCylinder = function (parsedCylinder, scene) {
  16619. if (parseGeometry(parsedCylinder, scene)) {
  16620. return null;
  16621. }
  16622. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  16623. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  16624. scene.pushGeometry(cylinder, true);
  16625. return cylinder;
  16626. };
  16627. var parseTorus = function (parsedTorus, scene) {
  16628. if (parseGeometry(parsedTorus, scene)) {
  16629. return null;
  16630. }
  16631. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  16632. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  16633. scene.pushGeometry(torus, true);
  16634. return torus;
  16635. };
  16636. var parseGround = function (parsedGround, scene) {
  16637. if (parseGeometry(parsedGround, scene)) {
  16638. return null;
  16639. }
  16640. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  16641. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  16642. scene.pushGeometry(ground, true);
  16643. return ground;
  16644. };
  16645. var parsePlane = function (parsedPlane, scene) {
  16646. if (parseGeometry(parsedPlane, scene)) {
  16647. return null;
  16648. }
  16649. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  16650. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  16651. scene.pushGeometry(plane, true);
  16652. return plane;
  16653. };
  16654. var parseTorusKnot = function (parsedTorusKnot, scene) {
  16655. if (parseGeometry(parsedTorusKnot, scene)) {
  16656. return null;
  16657. }
  16658. 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);
  16659. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  16660. scene.pushGeometry(torusKnot, true);
  16661. return torusKnot;
  16662. };
  16663. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  16664. if (parseGeometry(parsedVertexData, scene)) {
  16665. return null;
  16666. }
  16667. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  16668. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  16669. if (parsedVertexData.delayLoadingFile) {
  16670. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16671. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  16672. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  16673. geometry._delayInfo = [];
  16674. if (parsedVertexData.hasUVs) {
  16675. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  16676. }
  16677. if (parsedVertexData.hasUVs2) {
  16678. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  16679. }
  16680. if (parsedVertexData.hasColors) {
  16681. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  16682. }
  16683. if (parsedVertexData.hasMatricesIndices) {
  16684. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  16685. }
  16686. if (parsedVertexData.hasMatricesWeights) {
  16687. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  16688. }
  16689. geometry._delayLoadingFunction = importVertexData;
  16690. } else {
  16691. importVertexData(parsedVertexData, geometry);
  16692. }
  16693. scene.pushGeometry(geometry, true);
  16694. return geometry;
  16695. };
  16696. var parseMesh = function (parsedMesh, scene, rootUrl) {
  16697. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  16698. mesh.id = parsedMesh.id;
  16699. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  16700. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  16701. if (parsedMesh.rotationQuaternion) {
  16702. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  16703. } else if (parsedMesh.rotation) {
  16704. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  16705. }
  16706. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  16707. if (parsedMesh.localMatrix) {
  16708. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  16709. } else if (parsedMesh.pivotMatrix) {
  16710. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  16711. }
  16712. mesh.setEnabled(parsedMesh.isEnabled);
  16713. mesh.isVisible = parsedMesh.isVisible;
  16714. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  16715. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  16716. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  16717. if (parsedMesh.applyFog !== undefined) {
  16718. mesh.applyFog = parsedMesh.applyFog;
  16719. }
  16720. if (parsedMesh.pickable !== undefined) {
  16721. mesh.isPickable = parsedMesh.pickable;
  16722. }
  16723. if (parsedMesh.alphaIndex !== undefined) {
  16724. mesh.alphaIndex = parsedMesh.alphaIndex;
  16725. }
  16726. mesh.receiveShadows = parsedMesh.receiveShadows;
  16727. mesh.billboardMode = parsedMesh.billboardMode;
  16728. if (parsedMesh.visibility !== undefined) {
  16729. mesh.visibility = parsedMesh.visibility;
  16730. }
  16731. mesh.checkCollisions = parsedMesh.checkCollisions;
  16732. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  16733. if (parsedMesh.parentId) {
  16734. mesh._waitingParentId = parsedMesh.parentId;
  16735. }
  16736. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  16737. if (parsedMesh.delayLoadingFile) {
  16738. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16739. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  16740. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  16741. if (parsedMesh._binaryInfo) {
  16742. mesh._binaryInfo = parsedMesh._binaryInfo;
  16743. }
  16744. mesh._delayInfo = [];
  16745. if (parsedMesh.hasUVs) {
  16746. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  16747. }
  16748. if (parsedMesh.hasUVs2) {
  16749. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  16750. }
  16751. if (parsedMesh.hasColors) {
  16752. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  16753. }
  16754. if (parsedMesh.hasMatricesIndices) {
  16755. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  16756. }
  16757. if (parsedMesh.hasMatricesWeights) {
  16758. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  16759. }
  16760. mesh._delayLoadingFunction = importGeometry;
  16761. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  16762. mesh._checkDelayState();
  16763. }
  16764. } else {
  16765. importGeometry(parsedMesh, mesh);
  16766. }
  16767. if (parsedMesh.materialId) {
  16768. mesh.setMaterialByID(parsedMesh.materialId);
  16769. } else {
  16770. mesh.material = null;
  16771. }
  16772. if (parsedMesh.skeletonId > -1) {
  16773. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  16774. }
  16775. if (parsedMesh.physicsImpostor) {
  16776. if (!scene.isPhysicsEnabled()) {
  16777. scene.enablePhysics();
  16778. }
  16779. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  16780. }
  16781. if (parsedMesh.animations) {
  16782. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16783. var parsedAnimation = parsedMesh.animations[animationIndex];
  16784. mesh.animations.push(parseAnimation(parsedAnimation));
  16785. }
  16786. }
  16787. if (parsedMesh.autoAnimate) {
  16788. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  16789. }
  16790. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  16791. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  16792. } else {
  16793. mesh.layerMask = 0xFFFFFFFF;
  16794. }
  16795. if (parsedMesh.instances) {
  16796. for (var index = 0; index < parsedMesh.instances.length; index++) {
  16797. var parsedInstance = parsedMesh.instances[index];
  16798. var instance = mesh.createInstance(parsedInstance.name);
  16799. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  16800. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  16801. if (parsedInstance.rotationQuaternion) {
  16802. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  16803. } else if (parsedInstance.rotation) {
  16804. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  16805. }
  16806. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  16807. instance.checkCollisions = mesh.checkCollisions;
  16808. if (parsedMesh.animations) {
  16809. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16810. parsedAnimation = parsedMesh.animations[animationIndex];
  16811. instance.animations.push(parseAnimation(parsedAnimation));
  16812. }
  16813. }
  16814. }
  16815. }
  16816. return mesh;
  16817. };
  16818. var isDescendantOf = function (mesh, names, hierarchyIds) {
  16819. names = (names instanceof Array) ? names : [names];
  16820. for (var i in names) {
  16821. if (mesh.name === names[i]) {
  16822. hierarchyIds.push(mesh.id);
  16823. return true;
  16824. }
  16825. }
  16826. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  16827. hierarchyIds.push(mesh.id);
  16828. return true;
  16829. }
  16830. return false;
  16831. };
  16832. var importVertexData = function (parsedVertexData, geometry) {
  16833. var vertexData = new BABYLON.VertexData();
  16834. var positions = parsedVertexData.positions;
  16835. if (positions) {
  16836. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  16837. }
  16838. var normals = parsedVertexData.normals;
  16839. if (normals) {
  16840. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  16841. }
  16842. var uvs = parsedVertexData.uvs;
  16843. if (uvs) {
  16844. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  16845. }
  16846. var uv2s = parsedVertexData.uv2s;
  16847. if (uv2s) {
  16848. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  16849. }
  16850. var colors = parsedVertexData.colors;
  16851. if (colors) {
  16852. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  16853. }
  16854. var matricesIndices = parsedVertexData.matricesIndices;
  16855. if (matricesIndices) {
  16856. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  16857. }
  16858. var matricesWeights = parsedVertexData.matricesWeights;
  16859. if (matricesWeights) {
  16860. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  16861. }
  16862. var indices = parsedVertexData.indices;
  16863. if (indices) {
  16864. vertexData.indices = indices;
  16865. }
  16866. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  16867. };
  16868. var importGeometry = function (parsedGeometry, mesh) {
  16869. var scene = mesh.getScene();
  16870. var geometryId = parsedGeometry.geometryId;
  16871. if (geometryId) {
  16872. var geometry = scene.getGeometryByID(geometryId);
  16873. if (geometry) {
  16874. geometry.applyToMesh(mesh);
  16875. }
  16876. } else if (parsedGeometry instanceof ArrayBuffer) {
  16877. var binaryInfo = mesh._binaryInfo;
  16878. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  16879. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  16880. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  16881. }
  16882. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  16883. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  16884. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  16885. }
  16886. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  16887. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  16888. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  16889. }
  16890. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  16891. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  16892. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  16893. }
  16894. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  16895. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  16896. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  16897. }
  16898. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  16899. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  16900. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  16901. }
  16902. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  16903. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  16904. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  16905. }
  16906. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  16907. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  16908. mesh.setIndices(indicesData);
  16909. }
  16910. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  16911. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  16912. mesh.subMeshes = [];
  16913. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  16914. var materialIndex = subMeshesData[(i * 5) + 0];
  16915. var verticesStart = subMeshesData[(i * 5) + 1];
  16916. var verticesCount = subMeshesData[(i * 5) + 2];
  16917. var indexStart = subMeshesData[(i * 5) + 3];
  16918. var indexCount = subMeshesData[(i * 5) + 4];
  16919. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  16920. }
  16921. }
  16922. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  16923. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  16924. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  16925. if (parsedGeometry.uvs) {
  16926. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  16927. }
  16928. if (parsedGeometry.uvs2) {
  16929. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  16930. }
  16931. if (parsedGeometry.colors) {
  16932. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  16933. }
  16934. if (parsedGeometry.matricesIndices) {
  16935. if (!parsedGeometry.matricesIndices._isExpanded) {
  16936. var floatIndices = [];
  16937. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  16938. var matricesIndex = parsedGeometry.matricesIndices[i];
  16939. floatIndices.push(matricesIndex & 0x000000FF);
  16940. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  16941. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  16942. floatIndices.push(matricesIndex >> 24);
  16943. }
  16944. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  16945. } else {
  16946. delete parsedGeometry.matricesIndices._isExpanded;
  16947. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  16948. }
  16949. }
  16950. if (parsedGeometry.matricesWeights) {
  16951. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  16952. }
  16953. mesh.setIndices(parsedGeometry.indices);
  16954. if (parsedGeometry.subMeshes) {
  16955. mesh.subMeshes = [];
  16956. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  16957. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  16958. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  16959. }
  16960. }
  16961. }
  16962. if (mesh._shouldGenerateFlatShading) {
  16963. mesh.convertToFlatShadedMesh();
  16964. delete mesh._shouldGenerateFlatShading;
  16965. }
  16966. mesh.computeWorldMatrix(true);
  16967. if (scene._selectionOctree) {
  16968. scene._selectionOctree.addMesh(mesh);
  16969. }
  16970. };
  16971. BABYLON.SceneLoader.RegisterPlugin({
  16972. extensions: ".babylon",
  16973. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  16974. var parsedData = JSON.parse(data);
  16975. var loadedSkeletonsIds = [];
  16976. var loadedMaterialsIds = [];
  16977. var hierarchyIds = [];
  16978. for (var index = 0; index < parsedData.meshes.length; index++) {
  16979. var parsedMesh = parsedData.meshes[index];
  16980. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  16981. if (meshesNames instanceof Array) {
  16982. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  16983. }
  16984. if (parsedMesh.materialId) {
  16985. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  16986. if (!materialFound) {
  16987. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  16988. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  16989. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  16990. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  16991. var subMatId = parsedMultiMaterial.materials[matIndex];
  16992. loadedMaterialsIds.push(subMatId);
  16993. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  16994. }
  16995. loadedMaterialsIds.push(parsedMultiMaterial.id);
  16996. parseMultiMaterial(parsedMultiMaterial, scene);
  16997. materialFound = true;
  16998. break;
  16999. }
  17000. }
  17001. }
  17002. if (!materialFound) {
  17003. loadedMaterialsIds.push(parsedMesh.materialId);
  17004. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  17005. }
  17006. }
  17007. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  17008. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  17009. if (!skeletonAlreadyLoaded) {
  17010. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  17011. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  17012. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  17013. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  17014. loadedSkeletonsIds.push(parsedSkeleton.id);
  17015. }
  17016. }
  17017. }
  17018. }
  17019. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  17020. meshes.push(mesh);
  17021. }
  17022. }
  17023. for (index = 0; index < scene.meshes.length; index++) {
  17024. var currentMesh = scene.meshes[index];
  17025. if (currentMesh._waitingParentId) {
  17026. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  17027. currentMesh._waitingParentId = undefined;
  17028. }
  17029. }
  17030. if (parsedData.particleSystems) {
  17031. for (index = 0; index < parsedData.particleSystems.length; index++) {
  17032. var parsedParticleSystem = parsedData.particleSystems[index];
  17033. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  17034. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  17035. }
  17036. }
  17037. }
  17038. return true;
  17039. },
  17040. load: function (scene, data, rootUrl) {
  17041. var parsedData = JSON.parse(data);
  17042. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  17043. scene.autoClear = parsedData.autoClear;
  17044. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  17045. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  17046. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  17047. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  17048. scene.fogMode = parsedData.fogMode;
  17049. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  17050. scene.fogStart = parsedData.fogStart;
  17051. scene.fogEnd = parsedData.fogEnd;
  17052. scene.fogDensity = parsedData.fogDensity;
  17053. }
  17054. for (var index = 0; index < parsedData.lights.length; index++) {
  17055. var parsedLight = parsedData.lights[index];
  17056. parseLight(parsedLight, scene);
  17057. }
  17058. if (parsedData.materials) {
  17059. for (index = 0; index < parsedData.materials.length; index++) {
  17060. var parsedMaterial = parsedData.materials[index];
  17061. parseMaterial(parsedMaterial, scene, rootUrl);
  17062. }
  17063. }
  17064. if (parsedData.multiMaterials) {
  17065. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  17066. var parsedMultiMaterial = parsedData.multiMaterials[index];
  17067. parseMultiMaterial(parsedMultiMaterial, scene);
  17068. }
  17069. }
  17070. if (parsedData.skeletons) {
  17071. for (index = 0; index < parsedData.skeletons.length; index++) {
  17072. var parsedSkeleton = parsedData.skeletons[index];
  17073. parseSkeleton(parsedSkeleton, scene);
  17074. }
  17075. }
  17076. var geometries = parsedData.geometries;
  17077. if (geometries) {
  17078. var boxes = geometries.boxes;
  17079. if (boxes) {
  17080. for (index = 0; index < boxes.length; index++) {
  17081. var parsedBox = boxes[index];
  17082. parseBox(parsedBox, scene);
  17083. }
  17084. }
  17085. var spheres = geometries.spheres;
  17086. if (spheres) {
  17087. for (index = 0; index < spheres.length; index++) {
  17088. var parsedSphere = spheres[index];
  17089. parseSphere(parsedSphere, scene);
  17090. }
  17091. }
  17092. var cylinders = geometries.cylinders;
  17093. if (cylinders) {
  17094. for (index = 0; index < cylinders.length; index++) {
  17095. var parsedCylinder = cylinders[index];
  17096. parseCylinder(parsedCylinder, scene);
  17097. }
  17098. }
  17099. var toruses = geometries.toruses;
  17100. if (toruses) {
  17101. for (index = 0; index < toruses.length; index++) {
  17102. var parsedTorus = toruses[index];
  17103. parseTorus(parsedTorus, scene);
  17104. }
  17105. }
  17106. var grounds = geometries.grounds;
  17107. if (grounds) {
  17108. for (index = 0; index < grounds.length; index++) {
  17109. var parsedGround = grounds[index];
  17110. parseGround(parsedGround, scene);
  17111. }
  17112. }
  17113. var planes = geometries.planes;
  17114. if (planes) {
  17115. for (index = 0; index < planes.length; index++) {
  17116. var parsedPlane = planes[index];
  17117. parsePlane(parsedPlane, scene);
  17118. }
  17119. }
  17120. var torusKnots = geometries.torusKnots;
  17121. if (torusKnots) {
  17122. for (index = 0; index < torusKnots.length; index++) {
  17123. var parsedTorusKnot = torusKnots[index];
  17124. parseTorusKnot(parsedTorusKnot, scene);
  17125. }
  17126. }
  17127. var vertexData = geometries.vertexData;
  17128. if (vertexData) {
  17129. for (index = 0; index < vertexData.length; index++) {
  17130. var parsedVertexData = vertexData[index];
  17131. parseVertexData(parsedVertexData, scene, rootUrl);
  17132. }
  17133. }
  17134. }
  17135. for (index = 0; index < parsedData.meshes.length; index++) {
  17136. var parsedMesh = parsedData.meshes[index];
  17137. parseMesh(parsedMesh, scene, rootUrl);
  17138. }
  17139. for (index = 0; index < parsedData.cameras.length; index++) {
  17140. var parsedCamera = parsedData.cameras[index];
  17141. parseCamera(parsedCamera, scene);
  17142. }
  17143. if (parsedData.activeCameraID) {
  17144. scene.setActiveCameraByID(parsedData.activeCameraID);
  17145. }
  17146. for (index = 0; index < scene.cameras.length; index++) {
  17147. var camera = scene.cameras[index];
  17148. if (camera._waitingParentId) {
  17149. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  17150. camera._waitingParentId = undefined;
  17151. }
  17152. }
  17153. for (index = 0; index < scene.lights.length; index++) {
  17154. var light = scene.lights[index];
  17155. if (light._waitingParentId) {
  17156. light.parent = scene.getLastEntryByID(light._waitingParentId);
  17157. light._waitingParentId = undefined;
  17158. }
  17159. }
  17160. for (index = 0; index < scene.meshes.length; index++) {
  17161. var mesh = scene.meshes[index];
  17162. if (mesh._waitingParentId) {
  17163. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  17164. mesh._waitingParentId = undefined;
  17165. }
  17166. }
  17167. if (parsedData.particleSystems) {
  17168. for (index = 0; index < parsedData.particleSystems.length; index++) {
  17169. var parsedParticleSystem = parsedData.particleSystems[index];
  17170. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  17171. }
  17172. }
  17173. if (parsedData.lensFlareSystems) {
  17174. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  17175. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  17176. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  17177. }
  17178. }
  17179. if (parsedData.shadowGenerators) {
  17180. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  17181. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  17182. parseShadowGenerator(parsedShadowGenerator, scene);
  17183. }
  17184. }
  17185. return true;
  17186. }
  17187. });
  17188. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17189. var Internals = BABYLON.Internals;
  17190. })(BABYLON || (BABYLON = {}));
  17191. var BABYLON;
  17192. (function (BABYLON) {
  17193. var currentCSGMeshId = 0;
  17194. var Vertex = (function () {
  17195. function Vertex(pos, normal, uv) {
  17196. this.pos = pos;
  17197. this.normal = normal;
  17198. this.uv = uv;
  17199. }
  17200. Vertex.prototype.clone = function () {
  17201. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  17202. };
  17203. Vertex.prototype.flip = function () {
  17204. this.normal = this.normal.scale(-1);
  17205. };
  17206. Vertex.prototype.interpolate = function (other, t) {
  17207. 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));
  17208. };
  17209. return Vertex;
  17210. })();
  17211. var Plane = (function () {
  17212. function Plane(normal, w) {
  17213. this.normal = normal;
  17214. this.w = w;
  17215. }
  17216. Plane.FromPoints = function (a, b, c) {
  17217. var v0 = c.subtract(a);
  17218. var v1 = b.subtract(a);
  17219. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  17220. return null;
  17221. }
  17222. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  17223. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  17224. };
  17225. Plane.prototype.clone = function () {
  17226. return new Plane(this.normal.clone(), this.w);
  17227. };
  17228. Plane.prototype.flip = function () {
  17229. this.normal.scaleInPlace(-1);
  17230. this.w = -this.w;
  17231. };
  17232. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  17233. var COPLANAR = 0;
  17234. var FRONT = 1;
  17235. var BACK = 2;
  17236. var SPANNING = 3;
  17237. var polygonType = 0;
  17238. var types = [];
  17239. for (var i = 0; i < polygon.vertices.length; i++) {
  17240. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  17241. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  17242. polygonType |= type;
  17243. types.push(type);
  17244. }
  17245. switch (polygonType) {
  17246. case COPLANAR:
  17247. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  17248. break;
  17249. case FRONT:
  17250. front.push(polygon);
  17251. break;
  17252. case BACK:
  17253. back.push(polygon);
  17254. break;
  17255. case SPANNING:
  17256. var f = [], b = [];
  17257. for (i = 0; i < polygon.vertices.length; i++) {
  17258. var j = (i + 1) % polygon.vertices.length;
  17259. var ti = types[i], tj = types[j];
  17260. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  17261. if (ti != BACK)
  17262. f.push(vi);
  17263. if (ti != FRONT)
  17264. b.push(ti != BACK ? vi.clone() : vi);
  17265. if ((ti | tj) == SPANNING) {
  17266. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  17267. var v = vi.interpolate(vj, t);
  17268. f.push(v);
  17269. b.push(v.clone());
  17270. }
  17271. }
  17272. if (f.length >= 3) {
  17273. var poly = new Polygon(f, polygon.shared);
  17274. if (poly.plane)
  17275. front.push(poly);
  17276. }
  17277. if (b.length >= 3) {
  17278. poly = new Polygon(b, polygon.shared);
  17279. if (poly.plane)
  17280. back.push(poly);
  17281. }
  17282. break;
  17283. }
  17284. };
  17285. Plane.EPSILON = 1e-5;
  17286. return Plane;
  17287. })();
  17288. var Polygon = (function () {
  17289. function Polygon(vertices, shared) {
  17290. this.vertices = vertices;
  17291. this.shared = shared;
  17292. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  17293. }
  17294. Polygon.prototype.clone = function () {
  17295. var vertices = this.vertices.map(function (v) {
  17296. return v.clone();
  17297. });
  17298. return new Polygon(vertices, this.shared);
  17299. };
  17300. Polygon.prototype.flip = function () {
  17301. this.vertices.reverse().map(function (v) {
  17302. v.flip();
  17303. });
  17304. this.plane.flip();
  17305. };
  17306. return Polygon;
  17307. })();
  17308. var Node = (function () {
  17309. function Node(polygons) {
  17310. this.plane = null;
  17311. this.front = null;
  17312. this.back = null;
  17313. this.polygons = [];
  17314. if (polygons) {
  17315. this.build(polygons);
  17316. }
  17317. }
  17318. Node.prototype.clone = function () {
  17319. var node = new Node();
  17320. node.plane = this.plane && this.plane.clone();
  17321. node.front = this.front && this.front.clone();
  17322. node.back = this.back && this.back.clone();
  17323. node.polygons = this.polygons.map(function (p) {
  17324. return p.clone();
  17325. });
  17326. return node;
  17327. };
  17328. Node.prototype.invert = function () {
  17329. for (var i = 0; i < this.polygons.length; i++) {
  17330. this.polygons[i].flip();
  17331. }
  17332. if (this.plane) {
  17333. this.plane.flip();
  17334. }
  17335. if (this.front) {
  17336. this.front.invert();
  17337. }
  17338. if (this.back) {
  17339. this.back.invert();
  17340. }
  17341. var temp = this.front;
  17342. this.front = this.back;
  17343. this.back = temp;
  17344. };
  17345. Node.prototype.clipPolygons = function (polygons) {
  17346. if (!this.plane)
  17347. return polygons.slice();
  17348. var front = [], back = [];
  17349. for (var i = 0; i < polygons.length; i++) {
  17350. this.plane.splitPolygon(polygons[i], front, back, front, back);
  17351. }
  17352. if (this.front) {
  17353. front = this.front.clipPolygons(front);
  17354. }
  17355. if (this.back) {
  17356. back = this.back.clipPolygons(back);
  17357. } else {
  17358. back = [];
  17359. }
  17360. return front.concat(back);
  17361. };
  17362. Node.prototype.clipTo = function (bsp) {
  17363. this.polygons = bsp.clipPolygons(this.polygons);
  17364. if (this.front)
  17365. this.front.clipTo(bsp);
  17366. if (this.back)
  17367. this.back.clipTo(bsp);
  17368. };
  17369. Node.prototype.allPolygons = function () {
  17370. var polygons = this.polygons.slice();
  17371. if (this.front)
  17372. polygons = polygons.concat(this.front.allPolygons());
  17373. if (this.back)
  17374. polygons = polygons.concat(this.back.allPolygons());
  17375. return polygons;
  17376. };
  17377. Node.prototype.build = function (polygons) {
  17378. if (!polygons.length)
  17379. return;
  17380. if (!this.plane)
  17381. this.plane = polygons[0].plane.clone();
  17382. var front = [], back = [];
  17383. for (var i = 0; i < polygons.length; i++) {
  17384. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  17385. }
  17386. if (front.length) {
  17387. if (!this.front)
  17388. this.front = new Node();
  17389. this.front.build(front);
  17390. }
  17391. if (back.length) {
  17392. if (!this.back)
  17393. this.back = new Node();
  17394. this.back.build(back);
  17395. }
  17396. };
  17397. return Node;
  17398. })();
  17399. var CSG = (function () {
  17400. function CSG() {
  17401. this.polygons = new Array();
  17402. }
  17403. CSG.FromMesh = function (mesh) {
  17404. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  17405. if (mesh instanceof BABYLON.Mesh) {
  17406. mesh.computeWorldMatrix(true);
  17407. var matrix = mesh.getWorldMatrix();
  17408. var meshPosition = mesh.position.clone();
  17409. var meshRotation = mesh.rotation.clone();
  17410. var meshScaling = mesh.scaling.clone();
  17411. } else {
  17412. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  17413. }
  17414. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17415. var subMeshes = mesh.subMeshes;
  17416. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  17417. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  17418. vertices = [];
  17419. for (var j = 0; j < 3; j++) {
  17420. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  17421. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  17422. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  17423. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  17424. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  17425. vertex = new Vertex(position, normal, uv);
  17426. vertices.push(vertex);
  17427. }
  17428. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  17429. if (polygon.plane)
  17430. polygons.push(polygon);
  17431. }
  17432. }
  17433. var csg = CSG.FromPolygons(polygons);
  17434. csg.matrix = matrix;
  17435. csg.position = meshPosition;
  17436. csg.rotation = meshRotation;
  17437. csg.scaling = meshScaling;
  17438. currentCSGMeshId++;
  17439. return csg;
  17440. };
  17441. CSG.FromPolygons = function (polygons) {
  17442. var csg = new BABYLON.CSG();
  17443. csg.polygons = polygons;
  17444. return csg;
  17445. };
  17446. CSG.prototype.clone = function () {
  17447. var csg = new BABYLON.CSG();
  17448. csg.polygons = this.polygons.map(function (p) {
  17449. return p.clone();
  17450. });
  17451. csg.copyTransformAttributes(this);
  17452. return csg;
  17453. };
  17454. CSG.prototype.toPolygons = function () {
  17455. return this.polygons;
  17456. };
  17457. CSG.prototype.union = function (csg) {
  17458. var a = new Node(this.clone().polygons);
  17459. var b = new Node(csg.clone().polygons);
  17460. a.clipTo(b);
  17461. b.clipTo(a);
  17462. b.invert();
  17463. b.clipTo(a);
  17464. b.invert();
  17465. a.build(b.allPolygons());
  17466. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  17467. };
  17468. CSG.prototype.unionInPlace = function (csg) {
  17469. var a = new Node(this.polygons);
  17470. var b = new Node(csg.polygons);
  17471. a.clipTo(b);
  17472. b.clipTo(a);
  17473. b.invert();
  17474. b.clipTo(a);
  17475. b.invert();
  17476. a.build(b.allPolygons());
  17477. this.polygons = a.allPolygons();
  17478. };
  17479. CSG.prototype.subtract = function (csg) {
  17480. var a = new Node(this.clone().polygons);
  17481. var b = new Node(csg.clone().polygons);
  17482. a.invert();
  17483. a.clipTo(b);
  17484. b.clipTo(a);
  17485. b.invert();
  17486. b.clipTo(a);
  17487. b.invert();
  17488. a.build(b.allPolygons());
  17489. a.invert();
  17490. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  17491. };
  17492. CSG.prototype.subtractInPlace = function (csg) {
  17493. var a = new Node(this.polygons);
  17494. var b = new Node(csg.polygons);
  17495. a.invert();
  17496. a.clipTo(b);
  17497. b.clipTo(a);
  17498. b.invert();
  17499. b.clipTo(a);
  17500. b.invert();
  17501. a.build(b.allPolygons());
  17502. a.invert();
  17503. this.polygons = a.allPolygons();
  17504. };
  17505. CSG.prototype.intersect = function (csg) {
  17506. var a = new Node(this.clone().polygons);
  17507. var b = new Node(csg.clone().polygons);
  17508. a.invert();
  17509. b.clipTo(a);
  17510. b.invert();
  17511. a.clipTo(b);
  17512. b.clipTo(a);
  17513. a.build(b.allPolygons());
  17514. a.invert();
  17515. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  17516. };
  17517. CSG.prototype.intersectInPlace = function (csg) {
  17518. var a = new Node(this.polygons);
  17519. var b = new Node(csg.polygons);
  17520. a.invert();
  17521. b.clipTo(a);
  17522. b.invert();
  17523. a.clipTo(b);
  17524. b.clipTo(a);
  17525. a.build(b.allPolygons());
  17526. a.invert();
  17527. this.polygons = a.allPolygons();
  17528. };
  17529. CSG.prototype.inverse = function () {
  17530. var csg = this.clone();
  17531. csg.inverseInPlace();
  17532. return csg;
  17533. };
  17534. CSG.prototype.inverseInPlace = function () {
  17535. this.polygons.map(function (p) {
  17536. p.flip();
  17537. });
  17538. };
  17539. CSG.prototype.copyTransformAttributes = function (csg) {
  17540. this.matrix = csg.matrix;
  17541. this.position = csg.position;
  17542. this.rotation = csg.rotation;
  17543. this.scaling = csg.scaling;
  17544. return this;
  17545. };
  17546. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  17547. var matrix = this.matrix.clone();
  17548. matrix.invert();
  17549. 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;
  17550. if (keepSubMeshes) {
  17551. polygons.sort(function (a, b) {
  17552. if (a.shared.meshId === b.shared.meshId) {
  17553. return a.shared.subMeshId - b.shared.subMeshId;
  17554. } else {
  17555. return a.shared.meshId - b.shared.meshId;
  17556. }
  17557. });
  17558. }
  17559. for (var i = 0, il = polygons.length; i < il; i++) {
  17560. polygon = polygons[i];
  17561. if (!subMesh_dict[polygon.shared.meshId]) {
  17562. subMesh_dict[polygon.shared.meshId] = {};
  17563. }
  17564. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  17565. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  17566. indexStart: +Infinity,
  17567. indexEnd: -Infinity,
  17568. materialIndex: polygon.shared.materialIndex
  17569. };
  17570. }
  17571. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  17572. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  17573. polygonIndices[0] = 0;
  17574. polygonIndices[1] = j - 1;
  17575. polygonIndices[2] = j;
  17576. for (var k = 0; k < 3; k++) {
  17577. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  17578. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  17579. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  17580. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  17581. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  17582. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  17583. if (!(typeof vertex_idx !== 'undefined' && normals[vertex_idx * 3] === localNormal.x && normals[vertex_idx * 3 + 1] === localNormal.y && normals[vertex_idx * 3 + 2] === localNormal.z && uvs[vertex_idx * 2] === uv.x && uvs[vertex_idx * 2 + 1] === uv.y)) {
  17584. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  17585. uvs.push(uv.x, uv.y);
  17586. normals.push(normal.x, normal.y, normal.z);
  17587. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  17588. }
  17589. indices.push(vertex_idx);
  17590. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  17591. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  17592. currentIndex++;
  17593. }
  17594. }
  17595. }
  17596. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  17597. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  17598. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  17599. mesh.setIndices(indices);
  17600. if (keepSubMeshes) {
  17601. var materialIndexOffset = 0, materialMaxIndex;
  17602. mesh.subMeshes.length = 0;
  17603. for (var m in subMesh_dict) {
  17604. materialMaxIndex = -1;
  17605. for (var sm in subMesh_dict[m]) {
  17606. subMesh_obj = subMesh_dict[m][sm];
  17607. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  17608. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  17609. }
  17610. materialIndexOffset += ++materialMaxIndex;
  17611. }
  17612. }
  17613. return mesh;
  17614. };
  17615. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  17616. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  17617. mesh.material = material;
  17618. mesh.position.copyFrom(this.position);
  17619. mesh.rotation.copyFrom(this.rotation);
  17620. mesh.scaling.copyFrom(this.scaling);
  17621. mesh.computeWorldMatrix(true);
  17622. return mesh;
  17623. };
  17624. return CSG;
  17625. })();
  17626. BABYLON.CSG = CSG;
  17627. })(BABYLON || (BABYLON = {}));
  17628. var __extends = this.__extends || function (d, b) {
  17629. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17630. function __() { this.constructor = d; }
  17631. __.prototype = b.prototype;
  17632. d.prototype = new __();
  17633. };
  17634. var BABYLON;
  17635. (function (BABYLON) {
  17636. var OculusDistortionCorrectionPostProcess = (function (_super) {
  17637. __extends(OculusDistortionCorrectionPostProcess, _super);
  17638. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  17639. var _this = this;
  17640. _super.call(this, name, "oculusDistortionCorrection", [
  17641. 'LensCenter',
  17642. 'Scale',
  17643. 'ScaleIn',
  17644. 'HmdWarpParam'
  17645. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  17646. this._isRightEye = isRightEye;
  17647. this._distortionFactors = cameraSettings.DistortionK;
  17648. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  17649. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  17650. this.onSizeChanged = function () {
  17651. _this.aspectRatio = _this.width * .5 / _this.height;
  17652. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  17653. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  17654. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  17655. };
  17656. this.onApply = function (effect) {
  17657. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  17658. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  17659. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  17660. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  17661. };
  17662. }
  17663. return OculusDistortionCorrectionPostProcess;
  17664. })(BABYLON.PostProcess);
  17665. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  17666. })(BABYLON || (BABYLON = {}));
  17667. var BABYLON;
  17668. (function (BABYLON) {
  17669. (function (JoystickAxis) {
  17670. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  17671. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  17672. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  17673. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  17674. var JoystickAxis = BABYLON.JoystickAxis;
  17675. var VirtualJoystick = (function () {
  17676. function VirtualJoystick(leftJoystick) {
  17677. var _this = this;
  17678. if (leftJoystick) {
  17679. this._leftJoystick = true;
  17680. } else {
  17681. this._leftJoystick = false;
  17682. }
  17683. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  17684. VirtualJoystick._globalJoystickIndex++;
  17685. this._axisTargetedByLeftAndRight = 0 /* X */;
  17686. this._axisTargetedByUpAndDown = 1 /* Y */;
  17687. this.reverseLeftRight = false;
  17688. this.reverseUpDown = false;
  17689. this._touches = new BABYLON.VirtualJoystick.Collection();
  17690. this.deltaPosition = BABYLON.Vector3.Zero();
  17691. this._joystickSensibility = 25;
  17692. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  17693. this._rotationSpeed = 25;
  17694. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  17695. this._rotateOnAxisRelativeToMesh = false;
  17696. if (!VirtualJoystick.vjCanvas) {
  17697. window.addEventListener("resize", function () {
  17698. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  17699. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  17700. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  17701. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  17702. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  17703. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  17704. }, false);
  17705. VirtualJoystick.vjCanvas = document.createElement("canvas");
  17706. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  17707. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  17708. VirtualJoystick.vjCanvas.width = window.innerWidth;
  17709. VirtualJoystick.vjCanvas.height = window.innerHeight;
  17710. VirtualJoystick.vjCanvas.style.width = "100%";
  17711. VirtualJoystick.vjCanvas.style.height = "100%";
  17712. VirtualJoystick.vjCanvas.style.position = "absolute";
  17713. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  17714. VirtualJoystick.vjCanvas.style.top = "0px";
  17715. VirtualJoystick.vjCanvas.style.left = "0px";
  17716. VirtualJoystick.vjCanvas.style.zIndex = "5";
  17717. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  17718. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  17719. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  17720. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  17721. document.body.appendChild(VirtualJoystick.vjCanvas);
  17722. }
  17723. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  17724. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  17725. this.pressed = false;
  17726. this._joystickColor = "cyan";
  17727. this._joystickPointerID = -1;
  17728. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  17729. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  17730. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  17731. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  17732. _this._onPointerDown(evt);
  17733. }, false);
  17734. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  17735. _this._onPointerMove(evt);
  17736. }, false);
  17737. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  17738. _this._onPointerUp(evt);
  17739. }, false);
  17740. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  17741. _this._onPointerUp(evt);
  17742. }, false);
  17743. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  17744. evt.preventDefault();
  17745. }, false);
  17746. requestAnimationFrame(function () {
  17747. _this._drawVirtualJoystick();
  17748. });
  17749. }
  17750. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  17751. this._joystickSensibility = newJoystickSensibility;
  17752. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  17753. };
  17754. VirtualJoystick.prototype._onPointerDown = function (e) {
  17755. var positionOnScreenCondition;
  17756. e.preventDefault();
  17757. if (this._leftJoystick === true) {
  17758. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  17759. } else {
  17760. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  17761. }
  17762. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  17763. this._joystickPointerID = e.pointerId;
  17764. this._joystickPointerStartPos.x = e.clientX;
  17765. this._joystickPointerStartPos.y = e.clientY;
  17766. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  17767. this._deltaJoystickVector.x = 0;
  17768. this._deltaJoystickVector.y = 0;
  17769. this.pressed = true;
  17770. this._touches.add(e.pointerId.toString(), e);
  17771. } else {
  17772. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  17773. this._action();
  17774. this._touches.add(e.pointerId.toString(), e);
  17775. }
  17776. }
  17777. };
  17778. VirtualJoystick.prototype._onPointerMove = function (e) {
  17779. if (this._joystickPointerID == e.pointerId) {
  17780. this._joystickPointerPos.x = e.clientX;
  17781. this._joystickPointerPos.y = e.clientY;
  17782. this._deltaJoystickVector = this._joystickPointerPos.clone();
  17783. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  17784. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  17785. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  17786. switch (this._axisTargetedByLeftAndRight) {
  17787. case 0 /* X */:
  17788. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  17789. break;
  17790. case 1 /* Y */:
  17791. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  17792. break;
  17793. case 2 /* Z */:
  17794. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  17795. break;
  17796. }
  17797. var directionUpDown = this.reverseUpDown ? 1 : -1;
  17798. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  17799. switch (this._axisTargetedByUpAndDown) {
  17800. case 0 /* X */:
  17801. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  17802. break;
  17803. case 1 /* Y */:
  17804. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  17805. break;
  17806. case 2 /* Z */:
  17807. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  17808. break;
  17809. }
  17810. } else {
  17811. if (this._touches.item(e.pointerId.toString())) {
  17812. this._touches.item(e.pointerId.toString()).x = e.clientX;
  17813. this._touches.item(e.pointerId.toString()).y = e.clientY;
  17814. }
  17815. }
  17816. };
  17817. VirtualJoystick.prototype._onPointerUp = function (e) {
  17818. this._clearCanvas();
  17819. if (this._joystickPointerID == e.pointerId) {
  17820. this._joystickPointerID = -1;
  17821. this.pressed = false;
  17822. }
  17823. this._deltaJoystickVector.x = 0;
  17824. this._deltaJoystickVector.y = 0;
  17825. this._touches.remove(e.pointerId.toString());
  17826. };
  17827. /**
  17828. * Change the color of the virtual joystick
  17829. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  17830. */
  17831. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  17832. this._joystickColor = newColor;
  17833. };
  17834. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  17835. this._action = action;
  17836. };
  17837. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  17838. switch (axis) {
  17839. case 0 /* X */:
  17840. case 1 /* Y */:
  17841. case 2 /* Z */:
  17842. this._axisTargetedByLeftAndRight = axis;
  17843. break;
  17844. default:
  17845. this._axisTargetedByLeftAndRight = 0 /* X */;
  17846. break;
  17847. }
  17848. };
  17849. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  17850. switch (axis) {
  17851. case 0 /* X */:
  17852. case 1 /* Y */:
  17853. case 2 /* Z */:
  17854. this._axisTargetedByUpAndDown = axis;
  17855. break;
  17856. default:
  17857. this._axisTargetedByUpAndDown = 1 /* Y */;
  17858. break;
  17859. }
  17860. };
  17861. VirtualJoystick.prototype._clearCanvas = function () {
  17862. if (this._leftJoystick) {
  17863. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  17864. } else {
  17865. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  17866. }
  17867. };
  17868. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  17869. var _this = this;
  17870. if (this.pressed) {
  17871. this._clearCanvas();
  17872. this._touches.forEach(function (touch) {
  17873. if (touch.pointerId === _this._joystickPointerID) {
  17874. VirtualJoystick.vjCanvasContext.beginPath();
  17875. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  17876. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  17877. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  17878. VirtualJoystick.vjCanvasContext.stroke();
  17879. VirtualJoystick.vjCanvasContext.beginPath();
  17880. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  17881. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  17882. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  17883. VirtualJoystick.vjCanvasContext.stroke();
  17884. VirtualJoystick.vjCanvasContext.beginPath();
  17885. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  17886. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  17887. VirtualJoystick.vjCanvasContext.stroke();
  17888. } else {
  17889. VirtualJoystick.vjCanvasContext.beginPath();
  17890. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  17891. VirtualJoystick.vjCanvasContext.beginPath();
  17892. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  17893. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  17894. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  17895. VirtualJoystick.vjCanvasContext.stroke();
  17896. }
  17897. ;
  17898. });
  17899. }
  17900. requestAnimationFrame(function () {
  17901. _this._drawVirtualJoystick();
  17902. });
  17903. };
  17904. VirtualJoystick.prototype.releaseCanvas = function () {
  17905. if (VirtualJoystick.vjCanvas) {
  17906. document.body.removeChild(VirtualJoystick.vjCanvas);
  17907. VirtualJoystick.vjCanvas = null;
  17908. }
  17909. };
  17910. VirtualJoystick._globalJoystickIndex = 0;
  17911. return VirtualJoystick;
  17912. })();
  17913. BABYLON.VirtualJoystick = VirtualJoystick;
  17914. })(BABYLON || (BABYLON = {}));
  17915. var BABYLON;
  17916. (function (BABYLON) {
  17917. (function (VirtualJoystick) {
  17918. var Collection = (function () {
  17919. function Collection() {
  17920. this._count = 0;
  17921. this._collection = new Array();
  17922. }
  17923. Collection.prototype.Count = function () {
  17924. return this._count;
  17925. };
  17926. Collection.prototype.add = function (key, item) {
  17927. if (this._collection[key] != undefined) {
  17928. return undefined;
  17929. }
  17930. this._collection[key] = item;
  17931. return ++this._count;
  17932. };
  17933. Collection.prototype.remove = function (key) {
  17934. if (this._collection[key] == undefined) {
  17935. return undefined;
  17936. }
  17937. delete this._collection[key];
  17938. return --this._count;
  17939. };
  17940. Collection.prototype.item = function (key) {
  17941. return this._collection[key];
  17942. };
  17943. Collection.prototype.forEach = function (block) {
  17944. var key;
  17945. for (key in this._collection) {
  17946. if (this._collection.hasOwnProperty(key)) {
  17947. block(this._collection[key]);
  17948. }
  17949. }
  17950. };
  17951. return Collection;
  17952. })();
  17953. VirtualJoystick.Collection = Collection;
  17954. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  17955. var VirtualJoystick = BABYLON.VirtualJoystick;
  17956. })(BABYLON || (BABYLON = {}));
  17957. var __extends = this.__extends || function (d, b) {
  17958. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17959. function __() { this.constructor = d; }
  17960. __.prototype = b.prototype;
  17961. d.prototype = new __();
  17962. };
  17963. var BABYLON;
  17964. (function (BABYLON) {
  17965. var OculusRiftDevKit2013_Metric = {
  17966. HResolution: 1280,
  17967. VResolution: 800,
  17968. HScreenSize: 0.149759993,
  17969. VScreenSize: 0.0935999975,
  17970. VScreenCenter: 0.0467999987,
  17971. EyeToScreenDistance: 0.0410000011,
  17972. LensSeparationDistance: 0.0635000020,
  17973. InterpupillaryDistance: 0.0640000030,
  17974. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  17975. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  17976. PostProcessScaleFactor: 1.714605507808412,
  17977. LensCenterOffset: 0.151976421
  17978. };
  17979. var _OculusInnerCamera = (function (_super) {
  17980. __extends(_OculusInnerCamera, _super);
  17981. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  17982. _super.call(this, name, position, scene);
  17983. this._workMatrix = new BABYLON.Matrix();
  17984. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  17985. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  17986. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  17987. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  17988. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  17989. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  17990. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  17991. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  17992. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  17993. }
  17994. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  17995. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  17996. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  17997. return this._projectionMatrix;
  17998. };
  17999. _OculusInnerCamera.prototype._getViewMatrix = function () {
  18000. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  18001. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  18002. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  18003. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  18004. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  18005. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  18006. return this._viewMatrix;
  18007. };
  18008. return _OculusInnerCamera;
  18009. })(BABYLON.FreeCamera);
  18010. var OculusCamera = (function (_super) {
  18011. __extends(OculusCamera, _super);
  18012. function OculusCamera(name, position, scene) {
  18013. _super.call(this, name, position, scene);
  18014. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  18015. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  18016. this.subCameras.push(this._leftCamera);
  18017. this.subCameras.push(this._rightCamera);
  18018. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  18019. }
  18020. OculusCamera.prototype._update = function () {
  18021. this._leftCamera.position.copyFrom(this.position);
  18022. this._rightCamera.position.copyFrom(this.position);
  18023. this._updateCamera(this._leftCamera);
  18024. this._updateCamera(this._rightCamera);
  18025. _super.prototype._update.call(this);
  18026. };
  18027. OculusCamera.prototype._updateCamera = function (camera) {
  18028. camera.minZ = this.minZ;
  18029. camera.maxZ = this.maxZ;
  18030. camera.rotation.x = this.rotation.x;
  18031. camera.rotation.y = this.rotation.y;
  18032. camera.rotation.z = this.rotation.z;
  18033. };
  18034. OculusCamera.prototype._onOrientationEvent = function (evt) {
  18035. var yaw = evt.alpha / 180 * Math.PI;
  18036. var pitch = evt.beta / 180 * Math.PI;
  18037. var roll = evt.gamma / 180 * Math.PI;
  18038. if (!this._offsetOrientation) {
  18039. this._offsetOrientation = {
  18040. yaw: yaw,
  18041. pitch: pitch,
  18042. roll: roll
  18043. };
  18044. return;
  18045. } else {
  18046. this.rotation.y += yaw - this._offsetOrientation.yaw;
  18047. this.rotation.x += pitch - this._offsetOrientation.pitch;
  18048. this.rotation.z += this._offsetOrientation.roll - roll;
  18049. this._offsetOrientation.yaw = yaw;
  18050. this._offsetOrientation.pitch = pitch;
  18051. this._offsetOrientation.roll = roll;
  18052. }
  18053. };
  18054. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  18055. _super.prototype.attachControl.call(this, element, noPreventDefault);
  18056. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  18057. };
  18058. OculusCamera.prototype.detachControl = function (element) {
  18059. _super.prototype.detachControl.call(this, element);
  18060. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  18061. };
  18062. return OculusCamera;
  18063. })(BABYLON.FreeCamera);
  18064. BABYLON.OculusCamera = OculusCamera;
  18065. })(BABYLON || (BABYLON = {}));
  18066. var __extends = this.__extends || function (d, b) {
  18067. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18068. function __() { this.constructor = d; }
  18069. __.prototype = b.prototype;
  18070. d.prototype = new __();
  18071. };
  18072. var BABYLON;
  18073. (function (BABYLON) {
  18074. var OculusRiftDevKit2013_Metric = {
  18075. HResolution: 1280,
  18076. VResolution: 800,
  18077. HScreenSize: 0.149759993,
  18078. VScreenSize: 0.0935999975,
  18079. VScreenCenter: 0.0467999987,
  18080. EyeToScreenDistance: 0.0410000011,
  18081. LensSeparationDistance: 0.0635000020,
  18082. InterpupillaryDistance: 0.0640000030,
  18083. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  18084. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  18085. PostProcessScaleFactor: 1.714605507808412,
  18086. LensCenterOffset: 0.151976421
  18087. };
  18088. var _OculusInnerGamepadCamera = (function (_super) {
  18089. __extends(_OculusInnerGamepadCamera, _super);
  18090. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  18091. _super.call(this, name, position, scene);
  18092. this._workMatrix = new BABYLON.Matrix();
  18093. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  18094. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  18095. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  18096. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  18097. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  18098. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  18099. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  18100. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  18101. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  18102. }
  18103. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  18104. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  18105. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  18106. return this._projectionMatrix;
  18107. };
  18108. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  18109. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  18110. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  18111. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  18112. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  18113. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  18114. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  18115. return this._viewMatrix;
  18116. };
  18117. return _OculusInnerGamepadCamera;
  18118. })(BABYLON.FreeCamera);
  18119. var OculusGamepadCamera = (function (_super) {
  18120. __extends(OculusGamepadCamera, _super);
  18121. function OculusGamepadCamera(name, position, scene) {
  18122. var _this = this;
  18123. _super.call(this, name, position, scene);
  18124. this.angularSensibility = 200;
  18125. this.moveSensibility = 75;
  18126. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  18127. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  18128. this.subCameras.push(this._leftCamera);
  18129. this.subCameras.push(this._rightCamera);
  18130. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  18131. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  18132. _this._onNewGameConnected(gamepad);
  18133. });
  18134. }
  18135. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  18136. if (gamepad.index === 0) {
  18137. this._gamepad = gamepad;
  18138. }
  18139. };
  18140. OculusGamepadCamera.prototype._update = function () {
  18141. this._leftCamera.position.copyFrom(this.position);
  18142. this._rightCamera.position.copyFrom(this.position);
  18143. this._updateCamera(this._leftCamera);
  18144. this._updateCamera(this._rightCamera);
  18145. _super.prototype._update.call(this);
  18146. };
  18147. OculusGamepadCamera.prototype._checkInputs = function () {
  18148. if (!this._gamepad) {
  18149. return;
  18150. }
  18151. var LSValues = this._gamepad.leftStick;
  18152. var normalizedLX = LSValues.x / this.moveSensibility;
  18153. var normalizedLY = LSValues.y / this.moveSensibility;
  18154. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  18155. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  18156. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  18157. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  18158. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  18159. };
  18160. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  18161. camera.minZ = this.minZ;
  18162. camera.maxZ = this.maxZ;
  18163. camera.rotation.x = this.rotation.x;
  18164. camera.rotation.y = this.rotation.y;
  18165. camera.rotation.z = this.rotation.z;
  18166. };
  18167. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  18168. var yaw = evt.alpha / 180 * Math.PI;
  18169. var pitch = evt.beta / 180 * Math.PI;
  18170. var roll = evt.gamma / 180 * Math.PI;
  18171. if (!this._offsetOrientation) {
  18172. this._offsetOrientation = {
  18173. yaw: yaw,
  18174. pitch: pitch,
  18175. roll: roll
  18176. };
  18177. return;
  18178. } else {
  18179. this.rotation.y += yaw - this._offsetOrientation.yaw;
  18180. this.rotation.x += pitch - this._offsetOrientation.pitch;
  18181. this.rotation.z += this._offsetOrientation.roll - roll;
  18182. this._offsetOrientation.yaw = yaw;
  18183. this._offsetOrientation.pitch = pitch;
  18184. this._offsetOrientation.roll = roll;
  18185. }
  18186. };
  18187. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  18188. _super.prototype.attachControl.call(this, element, noPreventDefault);
  18189. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  18190. };
  18191. OculusGamepadCamera.prototype.detachControl = function (element) {
  18192. _super.prototype.detachControl.call(this, element);
  18193. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  18194. };
  18195. OculusGamepadCamera.prototype.dispose = function () {
  18196. this._gamepads.dispose();
  18197. _super.prototype.dispose.call(this);
  18198. };
  18199. return OculusGamepadCamera;
  18200. })(BABYLON.FreeCamera);
  18201. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  18202. })(BABYLON || (BABYLON = {}));
  18203. var __extends = this.__extends || function (d, b) {
  18204. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18205. function __() { this.constructor = d; }
  18206. __.prototype = b.prototype;
  18207. d.prototype = new __();
  18208. };
  18209. var BABYLON;
  18210. (function (BABYLON) {
  18211. var VirtualJoysticksCamera = (function (_super) {
  18212. __extends(VirtualJoysticksCamera, _super);
  18213. function VirtualJoysticksCamera(name, position, scene) {
  18214. _super.call(this, name, position, scene);
  18215. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  18216. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  18217. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  18218. this._leftjoystick.setJoystickSensibility(0.15);
  18219. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  18220. this._rightjoystick.setAxisForUpDown(0 /* X */);
  18221. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  18222. this._rightjoystick.reverseUpDown = true;
  18223. this._rightjoystick.setJoystickSensibility(0.05);
  18224. this._rightjoystick.setJoystickColor("yellow");
  18225. }
  18226. VirtualJoysticksCamera.prototype._checkInputs = function () {
  18227. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  18228. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  18229. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  18230. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  18231. if (!this._leftjoystick.pressed) {
  18232. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  18233. }
  18234. if (!this._rightjoystick.pressed) {
  18235. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  18236. }
  18237. };
  18238. VirtualJoysticksCamera.prototype.dispose = function () {
  18239. this._leftjoystick.releaseCanvas();
  18240. _super.prototype.dispose.call(this);
  18241. };
  18242. return VirtualJoysticksCamera;
  18243. })(BABYLON.FreeCamera);
  18244. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  18245. })(BABYLON || (BABYLON = {}));
  18246. var __extends = this.__extends || function (d, b) {
  18247. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18248. function __() { this.constructor = d; }
  18249. __.prototype = b.prototype;
  18250. d.prototype = new __();
  18251. };
  18252. var BABYLON;
  18253. (function (BABYLON) {
  18254. var ShaderMaterial = (function (_super) {
  18255. __extends(ShaderMaterial, _super);
  18256. function ShaderMaterial(name, scene, shaderPath, options) {
  18257. _super.call(this, name, scene);
  18258. this._textures = new Array();
  18259. this._floats = new Array();
  18260. this._floatsArrays = {};
  18261. this._colors3 = new Array();
  18262. this._colors4 = new Array();
  18263. this._vectors2 = new Array();
  18264. this._vectors3 = new Array();
  18265. this._matrices = new Array();
  18266. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  18267. this._shaderPath = shaderPath;
  18268. options.needAlphaBlending = options.needAlphaBlending || false;
  18269. options.needAlphaTesting = options.needAlphaTesting || false;
  18270. options.attributes = options.attributes || ["position", "normal", "uv"];
  18271. options.uniforms = options.uniforms || ["worldViewProjection"];
  18272. options.samplers = options.samplers || [];
  18273. this._options = options;
  18274. }
  18275. ShaderMaterial.prototype.needAlphaBlending = function () {
  18276. return this._options.needAlphaBlending;
  18277. };
  18278. ShaderMaterial.prototype.needAlphaTesting = function () {
  18279. return this._options.needAlphaTesting;
  18280. };
  18281. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  18282. if (this._options.uniforms.indexOf(uniformName) === -1) {
  18283. this._options.uniforms.push(uniformName);
  18284. }
  18285. };
  18286. ShaderMaterial.prototype.setTexture = function (name, texture) {
  18287. if (this._options.samplers.indexOf(name) === -1) {
  18288. this._options.samplers.push(name);
  18289. }
  18290. this._textures[name] = texture;
  18291. return this;
  18292. };
  18293. ShaderMaterial.prototype.setFloat = function (name, value) {
  18294. this._checkUniform(name);
  18295. this._floats[name] = value;
  18296. return this;
  18297. };
  18298. ShaderMaterial.prototype.setFloats = function (name, value) {
  18299. this._checkUniform(name);
  18300. this._floatsArrays[name] = value;
  18301. return this;
  18302. };
  18303. ShaderMaterial.prototype.setColor3 = function (name, value) {
  18304. this._checkUniform(name);
  18305. this._colors3[name] = value;
  18306. return this;
  18307. };
  18308. ShaderMaterial.prototype.setColor4 = function (name, value) {
  18309. this._checkUniform(name);
  18310. this._colors4[name] = value;
  18311. return this;
  18312. };
  18313. ShaderMaterial.prototype.setVector2 = function (name, value) {
  18314. this._checkUniform(name);
  18315. this._vectors2[name] = value;
  18316. return this;
  18317. };
  18318. ShaderMaterial.prototype.setVector3 = function (name, value) {
  18319. this._checkUniform(name);
  18320. this._vectors3[name] = value;
  18321. return this;
  18322. };
  18323. ShaderMaterial.prototype.setMatrix = function (name, value) {
  18324. this._checkUniform(name);
  18325. this._matrices[name] = value;
  18326. return this;
  18327. };
  18328. ShaderMaterial.prototype.isReady = function () {
  18329. var scene = this.getScene();
  18330. var engine = scene.getEngine();
  18331. if (!this.checkReadyOnEveryCall) {
  18332. if (this._renderId === scene.getRenderId()) {
  18333. return true;
  18334. }
  18335. }
  18336. var previousEffect = this._effect;
  18337. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  18338. if (!this._effect.isReady()) {
  18339. return false;
  18340. }
  18341. if (previousEffect !== this._effect) {
  18342. scene.resetCachedMaterial();
  18343. }
  18344. this._renderId = scene.getRenderId();
  18345. return true;
  18346. };
  18347. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  18348. var scene = this.getScene();
  18349. if (this._options.uniforms.indexOf("world") !== -1) {
  18350. this._effect.setMatrix("world", world);
  18351. }
  18352. if (this._options.uniforms.indexOf("worldView") !== -1) {
  18353. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  18354. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  18355. }
  18356. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  18357. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  18358. }
  18359. };
  18360. ShaderMaterial.prototype.bind = function (world) {
  18361. this.bindOnlyWorldMatrix(world);
  18362. if (this.getScene().getCachedMaterial() !== this) {
  18363. if (this._options.uniforms.indexOf("view") !== -1) {
  18364. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  18365. }
  18366. if (this._options.uniforms.indexOf("projection") !== -1) {
  18367. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  18368. }
  18369. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  18370. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  18371. }
  18372. for (var name in this._textures) {
  18373. this._effect.setTexture(name, this._textures[name]);
  18374. }
  18375. for (name in this._floats) {
  18376. this._effect.setFloat(name, this._floats[name]);
  18377. }
  18378. for (name in this._floatsArrays) {
  18379. this._effect.setArray(name, this._floatsArrays[name]);
  18380. }
  18381. for (name in this._colors3) {
  18382. this._effect.setColor3(name, this._colors3[name]);
  18383. }
  18384. for (name in this._colors4) {
  18385. var color = this._colors4[name];
  18386. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  18387. }
  18388. for (name in this._vectors2) {
  18389. this._effect.setVector2(name, this._vectors2[name]);
  18390. }
  18391. for (name in this._vectors3) {
  18392. this._effect.setVector3(name, this._vectors3[name]);
  18393. }
  18394. for (name in this._matrices) {
  18395. this._effect.setMatrix(name, this._matrices[name]);
  18396. }
  18397. }
  18398. _super.prototype.bind.call(this, world, null);
  18399. };
  18400. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  18401. for (var name in this._textures) {
  18402. this._textures[name].dispose();
  18403. }
  18404. this._textures = [];
  18405. _super.prototype.dispose.call(this, forceDisposeEffect);
  18406. };
  18407. return ShaderMaterial;
  18408. })(BABYLON.Material);
  18409. BABYLON.ShaderMaterial = ShaderMaterial;
  18410. })(BABYLON || (BABYLON = {}));
  18411. var BABYLON;
  18412. (function (BABYLON) {
  18413. var VertexData = (function () {
  18414. function VertexData() {
  18415. }
  18416. VertexData.prototype.set = function (data, kind) {
  18417. switch (kind) {
  18418. case BABYLON.VertexBuffer.PositionKind:
  18419. this.positions = data;
  18420. break;
  18421. case BABYLON.VertexBuffer.NormalKind:
  18422. this.normals = data;
  18423. break;
  18424. case BABYLON.VertexBuffer.UVKind:
  18425. this.uvs = data;
  18426. break;
  18427. case BABYLON.VertexBuffer.UV2Kind:
  18428. this.uv2s = data;
  18429. break;
  18430. case BABYLON.VertexBuffer.ColorKind:
  18431. this.colors = data;
  18432. break;
  18433. case BABYLON.VertexBuffer.MatricesIndicesKind:
  18434. this.matricesIndices = data;
  18435. break;
  18436. case BABYLON.VertexBuffer.MatricesWeightsKind:
  18437. this.matricesWeights = data;
  18438. break;
  18439. }
  18440. };
  18441. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  18442. this._applyTo(mesh, updatable);
  18443. };
  18444. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  18445. this._applyTo(geometry, updatable);
  18446. };
  18447. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  18448. this._update(mesh);
  18449. };
  18450. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  18451. this._update(geometry);
  18452. };
  18453. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  18454. if (this.positions) {
  18455. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  18456. }
  18457. if (this.normals) {
  18458. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  18459. }
  18460. if (this.uvs) {
  18461. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  18462. }
  18463. if (this.uv2s) {
  18464. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  18465. }
  18466. if (this.colors) {
  18467. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  18468. }
  18469. if (this.matricesIndices) {
  18470. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  18471. }
  18472. if (this.matricesWeights) {
  18473. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  18474. }
  18475. if (this.indices) {
  18476. meshOrGeometry.setIndices(this.indices);
  18477. }
  18478. };
  18479. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  18480. if (this.positions) {
  18481. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  18482. }
  18483. if (this.normals) {
  18484. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  18485. }
  18486. if (this.uvs) {
  18487. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  18488. }
  18489. if (this.uv2s) {
  18490. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  18491. }
  18492. if (this.colors) {
  18493. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  18494. }
  18495. if (this.matricesIndices) {
  18496. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  18497. }
  18498. if (this.matricesWeights) {
  18499. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  18500. }
  18501. if (this.indices) {
  18502. meshOrGeometry.setIndices(this.indices);
  18503. }
  18504. };
  18505. VertexData.prototype.transform = function (matrix) {
  18506. var transformed = BABYLON.Vector3.Zero();
  18507. if (this.positions) {
  18508. var position = BABYLON.Vector3.Zero();
  18509. for (var index = 0; index < this.positions.length; index += 3) {
  18510. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  18511. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  18512. this.positions[index] = transformed.x;
  18513. this.positions[index + 1] = transformed.y;
  18514. this.positions[index + 2] = transformed.z;
  18515. }
  18516. }
  18517. if (this.normals) {
  18518. var normal = BABYLON.Vector3.Zero();
  18519. for (index = 0; index < this.normals.length; index += 3) {
  18520. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  18521. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  18522. this.normals[index] = transformed.x;
  18523. this.normals[index + 1] = transformed.y;
  18524. this.normals[index + 2] = transformed.z;
  18525. }
  18526. }
  18527. };
  18528. VertexData.prototype.merge = function (other) {
  18529. if (other.indices) {
  18530. if (!this.indices) {
  18531. this.indices = [];
  18532. }
  18533. var offset = this.positions ? this.positions.length / 3 : 0;
  18534. for (var index = 0; index < other.indices.length; index++) {
  18535. this.indices.push(other.indices[index] + offset);
  18536. }
  18537. }
  18538. if (other.positions) {
  18539. if (!this.positions) {
  18540. this.positions = [];
  18541. }
  18542. for (index = 0; index < other.positions.length; index++) {
  18543. this.positions.push(other.positions[index]);
  18544. }
  18545. }
  18546. if (other.normals) {
  18547. if (!this.normals) {
  18548. this.normals = [];
  18549. }
  18550. for (index = 0; index < other.normals.length; index++) {
  18551. this.normals.push(other.normals[index]);
  18552. }
  18553. }
  18554. if (other.uvs) {
  18555. if (!this.uvs) {
  18556. this.uvs = [];
  18557. }
  18558. for (index = 0; index < other.uvs.length; index++) {
  18559. this.uvs.push(other.uvs[index]);
  18560. }
  18561. }
  18562. if (other.uv2s) {
  18563. if (!this.uv2s) {
  18564. this.uv2s = [];
  18565. }
  18566. for (index = 0; index < other.uv2s.length; index++) {
  18567. this.uv2s.push(other.uv2s[index]);
  18568. }
  18569. }
  18570. if (other.matricesIndices) {
  18571. if (!this.matricesIndices) {
  18572. this.matricesIndices = [];
  18573. }
  18574. for (index = 0; index < other.matricesIndices.length; index++) {
  18575. this.matricesIndices.push(other.matricesIndices[index]);
  18576. }
  18577. }
  18578. if (other.matricesWeights) {
  18579. if (!this.matricesWeights) {
  18580. this.matricesWeights = [];
  18581. }
  18582. for (index = 0; index < other.matricesWeights.length; index++) {
  18583. this.matricesWeights.push(other.matricesWeights[index]);
  18584. }
  18585. }
  18586. if (other.colors) {
  18587. if (!this.colors) {
  18588. this.colors = [];
  18589. }
  18590. for (index = 0; index < other.colors.length; index++) {
  18591. this.colors.push(other.colors[index]);
  18592. }
  18593. }
  18594. };
  18595. VertexData.ExtractFromMesh = function (mesh) {
  18596. return VertexData._ExtractFrom(mesh);
  18597. };
  18598. VertexData.ExtractFromGeometry = function (geometry) {
  18599. return VertexData._ExtractFrom(geometry);
  18600. };
  18601. VertexData._ExtractFrom = function (meshOrGeometry) {
  18602. var result = new BABYLON.VertexData();
  18603. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18604. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18605. }
  18606. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18607. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18608. }
  18609. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18610. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18611. }
  18612. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18613. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  18614. }
  18615. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18616. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  18617. }
  18618. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18619. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18620. }
  18621. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18622. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18623. }
  18624. result.indices = meshOrGeometry.getIndices();
  18625. return result;
  18626. };
  18627. VertexData.CreateBox = function (size) {
  18628. var normalsSource = [
  18629. new BABYLON.Vector3(0, 0, 1),
  18630. new BABYLON.Vector3(0, 0, -1),
  18631. new BABYLON.Vector3(1, 0, 0),
  18632. new BABYLON.Vector3(-1, 0, 0),
  18633. new BABYLON.Vector3(0, 1, 0),
  18634. new BABYLON.Vector3(0, -1, 0)
  18635. ];
  18636. var indices = [];
  18637. var positions = [];
  18638. var normals = [];
  18639. var uvs = [];
  18640. size = size || 1;
  18641. for (var index = 0; index < normalsSource.length; index++) {
  18642. var normal = normalsSource[index];
  18643. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  18644. var side2 = BABYLON.Vector3.Cross(normal, side1);
  18645. var verticesLength = positions.length / 3;
  18646. indices.push(verticesLength);
  18647. indices.push(verticesLength + 1);
  18648. indices.push(verticesLength + 2);
  18649. indices.push(verticesLength);
  18650. indices.push(verticesLength + 2);
  18651. indices.push(verticesLength + 3);
  18652. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  18653. positions.push(vertex.x, vertex.y, vertex.z);
  18654. normals.push(normal.x, normal.y, normal.z);
  18655. uvs.push(1.0, 1.0);
  18656. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  18657. positions.push(vertex.x, vertex.y, vertex.z);
  18658. normals.push(normal.x, normal.y, normal.z);
  18659. uvs.push(0.0, 1.0);
  18660. vertex = normal.add(side1).add(side2).scale(size / 2);
  18661. positions.push(vertex.x, vertex.y, vertex.z);
  18662. normals.push(normal.x, normal.y, normal.z);
  18663. uvs.push(0.0, 0.0);
  18664. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  18665. positions.push(vertex.x, vertex.y, vertex.z);
  18666. normals.push(normal.x, normal.y, normal.z);
  18667. uvs.push(1.0, 0.0);
  18668. }
  18669. var vertexData = new BABYLON.VertexData();
  18670. vertexData.indices = indices;
  18671. vertexData.positions = positions;
  18672. vertexData.normals = normals;
  18673. vertexData.uvs = uvs;
  18674. return vertexData;
  18675. };
  18676. VertexData.CreateSphere = function (segments, diameter) {
  18677. segments = segments || 32;
  18678. diameter = diameter || 1;
  18679. var radius = diameter / 2;
  18680. var totalZRotationSteps = 2 + segments;
  18681. var totalYRotationSteps = 2 * totalZRotationSteps;
  18682. var indices = [];
  18683. var positions = [];
  18684. var normals = [];
  18685. var uvs = [];
  18686. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  18687. var normalizedZ = zRotationStep / totalZRotationSteps;
  18688. var angleZ = (normalizedZ * Math.PI);
  18689. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  18690. var normalizedY = yRotationStep / totalYRotationSteps;
  18691. var angleY = normalizedY * Math.PI * 2;
  18692. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  18693. var rotationY = BABYLON.Matrix.RotationY(angleY);
  18694. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  18695. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  18696. var vertex = complete.scale(radius);
  18697. var normal = BABYLON.Vector3.Normalize(vertex);
  18698. positions.push(vertex.x, vertex.y, vertex.z);
  18699. normals.push(normal.x, normal.y, normal.z);
  18700. uvs.push(normalizedZ, normalizedY);
  18701. }
  18702. if (zRotationStep > 0) {
  18703. var verticesCount = positions.length / 3;
  18704. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  18705. indices.push((firstIndex));
  18706. indices.push((firstIndex + 1));
  18707. indices.push(firstIndex + totalYRotationSteps + 1);
  18708. indices.push((firstIndex + totalYRotationSteps + 1));
  18709. indices.push((firstIndex + 1));
  18710. indices.push((firstIndex + totalYRotationSteps + 2));
  18711. }
  18712. }
  18713. }
  18714. var vertexData = new BABYLON.VertexData();
  18715. vertexData.indices = indices;
  18716. vertexData.positions = positions;
  18717. vertexData.normals = normals;
  18718. vertexData.uvs = uvs;
  18719. return vertexData;
  18720. };
  18721. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  18722. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  18723. var radiusTop = diameterTop / 2;
  18724. var radiusBottom = diameterBottom / 2;
  18725. var indices = [];
  18726. var positions = [];
  18727. var normals = [];
  18728. var uvs = [];
  18729. height = height || 1;
  18730. diameterTop = diameterTop || 0.5;
  18731. diameterBottom = diameterBottom || 1;
  18732. tessellation = tessellation || 16;
  18733. subdivisions = subdivisions || 1;
  18734. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  18735. var getCircleVector = function (i) {
  18736. var angle = (i * 2.0 * Math.PI / tessellation);
  18737. var dx = Math.cos(angle);
  18738. var dz = Math.sin(angle);
  18739. return new BABYLON.Vector3(dx, 0, dz);
  18740. };
  18741. var createCylinderCap = function (isTop) {
  18742. var radius = isTop ? radiusTop : radiusBottom;
  18743. if (radius == 0) {
  18744. return;
  18745. }
  18746. var vbase = positions.length / 3;
  18747. var offset = new BABYLON.Vector3(0, height / 2, 0);
  18748. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  18749. if (!isTop) {
  18750. offset.scaleInPlace(-1);
  18751. textureScale.x = -textureScale.x;
  18752. }
  18753. for (i = 0; i < tessellation; i++) {
  18754. var circleVector = getCircleVector(i);
  18755. var position = circleVector.scale(radius).add(offset);
  18756. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  18757. positions.push(position.x, position.y, position.z);
  18758. uvs.push(textureCoordinate.x, textureCoordinate.y);
  18759. }
  18760. for (var i = 0; i < tessellation - 2; i++) {
  18761. if (!isTop) {
  18762. indices.push(vbase);
  18763. indices.push(vbase + (i + 2) % tessellation);
  18764. indices.push(vbase + (i + 1) % tessellation);
  18765. } else {
  18766. indices.push(vbase);
  18767. indices.push(vbase + (i + 1) % tessellation);
  18768. indices.push(vbase + (i + 2) % tessellation);
  18769. }
  18770. }
  18771. };
  18772. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  18773. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  18774. var stride = tessellation + 1;
  18775. for (var i = 0; i <= tessellation; i++) {
  18776. var circleVector = getCircleVector(i);
  18777. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  18778. var position, radius = radiusBottom;
  18779. for (var s = 0; s <= subdivisions; s++) {
  18780. position = circleVector.scale(radius);
  18781. position.addInPlace(base.add(offset.scale(s)));
  18782. textureCoordinate.y += 1 / subdivisions;
  18783. radius += (radiusTop - radiusBottom) / subdivisions;
  18784. positions.push(position.x, position.y, position.z);
  18785. uvs.push(textureCoordinate.x, textureCoordinate.y);
  18786. }
  18787. }
  18788. subdivisions += 1;
  18789. for (var s = 0; s < subdivisions - 1; s++) {
  18790. for (var i = 0; i <= tessellation; i++) {
  18791. indices.push(i * subdivisions + s);
  18792. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  18793. indices.push(i * subdivisions + (s + 1));
  18794. indices.push(i * subdivisions + (s + 1));
  18795. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  18796. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  18797. }
  18798. }
  18799. createCylinderCap(true);
  18800. createCylinderCap(false);
  18801. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18802. var vertexData = new BABYLON.VertexData();
  18803. vertexData.indices = indices;
  18804. vertexData.positions = positions;
  18805. vertexData.normals = normals;
  18806. vertexData.uvs = uvs;
  18807. return vertexData;
  18808. };
  18809. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  18810. var indices = [];
  18811. var positions = [];
  18812. var normals = [];
  18813. var uvs = [];
  18814. diameter = diameter || 1;
  18815. thickness = thickness || 0.5;
  18816. tessellation = tessellation || 16;
  18817. var stride = tessellation + 1;
  18818. for (var i = 0; i <= tessellation; i++) {
  18819. var u = i / tessellation;
  18820. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  18821. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  18822. for (var j = 0; j <= tessellation; j++) {
  18823. var v = 1 - j / tessellation;
  18824. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  18825. var dx = Math.cos(innerAngle);
  18826. var dy = Math.sin(innerAngle);
  18827. var normal = new BABYLON.Vector3(dx, dy, 0);
  18828. var position = normal.scale(thickness / 2);
  18829. var textureCoordinate = new BABYLON.Vector2(u, v);
  18830. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  18831. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  18832. positions.push(position.x, position.y, position.z);
  18833. normals.push(normal.x, normal.y, normal.z);
  18834. uvs.push(textureCoordinate.x, textureCoordinate.y);
  18835. var nextI = (i + 1) % stride;
  18836. var nextJ = (j + 1) % stride;
  18837. indices.push(i * stride + j);
  18838. indices.push(i * stride + nextJ);
  18839. indices.push(nextI * stride + j);
  18840. indices.push(i * stride + nextJ);
  18841. indices.push(nextI * stride + nextJ);
  18842. indices.push(nextI * stride + j);
  18843. }
  18844. }
  18845. var vertexData = new BABYLON.VertexData();
  18846. vertexData.indices = indices;
  18847. vertexData.positions = positions;
  18848. vertexData.normals = normals;
  18849. vertexData.uvs = uvs;
  18850. return vertexData;
  18851. };
  18852. VertexData.CreateLines = function (points) {
  18853. var indices = [];
  18854. var positions = [];
  18855. for (var index = 0; index < points.length; index++) {
  18856. positions.push(points[index].x, points[index].y, points[index].z);
  18857. if (index > 0) {
  18858. indices.push(index - 1);
  18859. indices.push(index);
  18860. }
  18861. }
  18862. var vertexData = new BABYLON.VertexData();
  18863. vertexData.indices = indices;
  18864. vertexData.positions = positions;
  18865. return vertexData;
  18866. };
  18867. VertexData.CreateGround = function (width, height, subdivisions) {
  18868. var indices = [];
  18869. var positions = [];
  18870. var normals = [];
  18871. var uvs = [];
  18872. var row, col;
  18873. width = width || 1;
  18874. height = height || 1;
  18875. subdivisions = subdivisions || 1;
  18876. for (row = 0; row <= subdivisions; row++) {
  18877. for (col = 0; col <= subdivisions; col++) {
  18878. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  18879. var normal = new BABYLON.Vector3(0, 1.0, 0);
  18880. positions.push(position.x, position.y, position.z);
  18881. normals.push(normal.x, normal.y, normal.z);
  18882. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  18883. }
  18884. }
  18885. for (row = 0; row < subdivisions; row++) {
  18886. for (col = 0; col < subdivisions; col++) {
  18887. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  18888. indices.push(col + 1 + row * (subdivisions + 1));
  18889. indices.push(col + row * (subdivisions + 1));
  18890. indices.push(col + (row + 1) * (subdivisions + 1));
  18891. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  18892. indices.push(col + row * (subdivisions + 1));
  18893. }
  18894. }
  18895. var vertexData = new BABYLON.VertexData();
  18896. vertexData.indices = indices;
  18897. vertexData.positions = positions;
  18898. vertexData.normals = normals;
  18899. vertexData.uvs = uvs;
  18900. return vertexData;
  18901. };
  18902. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  18903. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  18904. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  18905. var indices = [];
  18906. var positions = [];
  18907. var normals = [];
  18908. var uvs = [];
  18909. var row, col, tileRow, tileCol;
  18910. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  18911. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  18912. precision.w = (precision.w < 1) ? 1 : precision.w;
  18913. precision.h = (precision.h < 1) ? 1 : precision.h;
  18914. var tileSize = {
  18915. 'w': (xmax - xmin) / subdivisions.w,
  18916. 'h': (zmax - zmin) / subdivisions.h
  18917. };
  18918. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  18919. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  18920. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  18921. }
  18922. }
  18923. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  18924. var base = positions.length / 3;
  18925. var rowLength = precision.w + 1;
  18926. for (row = 0; row < precision.h; row++) {
  18927. for (col = 0; col < precision.w; col++) {
  18928. var square = [
  18929. base + col + row * rowLength,
  18930. base + (col + 1) + row * rowLength,
  18931. base + (col + 1) + (row + 1) * rowLength,
  18932. base + col + (row + 1) * rowLength
  18933. ];
  18934. indices.push(square[1]);
  18935. indices.push(square[2]);
  18936. indices.push(square[3]);
  18937. indices.push(square[0]);
  18938. indices.push(square[1]);
  18939. indices.push(square[3]);
  18940. }
  18941. }
  18942. var position = BABYLON.Vector3.Zero();
  18943. var normal = new BABYLON.Vector3(0, 1.0, 0);
  18944. for (row = 0; row <= precision.h; row++) {
  18945. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  18946. for (col = 0; col <= precision.w; col++) {
  18947. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  18948. position.y = 0;
  18949. positions.push(position.x, position.y, position.z);
  18950. normals.push(normal.x, normal.y, normal.z);
  18951. uvs.push(col / precision.w, row / precision.h);
  18952. }
  18953. }
  18954. }
  18955. var vertexData = new BABYLON.VertexData();
  18956. vertexData.indices = indices;
  18957. vertexData.positions = positions;
  18958. vertexData.normals = normals;
  18959. vertexData.uvs = uvs;
  18960. return vertexData;
  18961. };
  18962. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  18963. var indices = [];
  18964. var positions = [];
  18965. var normals = [];
  18966. var uvs = [];
  18967. var row, col;
  18968. for (row = 0; row <= subdivisions; row++) {
  18969. for (col = 0; col <= subdivisions; col++) {
  18970. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  18971. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  18972. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  18973. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  18974. var r = buffer[pos] / 255.0;
  18975. var g = buffer[pos + 1] / 255.0;
  18976. var b = buffer[pos + 2] / 255.0;
  18977. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  18978. position.y = minHeight + (maxHeight - minHeight) * gradient;
  18979. positions.push(position.x, position.y, position.z);
  18980. normals.push(0, 0, 0);
  18981. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  18982. }
  18983. }
  18984. for (row = 0; row < subdivisions; row++) {
  18985. for (col = 0; col < subdivisions; col++) {
  18986. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  18987. indices.push(col + 1 + row * (subdivisions + 1));
  18988. indices.push(col + row * (subdivisions + 1));
  18989. indices.push(col + (row + 1) * (subdivisions + 1));
  18990. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  18991. indices.push(col + row * (subdivisions + 1));
  18992. }
  18993. }
  18994. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18995. var vertexData = new BABYLON.VertexData();
  18996. vertexData.indices = indices;
  18997. vertexData.positions = positions;
  18998. vertexData.normals = normals;
  18999. vertexData.uvs = uvs;
  19000. return vertexData;
  19001. };
  19002. VertexData.CreatePlane = function (size) {
  19003. var indices = [];
  19004. var positions = [];
  19005. var normals = [];
  19006. var uvs = [];
  19007. size = size || 1;
  19008. var halfSize = size / 2.0;
  19009. positions.push(-halfSize, -halfSize, 0);
  19010. normals.push(0, 0, -1.0);
  19011. uvs.push(0.0, 0.0);
  19012. positions.push(halfSize, -halfSize, 0);
  19013. normals.push(0, 0, -1.0);
  19014. uvs.push(1.0, 0.0);
  19015. positions.push(halfSize, halfSize, 0);
  19016. normals.push(0, 0, -1.0);
  19017. uvs.push(1.0, 1.0);
  19018. positions.push(-halfSize, halfSize, 0);
  19019. normals.push(0, 0, -1.0);
  19020. uvs.push(0.0, 1.0);
  19021. indices.push(0);
  19022. indices.push(1);
  19023. indices.push(2);
  19024. indices.push(0);
  19025. indices.push(2);
  19026. indices.push(3);
  19027. var vertexData = new BABYLON.VertexData();
  19028. vertexData.indices = indices;
  19029. vertexData.positions = positions;
  19030. vertexData.normals = normals;
  19031. vertexData.uvs = uvs;
  19032. return vertexData;
  19033. };
  19034. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  19035. var indices = [];
  19036. var positions = [];
  19037. var normals = [];
  19038. var uvs = [];
  19039. radius = radius || 2;
  19040. tube = tube || 0.5;
  19041. radialSegments = radialSegments || 32;
  19042. tubularSegments = tubularSegments || 32;
  19043. p = p || 2;
  19044. q = q || 3;
  19045. var getPos = function (angle) {
  19046. var cu = Math.cos(angle);
  19047. var su = Math.sin(angle);
  19048. var quOverP = q / p * angle;
  19049. var cs = Math.cos(quOverP);
  19050. var tx = radius * (2 + cs) * 0.5 * cu;
  19051. var ty = radius * (2 + cs) * su * 0.5;
  19052. var tz = radius * Math.sin(quOverP) * 0.5;
  19053. return new BABYLON.Vector3(tx, ty, tz);
  19054. };
  19055. for (var i = 0; i <= radialSegments; i++) {
  19056. var modI = i % radialSegments;
  19057. var u = modI / radialSegments * 2 * p * Math.PI;
  19058. var p1 = getPos(u);
  19059. var p2 = getPos(u + 0.01);
  19060. var tang = p2.subtract(p1);
  19061. var n = p2.add(p1);
  19062. var bitan = BABYLON.Vector3.Cross(tang, n);
  19063. n = BABYLON.Vector3.Cross(bitan, tang);
  19064. bitan.normalize();
  19065. n.normalize();
  19066. for (var j = 0; j < tubularSegments; j++) {
  19067. var modJ = j % tubularSegments;
  19068. var v = modJ / tubularSegments * 2 * Math.PI;
  19069. var cx = -tube * Math.cos(v);
  19070. var cy = tube * Math.sin(v);
  19071. positions.push(p1.x + cx * n.x + cy * bitan.x);
  19072. positions.push(p1.y + cx * n.y + cy * bitan.y);
  19073. positions.push(p1.z + cx * n.z + cy * bitan.z);
  19074. uvs.push(i / radialSegments);
  19075. uvs.push(j / tubularSegments);
  19076. }
  19077. }
  19078. for (i = 0; i < radialSegments; i++) {
  19079. for (j = 0; j < tubularSegments; j++) {
  19080. var jNext = (j + 1) % tubularSegments;
  19081. var a = i * tubularSegments + j;
  19082. var b = (i + 1) * tubularSegments + j;
  19083. var c = (i + 1) * tubularSegments + jNext;
  19084. var d = i * tubularSegments + jNext;
  19085. indices.push(d);
  19086. indices.push(b);
  19087. indices.push(a);
  19088. indices.push(d);
  19089. indices.push(c);
  19090. indices.push(b);
  19091. }
  19092. }
  19093. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19094. var vertexData = new BABYLON.VertexData();
  19095. vertexData.indices = indices;
  19096. vertexData.positions = positions;
  19097. vertexData.normals = normals;
  19098. vertexData.uvs = uvs;
  19099. return vertexData;
  19100. };
  19101. VertexData.ComputeNormals = function (positions, indices, normals) {
  19102. var positionVectors = [];
  19103. var facesOfVertices = [];
  19104. var index;
  19105. for (index = 0; index < positions.length; index += 3) {
  19106. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  19107. positionVectors.push(vector3);
  19108. facesOfVertices.push([]);
  19109. }
  19110. var facesNormals = [];
  19111. for (index = 0; index < indices.length / 3; index++) {
  19112. var i1 = indices[index * 3];
  19113. var i2 = indices[index * 3 + 1];
  19114. var i3 = indices[index * 3 + 2];
  19115. var p1 = positionVectors[i1];
  19116. var p2 = positionVectors[i2];
  19117. var p3 = positionVectors[i3];
  19118. var p1p2 = p1.subtract(p2);
  19119. var p3p2 = p3.subtract(p2);
  19120. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  19121. facesOfVertices[i1].push(index);
  19122. facesOfVertices[i2].push(index);
  19123. facesOfVertices[i3].push(index);
  19124. }
  19125. for (index = 0; index < positionVectors.length; index++) {
  19126. var faces = facesOfVertices[index];
  19127. var normal = BABYLON.Vector3.Zero();
  19128. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  19129. normal.addInPlace(facesNormals[faces[faceIndex]]);
  19130. }
  19131. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  19132. normals[index * 3] = normal.x;
  19133. normals[index * 3 + 1] = normal.y;
  19134. normals[index * 3 + 2] = normal.z;
  19135. }
  19136. };
  19137. return VertexData;
  19138. })();
  19139. BABYLON.VertexData = VertexData;
  19140. })(BABYLON || (BABYLON = {}));
  19141. var __extends = this.__extends || function (d, b) {
  19142. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19143. function __() { this.constructor = d; }
  19144. __.prototype = b.prototype;
  19145. d.prototype = new __();
  19146. };
  19147. var BABYLON;
  19148. (function (BABYLON) {
  19149. var buildCamera = function (that, name) {
  19150. that._leftCamera.isIntermediate = true;
  19151. that.subCameras.push(that._leftCamera);
  19152. that.subCameras.push(that._rightCamera);
  19153. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  19154. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  19155. that._anaglyphPostProcess.onApply = function (effect) {
  19156. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  19157. };
  19158. that._update();
  19159. };
  19160. var AnaglyphArcRotateCamera = (function (_super) {
  19161. __extends(AnaglyphArcRotateCamera, _super);
  19162. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  19163. _super.call(this, name, alpha, beta, radius, target, scene);
  19164. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  19165. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  19166. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  19167. buildCamera(this, name);
  19168. }
  19169. AnaglyphArcRotateCamera.prototype._update = function () {
  19170. this._updateCamera(this._leftCamera);
  19171. this._updateCamera(this._rightCamera);
  19172. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  19173. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  19174. _super.prototype._update.call(this);
  19175. };
  19176. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  19177. camera.beta = this.beta;
  19178. camera.radius = this.radius;
  19179. camera.minZ = this.minZ;
  19180. camera.maxZ = this.maxZ;
  19181. camera.fov = this.fov;
  19182. camera.target = this.target;
  19183. };
  19184. return AnaglyphArcRotateCamera;
  19185. })(BABYLON.ArcRotateCamera);
  19186. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  19187. var AnaglyphFreeCamera = (function (_super) {
  19188. __extends(AnaglyphFreeCamera, _super);
  19189. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  19190. _super.call(this, name, position, scene);
  19191. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  19192. this._transformMatrix = new BABYLON.Matrix();
  19193. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  19194. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  19195. buildCamera(this, name);
  19196. }
  19197. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  19198. var target = this.getTarget();
  19199. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  19200. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  19201. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  19202. };
  19203. AnaglyphFreeCamera.prototype._update = function () {
  19204. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  19205. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  19206. this._updateCamera(this._leftCamera);
  19207. this._updateCamera(this._rightCamera);
  19208. _super.prototype._update.call(this);
  19209. };
  19210. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  19211. camera.minZ = this.minZ;
  19212. camera.maxZ = this.maxZ;
  19213. camera.fov = this.fov;
  19214. camera.viewport = this.viewport;
  19215. camera.setTarget(this.getTarget());
  19216. };
  19217. return AnaglyphFreeCamera;
  19218. })(BABYLON.FreeCamera);
  19219. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  19220. })(BABYLON || (BABYLON = {}));
  19221. var __extends = this.__extends || function (d, b) {
  19222. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19223. function __() { this.constructor = d; }
  19224. __.prototype = b.prototype;
  19225. d.prototype = new __();
  19226. };
  19227. var BABYLON;
  19228. (function (BABYLON) {
  19229. var AnaglyphPostProcess = (function (_super) {
  19230. __extends(AnaglyphPostProcess, _super);
  19231. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  19232. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  19233. }
  19234. return AnaglyphPostProcess;
  19235. })(BABYLON.PostProcess);
  19236. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  19237. })(BABYLON || (BABYLON = {}));
  19238. var BABYLON;
  19239. (function (BABYLON) {
  19240. var Tags = (function () {
  19241. function Tags() {
  19242. }
  19243. Tags.EnableFor = function (obj) {
  19244. obj._tags = obj._tags || {};
  19245. obj.hasTags = function () {
  19246. return Tags.HasTags(obj);
  19247. };
  19248. obj.addTags = function (tagsString) {
  19249. return Tags.AddTagsTo(obj, tagsString);
  19250. };
  19251. obj.removeTags = function (tagsString) {
  19252. return Tags.RemoveTagsFrom(obj, tagsString);
  19253. };
  19254. obj.matchesTagsQuery = function (tagsQuery) {
  19255. return Tags.MatchesQuery(obj, tagsQuery);
  19256. };
  19257. };
  19258. Tags.DisableFor = function (obj) {
  19259. delete obj._tags;
  19260. delete obj.hasTags;
  19261. delete obj.addTags;
  19262. delete obj.removeTags;
  19263. delete obj.matchesTagsQuery;
  19264. };
  19265. Tags.HasTags = function (obj) {
  19266. if (!obj._tags) {
  19267. return false;
  19268. }
  19269. return !BABYLON.Tools.IsEmpty(obj._tags);
  19270. };
  19271. Tags.GetTags = function (obj) {
  19272. if (!obj._tags) {
  19273. return null;
  19274. }
  19275. return obj._tags;
  19276. };
  19277. Tags.AddTagsTo = function (obj, tagsString) {
  19278. if (!tagsString) {
  19279. return;
  19280. }
  19281. var tags = tagsString.split(" ");
  19282. for (var t in tags) {
  19283. Tags._AddTagTo(obj, tags[t]);
  19284. }
  19285. };
  19286. Tags._AddTagTo = function (obj, tag) {
  19287. tag = tag.trim();
  19288. if (tag === "" || tag === "true" || tag === "false") {
  19289. return;
  19290. }
  19291. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  19292. return;
  19293. }
  19294. Tags.EnableFor(obj);
  19295. obj._tags[tag] = true;
  19296. };
  19297. Tags.RemoveTagsFrom = function (obj, tagsString) {
  19298. if (!Tags.HasTags(obj)) {
  19299. return;
  19300. }
  19301. var tags = tagsString.split(" ");
  19302. for (var t in tags) {
  19303. Tags._RemoveTagFrom(obj, tags[t]);
  19304. }
  19305. };
  19306. Tags._RemoveTagFrom = function (obj, tag) {
  19307. delete obj._tags[tag];
  19308. };
  19309. Tags.MatchesQuery = function (obj, tagsQuery) {
  19310. if (tagsQuery === undefined) {
  19311. return true;
  19312. }
  19313. if (tagsQuery === "") {
  19314. return Tags.HasTags(obj);
  19315. }
  19316. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  19317. return Tags.HasTags(obj) && obj._tags[r];
  19318. });
  19319. };
  19320. return Tags;
  19321. })();
  19322. BABYLON.Tags = Tags;
  19323. })(BABYLON || (BABYLON = {}));
  19324. var BABYLON;
  19325. (function (BABYLON) {
  19326. (function (Internals) {
  19327. var AndOrNotEvaluator = (function () {
  19328. function AndOrNotEvaluator() {
  19329. }
  19330. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  19331. if (!query.match(/\([^\(\)]*\)/g)) {
  19332. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  19333. } else {
  19334. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  19335. r = r.slice(1, r.length - 1);
  19336. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  19337. });
  19338. }
  19339. if (query === "true") {
  19340. return true;
  19341. }
  19342. if (query === "false") {
  19343. return false;
  19344. }
  19345. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  19346. };
  19347. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  19348. evaluateCallback = evaluateCallback || (function (r) {
  19349. return r === "true" ? true : false;
  19350. });
  19351. var result;
  19352. var or = parenthesisContent.split("||");
  19353. for (var i in or) {
  19354. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  19355. var and = ori.split("&&");
  19356. if (and.length > 1) {
  19357. for (var j = 0; j < and.length; ++j) {
  19358. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  19359. if (andj !== "true" && andj !== "false") {
  19360. if (andj[0] === "!") {
  19361. result = !evaluateCallback(andj.substring(1));
  19362. } else {
  19363. result = evaluateCallback(andj);
  19364. }
  19365. } else {
  19366. result = andj === "true" ? true : false;
  19367. }
  19368. if (!result) {
  19369. ori = "false";
  19370. break;
  19371. }
  19372. }
  19373. }
  19374. if (result || ori === "true") {
  19375. result = true;
  19376. break;
  19377. }
  19378. if (ori !== "true" && ori !== "false") {
  19379. if (ori[0] === "!") {
  19380. result = !evaluateCallback(ori.substring(1));
  19381. } else {
  19382. result = evaluateCallback(ori);
  19383. }
  19384. } else {
  19385. result = ori === "true" ? true : false;
  19386. }
  19387. }
  19388. return result ? "true" : "false";
  19389. };
  19390. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  19391. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  19392. r = r.replace(/[\s]/g, function () {
  19393. return "";
  19394. });
  19395. return r.length % 2 ? "!" : "";
  19396. });
  19397. booleanString = booleanString.trim();
  19398. if (booleanString === "!true") {
  19399. booleanString = "false";
  19400. } else if (booleanString === "!false") {
  19401. booleanString = "true";
  19402. }
  19403. return booleanString;
  19404. };
  19405. return AndOrNotEvaluator;
  19406. })();
  19407. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  19408. })(BABYLON.Internals || (BABYLON.Internals = {}));
  19409. var Internals = BABYLON.Internals;
  19410. })(BABYLON || (BABYLON = {}));
  19411. var BABYLON;
  19412. (function (BABYLON) {
  19413. var PostProcessRenderPass = (function () {
  19414. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  19415. this._enabled = true;
  19416. this._refCount = 0;
  19417. this._name = name;
  19418. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  19419. this.setRenderList(renderList);
  19420. this._renderTexture.onBeforeRender = beforeRender;
  19421. this._renderTexture.onAfterRender = afterRender;
  19422. this._scene = scene;
  19423. this._renderList = renderList;
  19424. }
  19425. PostProcessRenderPass.prototype._incRefCount = function () {
  19426. if (this._refCount === 0) {
  19427. this._scene.customRenderTargets.push(this._renderTexture);
  19428. }
  19429. return ++this._refCount;
  19430. };
  19431. PostProcessRenderPass.prototype._decRefCount = function () {
  19432. this._refCount--;
  19433. if (this._refCount <= 0) {
  19434. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  19435. }
  19436. return this._refCount;
  19437. };
  19438. PostProcessRenderPass.prototype._update = function () {
  19439. this.setRenderList(this._renderList);
  19440. };
  19441. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  19442. this._renderTexture.renderList = renderList;
  19443. };
  19444. PostProcessRenderPass.prototype.getRenderTexture = function () {
  19445. return this._renderTexture;
  19446. };
  19447. return PostProcessRenderPass;
  19448. })();
  19449. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  19450. })(BABYLON || (BABYLON = {}));
  19451. var BABYLON;
  19452. (function (BABYLON) {
  19453. var PostProcessRenderEffect = (function () {
  19454. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  19455. this._engine = engine;
  19456. this._name = name;
  19457. this._singleInstance = singleInstance || true;
  19458. this._getPostProcess = getPostProcess;
  19459. this._cameras = [];
  19460. this._indicesForCamera = [];
  19461. this._postProcesses = {};
  19462. this._renderPasses = {};
  19463. this._renderEffectAsPasses = {};
  19464. }
  19465. PostProcessRenderEffect.prototype._update = function () {
  19466. for (var renderPassName in this._renderPasses) {
  19467. this._renderPasses[renderPassName]._update();
  19468. }
  19469. };
  19470. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  19471. this._renderPasses[renderPass._name] = renderPass;
  19472. this._linkParameters();
  19473. };
  19474. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  19475. delete this._renderPasses[renderPass._name];
  19476. this._linkParameters();
  19477. };
  19478. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  19479. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  19480. this._linkParameters();
  19481. };
  19482. PostProcessRenderEffect.prototype.getPass = function (passName) {
  19483. for (var renderPassName in this._renderPasses) {
  19484. if (renderPassName === passName) {
  19485. return this._renderPasses[passName];
  19486. }
  19487. }
  19488. };
  19489. PostProcessRenderEffect.prototype.emptyPasses = function () {
  19490. this._renderPasses = {};
  19491. this._linkParameters();
  19492. };
  19493. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  19494. var cameraKey;
  19495. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19496. for (var i = 0; i < _cam.length; i++) {
  19497. var camera = _cam[i];
  19498. var cameraName = camera.name;
  19499. if (this._singleInstance) {
  19500. cameraKey = 0;
  19501. } else {
  19502. cameraKey = cameraName;
  19503. }
  19504. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  19505. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  19506. if (!this._indicesForCamera[cameraName]) {
  19507. this._indicesForCamera[cameraName] = [];
  19508. }
  19509. this._indicesForCamera[cameraName].push(index);
  19510. if (this._cameras.indexOf(camera) === -1) {
  19511. this._cameras[cameraName] = camera;
  19512. }
  19513. for (var passName in this._renderPasses) {
  19514. this._renderPasses[passName]._incRefCount();
  19515. }
  19516. }
  19517. this._linkParameters();
  19518. };
  19519. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  19520. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19521. for (var i = 0; i < _cam.length; i++) {
  19522. var camera = _cam[i];
  19523. var cameraName = camera.name;
  19524. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  19525. var index = this._cameras.indexOf(cameraName);
  19526. this._indicesForCamera.splice(index, 1);
  19527. this._cameras.splice(index, 1);
  19528. for (var passName in this._renderPasses) {
  19529. this._renderPasses[passName]._decRefCount();
  19530. }
  19531. }
  19532. };
  19533. PostProcessRenderEffect.prototype._enable = function (cameras) {
  19534. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19535. for (var i = 0; i < _cam.length; i++) {
  19536. var camera = _cam[i];
  19537. var cameraName = camera.name;
  19538. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  19539. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  19540. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  19541. }
  19542. }
  19543. for (var passName in this._renderPasses) {
  19544. this._renderPasses[passName]._incRefCount();
  19545. }
  19546. }
  19547. };
  19548. PostProcessRenderEffect.prototype._disable = function (cameras) {
  19549. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19550. for (var i = 0; i < _cam.length; i++) {
  19551. var camera = _cam[i];
  19552. var cameraName = camera.Name;
  19553. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  19554. for (var passName in this._renderPasses) {
  19555. this._renderPasses[passName]._decRefCount();
  19556. }
  19557. }
  19558. };
  19559. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  19560. if (this._singleInstance) {
  19561. return this._postProcesses[0];
  19562. } else {
  19563. return this._postProcesses[camera.name];
  19564. }
  19565. };
  19566. PostProcessRenderEffect.prototype._linkParameters = function () {
  19567. var _this = this;
  19568. for (var index in this._postProcesses) {
  19569. if (this.applyParameters) {
  19570. this.applyParameters(this._postProcesses[index]);
  19571. }
  19572. this._postProcesses[index].onBeforeRender = function (effect) {
  19573. _this._linkTextures(effect);
  19574. };
  19575. }
  19576. };
  19577. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  19578. for (var renderPassName in this._renderPasses) {
  19579. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  19580. }
  19581. for (var renderEffectName in this._renderEffectAsPasses) {
  19582. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  19583. }
  19584. };
  19585. return PostProcessRenderEffect;
  19586. })();
  19587. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  19588. })(BABYLON || (BABYLON = {}));
  19589. var BABYLON;
  19590. (function (BABYLON) {
  19591. var PostProcessRenderPipeline = (function () {
  19592. function PostProcessRenderPipeline(engine, name) {
  19593. this._engine = engine;
  19594. this._name = name;
  19595. this._renderEffects = {};
  19596. this._renderEffectsForIsolatedPass = {};
  19597. this._cameras = [];
  19598. }
  19599. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  19600. this._renderEffects[renderEffect._name] = renderEffect;
  19601. };
  19602. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  19603. var renderEffects = this._renderEffects[renderEffectName];
  19604. if (!renderEffects) {
  19605. return;
  19606. }
  19607. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  19608. };
  19609. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  19610. var renderEffects = this._renderEffects[renderEffectName];
  19611. if (!renderEffects) {
  19612. return;
  19613. }
  19614. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  19615. };
  19616. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  19617. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19618. var indicesToDelete = [];
  19619. for (var i = 0; i < _cam.length; i++) {
  19620. var camera = _cam[i];
  19621. var cameraName = camera.name;
  19622. if (this._cameras.indexOf(camera) === -1) {
  19623. this._cameras[cameraName] = camera;
  19624. } else if (unique) {
  19625. indicesToDelete.push(i);
  19626. }
  19627. }
  19628. for (var i = 0; i < indicesToDelete.length; i++) {
  19629. cameras.splice(indicesToDelete[i], 1);
  19630. }
  19631. for (var renderEffectName in this._renderEffects) {
  19632. this._renderEffects[renderEffectName]._attachCameras(_cam);
  19633. }
  19634. };
  19635. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  19636. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19637. for (var renderEffectName in this._renderEffects) {
  19638. this._renderEffects[renderEffectName]._detachCameras(_cam);
  19639. }
  19640. for (var i = 0; i < _cam.length; i++) {
  19641. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  19642. }
  19643. };
  19644. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  19645. var _this = this;
  19646. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19647. var pass = null;
  19648. for (var renderEffectName in this._renderEffects) {
  19649. pass = this._renderEffects[renderEffectName].getPass(passName);
  19650. if (pass != null) {
  19651. break;
  19652. }
  19653. }
  19654. if (pass === null) {
  19655. return;
  19656. }
  19657. for (var renderEffectName in this._renderEffects) {
  19658. this._renderEffects[renderEffectName]._disable(_cam);
  19659. }
  19660. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  19661. for (var i = 0; i < _cam.length; i++) {
  19662. var camera = _cam[i];
  19663. var cameraName = camera.name;
  19664. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  19665. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  19666. });
  19667. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  19668. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  19669. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  19670. }
  19671. };
  19672. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  19673. var _this = this;
  19674. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19675. for (var i = 0; i < _cam.length; i++) {
  19676. var camera = _cam[i];
  19677. var cameraName = camera.name;
  19678. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  19679. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  19680. });
  19681. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  19682. }
  19683. for (var renderEffectName in this._renderEffects) {
  19684. this._renderEffects[renderEffectName]._enable(_cam);
  19685. }
  19686. };
  19687. PostProcessRenderPipeline.prototype._update = function () {
  19688. for (var renderEffectName in this._renderEffects) {
  19689. this._renderEffects[renderEffectName]._update();
  19690. }
  19691. for (var i = 0; i < this._cameras.length; i++) {
  19692. var cameraName = this._cameras[i].name;
  19693. if (this._renderEffectsForIsolatedPass[cameraName]) {
  19694. this._renderEffectsForIsolatedPass[cameraName]._update();
  19695. }
  19696. }
  19697. };
  19698. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  19699. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  19700. return PostProcessRenderPipeline;
  19701. })();
  19702. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  19703. })(BABYLON || (BABYLON = {}));
  19704. var BABYLON;
  19705. (function (BABYLON) {
  19706. var PostProcessRenderPipelineManager = (function () {
  19707. function PostProcessRenderPipelineManager() {
  19708. this._renderPipelines = {};
  19709. }
  19710. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  19711. this._renderPipelines[renderPipeline._name] = renderPipeline;
  19712. };
  19713. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  19714. var renderPipeline = this._renderPipelines[renderPipelineName];
  19715. if (!renderPipeline) {
  19716. return;
  19717. }
  19718. renderPipeline._attachCameras(cameras, unique);
  19719. };
  19720. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  19721. var renderPipeline = this._renderPipelines[renderPipelineName];
  19722. if (!renderPipeline) {
  19723. return;
  19724. }
  19725. renderPipeline._detachCameras(cameras);
  19726. };
  19727. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  19728. var renderPipeline = this._renderPipelines[renderPipelineName];
  19729. if (!renderPipeline) {
  19730. return;
  19731. }
  19732. renderPipeline._enableEffect(renderEffectName, cameras);
  19733. };
  19734. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  19735. var renderPipeline = this._renderPipelines[renderPipelineName];
  19736. if (!renderPipeline) {
  19737. return;
  19738. }
  19739. renderPipeline._disableEffect(renderEffectName, cameras);
  19740. };
  19741. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  19742. var renderPipeline = this._renderPipelines[renderPipelineName];
  19743. if (!renderPipeline) {
  19744. return;
  19745. }
  19746. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  19747. };
  19748. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  19749. var renderPipeline = this._renderPipelines[renderPipelineName];
  19750. if (!renderPipeline) {
  19751. return;
  19752. }
  19753. renderPipeline._disableDisplayOnlyPass(cameras);
  19754. };
  19755. PostProcessRenderPipelineManager.prototype.update = function () {
  19756. for (var renderPipelineName in this._renderPipelines) {
  19757. this._renderPipelines[renderPipelineName]._update();
  19758. }
  19759. };
  19760. return PostProcessRenderPipelineManager;
  19761. })();
  19762. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  19763. })(BABYLON || (BABYLON = {}));
  19764. var __extends = this.__extends || function (d, b) {
  19765. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19766. function __() { this.constructor = d; }
  19767. __.prototype = b.prototype;
  19768. d.prototype = new __();
  19769. };
  19770. var BABYLON;
  19771. (function (BABYLON) {
  19772. var DisplayPassPostProcess = (function (_super) {
  19773. __extends(DisplayPassPostProcess, _super);
  19774. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  19775. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  19776. }
  19777. return DisplayPassPostProcess;
  19778. })(BABYLON.PostProcess);
  19779. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  19780. })(BABYLON || (BABYLON = {}));
  19781. var BABYLON;
  19782. (function (BABYLON) {
  19783. var BoundingBoxRenderer = (function () {
  19784. function BoundingBoxRenderer(scene) {
  19785. this.frontColor = new BABYLON.Color3(1, 1, 1);
  19786. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  19787. this.showBackLines = true;
  19788. this.renderList = new BABYLON.SmartArray(32);
  19789. this._scene = scene;
  19790. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  19791. attributes: ["position"],
  19792. uniforms: ["worldViewProjection", "color"]
  19793. });
  19794. var engine = this._scene.getEngine();
  19795. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  19796. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  19797. 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]);
  19798. }
  19799. BoundingBoxRenderer.prototype.reset = function () {
  19800. this.renderList.reset();
  19801. };
  19802. BoundingBoxRenderer.prototype.render = function () {
  19803. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  19804. return;
  19805. }
  19806. var engine = this._scene.getEngine();
  19807. engine.setDepthWrite(false);
  19808. this._colorShader._preBind();
  19809. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  19810. var boundingBox = this.renderList.data[boundingBoxIndex];
  19811. var min = boundingBox.minimum;
  19812. var max = boundingBox.maximum;
  19813. var diff = max.subtract(min);
  19814. var median = min.add(diff.scale(0.5));
  19815. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  19816. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  19817. if (this.showBackLines) {
  19818. engine.setDepthFunctionToGreaterOrEqual();
  19819. this._scene.resetCachedMaterial();
  19820. this._colorShader.setColor4("color", this.backColor.toColor4());
  19821. this._colorShader.bind(worldMatrix);
  19822. engine.draw(false, 0, 24);
  19823. }
  19824. engine.setDepthFunctionToLess();
  19825. this._scene.resetCachedMaterial();
  19826. this._colorShader.setColor4("color", this.frontColor.toColor4());
  19827. this._colorShader.bind(worldMatrix);
  19828. engine.draw(false, 0, 24);
  19829. }
  19830. this._colorShader.unbind();
  19831. engine.setDepthFunctionToLessOrEqual();
  19832. engine.setDepthWrite(true);
  19833. };
  19834. BoundingBoxRenderer.prototype.dispose = function () {
  19835. this._colorShader.dispose();
  19836. this._vb.dispose();
  19837. this._scene.getEngine()._releaseBuffer(this._ib);
  19838. };
  19839. return BoundingBoxRenderer;
  19840. })();
  19841. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  19842. })(BABYLON || (BABYLON = {}));
  19843. /**
  19844. * Based on jsTGALoader - Javascript loader for TGA file
  19845. * By Vincent Thibault
  19846. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  19847. */
  19848. var BABYLON;
  19849. (function (BABYLON) {
  19850. (function (Internals) {
  19851. var TGATools = (function () {
  19852. function TGATools() {
  19853. }
  19854. TGATools.GetTGAHeader = function (data) {
  19855. var offset = 0;
  19856. var header = {
  19857. id_length: data[offset++],
  19858. colormap_type: data[offset++],
  19859. image_type: data[offset++],
  19860. colormap_index: data[offset++] | data[offset++] << 8,
  19861. colormap_length: data[offset++] | data[offset++] << 8,
  19862. colormap_size: data[offset++],
  19863. origin: [
  19864. data[offset++] | data[offset++] << 8,
  19865. data[offset++] | data[offset++] << 8
  19866. ],
  19867. width: data[offset++] | data[offset++] << 8,
  19868. height: data[offset++] | data[offset++] << 8,
  19869. pixel_size: data[offset++],
  19870. flags: data[offset++]
  19871. };
  19872. return header;
  19873. };
  19874. TGATools.UploadContent = function (gl, data) {
  19875. if (data.length < 19) {
  19876. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  19877. return;
  19878. }
  19879. var offset = 18;
  19880. var header = TGATools.GetTGAHeader(data);
  19881. if (header.id_length + offset > data.length) {
  19882. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  19883. return;
  19884. }
  19885. offset += header.id_length;
  19886. var use_rle = false;
  19887. var use_pal = false;
  19888. var use_rgb = false;
  19889. var use_grey = false;
  19890. switch (header.image_type) {
  19891. case TGATools._TYPE_RLE_INDEXED:
  19892. use_rle = true;
  19893. case TGATools._TYPE_INDEXED:
  19894. use_pal = true;
  19895. break;
  19896. case TGATools._TYPE_RLE_RGB:
  19897. use_rle = true;
  19898. case TGATools._TYPE_RGB:
  19899. use_rgb = true;
  19900. break;
  19901. case TGATools._TYPE_RLE_GREY:
  19902. use_rle = true;
  19903. case TGATools._TYPE_GREY:
  19904. use_grey = true;
  19905. break;
  19906. }
  19907. var pixel_data;
  19908. var numAlphaBits = header.flags & 0xf;
  19909. var pixel_size = header.pixel_size >> 3;
  19910. var pixel_total = header.width * header.height * pixel_size;
  19911. var palettes;
  19912. if (use_pal) {
  19913. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  19914. }
  19915. if (use_rle) {
  19916. pixel_data = new Uint8Array(pixel_total);
  19917. var c, count, i;
  19918. var localOffset = 0;
  19919. var pixels = new Uint8Array(pixel_size);
  19920. while (offset < pixel_total && localOffset < pixel_total) {
  19921. c = data[offset++];
  19922. count = (c & 0x7f) + 1;
  19923. if (c & 0x80) {
  19924. for (i = 0; i < pixel_size; ++i) {
  19925. pixels[i] = data[offset++];
  19926. }
  19927. for (i = 0; i < count; ++i) {
  19928. pixel_data.set(pixels, localOffset + i * pixel_size);
  19929. }
  19930. localOffset += pixel_size * count;
  19931. } else {
  19932. count *= pixel_size;
  19933. for (i = 0; i < count; ++i) {
  19934. pixel_data[localOffset + i] = data[offset++];
  19935. }
  19936. localOffset += count;
  19937. }
  19938. }
  19939. } else {
  19940. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  19941. }
  19942. var x_start, y_start, x_step, y_step, y_end, x_end;
  19943. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  19944. default:
  19945. case TGATools._ORIGIN_UL:
  19946. x_start = 0;
  19947. x_step = 1;
  19948. x_end = header.width;
  19949. y_start = 0;
  19950. y_step = 1;
  19951. y_end = header.height;
  19952. break;
  19953. case TGATools._ORIGIN_BL:
  19954. x_start = 0;
  19955. x_step = 1;
  19956. x_end = header.width;
  19957. y_start = header.height - 1;
  19958. y_step = -1;
  19959. y_end = -1;
  19960. break;
  19961. case TGATools._ORIGIN_UR:
  19962. x_start = header.width - 1;
  19963. x_step = -1;
  19964. x_end = -1;
  19965. y_start = 0;
  19966. y_step = 1;
  19967. y_end = header.height;
  19968. break;
  19969. case TGATools._ORIGIN_BR:
  19970. x_start = header.width - 1;
  19971. x_step = -1;
  19972. x_end = -1;
  19973. y_start = header.height - 1;
  19974. y_step = -1;
  19975. y_end = -1;
  19976. break;
  19977. }
  19978. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  19979. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  19980. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  19981. };
  19982. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  19983. var image = pixel_data, colormap = palettes;
  19984. var width = header.width, height = header.height;
  19985. var color, i = 0, x, y;
  19986. var imageData = new Uint8Array(width * height * 4);
  19987. for (y = y_start; y !== y_end; y += y_step) {
  19988. for (x = x_start; x !== x_end; x += x_step, i++) {
  19989. color = image[i];
  19990. imageData[(x + width * y) * 4 + 3] = 255;
  19991. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  19992. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  19993. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  19994. }
  19995. }
  19996. return imageData;
  19997. };
  19998. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  19999. var image = pixel_data;
  20000. var width = header.width, height = header.height;
  20001. var color, i = 0, x, y;
  20002. var imageData = new Uint8Array(width * height * 4);
  20003. for (y = y_start; y !== y_end; y += y_step) {
  20004. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  20005. color = image[i + 0] + (image[i + 1] << 8);
  20006. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  20007. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  20008. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  20009. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  20010. }
  20011. }
  20012. return imageData;
  20013. };
  20014. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  20015. var image = pixel_data;
  20016. var width = header.width, height = header.height;
  20017. var i = 0, x, y;
  20018. var imageData = new Uint8Array(width * height * 4);
  20019. for (y = y_start; y !== y_end; y += y_step) {
  20020. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  20021. imageData[(x + width * y) * 4 + 3] = 255;
  20022. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  20023. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  20024. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  20025. }
  20026. }
  20027. return imageData;
  20028. };
  20029. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  20030. var image = pixel_data;
  20031. var width = header.width, height = header.height;
  20032. var i = 0, x, y;
  20033. var imageData = new Uint8Array(width * height * 4);
  20034. for (y = y_start; y !== y_end; y += y_step) {
  20035. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  20036. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  20037. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  20038. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  20039. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  20040. }
  20041. }
  20042. return imageData;
  20043. };
  20044. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  20045. var image = pixel_data;
  20046. var width = header.width, height = header.height;
  20047. var color, i = 0, x, y;
  20048. var imageData = new Uint8Array(width * height * 4);
  20049. for (y = y_start; y !== y_end; y += y_step) {
  20050. for (x = x_start; x !== x_end; x += x_step, i++) {
  20051. color = image[i];
  20052. imageData[(x + width * y) * 4 + 0] = color;
  20053. imageData[(x + width * y) * 4 + 1] = color;
  20054. imageData[(x + width * y) * 4 + 2] = color;
  20055. imageData[(x + width * y) * 4 + 3] = 255;
  20056. }
  20057. }
  20058. return imageData;
  20059. };
  20060. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  20061. var image = pixel_data;
  20062. var width = header.width, height = header.height;
  20063. var i = 0, x, y;
  20064. var imageData = new Uint8Array(width * height * 4);
  20065. for (y = y_start; y !== y_end; y += y_step) {
  20066. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  20067. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  20068. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  20069. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  20070. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  20071. }
  20072. }
  20073. return imageData;
  20074. };
  20075. TGATools._TYPE_NO_DATA = 0;
  20076. TGATools._TYPE_INDEXED = 1;
  20077. TGATools._TYPE_RGB = 2;
  20078. TGATools._TYPE_GREY = 3;
  20079. TGATools._TYPE_RLE_INDEXED = 9;
  20080. TGATools._TYPE_RLE_RGB = 10;
  20081. TGATools._TYPE_RLE_GREY = 11;
  20082. TGATools._ORIGIN_MASK = 0x30;
  20083. TGATools._ORIGIN_SHIFT = 0x04;
  20084. TGATools._ORIGIN_BL = 0x00;
  20085. TGATools._ORIGIN_BR = 0x01;
  20086. TGATools._ORIGIN_UL = 0x02;
  20087. TGATools._ORIGIN_UR = 0x03;
  20088. return TGATools;
  20089. })();
  20090. Internals.TGATools = TGATools;
  20091. })(BABYLON.Internals || (BABYLON.Internals = {}));
  20092. var Internals = BABYLON.Internals;
  20093. })(BABYLON || (BABYLON = {}));
  20094. var BABYLON;
  20095. (function (BABYLON) {
  20096. (function (Internals) {
  20097. var DDS_MAGIC = 0x20534444;
  20098. 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;
  20099. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  20100. 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;
  20101. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  20102. function FourCCToInt32(value) {
  20103. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  20104. }
  20105. function Int32ToFourCC(value) {
  20106. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  20107. }
  20108. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  20109. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  20110. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  20111. var headerLengthInt = 31;
  20112. var off_magic = 0;
  20113. var off_size = 1;
  20114. var off_flags = 2;
  20115. var off_height = 3;
  20116. var off_width = 4;
  20117. var off_mipmapCount = 7;
  20118. var off_pfFlags = 20;
  20119. var off_pfFourCC = 21;
  20120. var off_RGBbpp = 22;
  20121. var off_RMask = 23;
  20122. var off_GMask = 24;
  20123. var off_BMask = 25;
  20124. var off_AMask = 26;
  20125. var off_caps1 = 27;
  20126. var off_caps2 = 28;
  20127. ;
  20128. var DDSTools = (function () {
  20129. function DDSTools() {
  20130. }
  20131. DDSTools.GetDDSInfo = function (arrayBuffer) {
  20132. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  20133. var mipmapCount = 1;
  20134. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  20135. mipmapCount = Math.max(1, header[off_mipmapCount]);
  20136. }
  20137. return {
  20138. width: header[off_width],
  20139. height: header[off_height],
  20140. mipmapCount: mipmapCount,
  20141. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  20142. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  20143. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  20144. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  20145. };
  20146. };
  20147. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  20148. var byteArray = new Uint8Array(dataLength);
  20149. var srcData = new Uint8Array(arrayBuffer);
  20150. var index = 0;
  20151. for (var y = height - 1; y >= 0; y--) {
  20152. for (var x = 0; x < width; x++) {
  20153. var srcPos = dataOffset + (x + y * width) * 4;
  20154. byteArray[index + 2] = srcData[srcPos];
  20155. byteArray[index + 1] = srcData[srcPos + 1];
  20156. byteArray[index] = srcData[srcPos + 2];
  20157. byteArray[index + 3] = srcData[srcPos + 3];
  20158. index += 4;
  20159. }
  20160. }
  20161. return byteArray;
  20162. };
  20163. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  20164. var byteArray = new Uint8Array(dataLength);
  20165. var srcData = new Uint8Array(arrayBuffer);
  20166. var index = 0;
  20167. for (var y = height - 1; y >= 0; y--) {
  20168. for (var x = 0; x < width; x++) {
  20169. var srcPos = dataOffset + (x + y * width) * 3;
  20170. byteArray[index + 2] = srcData[srcPos];
  20171. byteArray[index + 1] = srcData[srcPos + 1];
  20172. byteArray[index] = srcData[srcPos + 2];
  20173. index += 3;
  20174. }
  20175. }
  20176. return byteArray;
  20177. };
  20178. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  20179. var byteArray = new Uint8Array(dataLength);
  20180. var srcData = new Uint8Array(arrayBuffer);
  20181. var index = 0;
  20182. for (var y = height - 1; y >= 0; y--) {
  20183. for (var x = 0; x < width; x++) {
  20184. var srcPos = dataOffset + (x + y * width);
  20185. byteArray[index] = srcData[srcPos];
  20186. index++;
  20187. }
  20188. }
  20189. return byteArray;
  20190. };
  20191. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  20192. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  20193. if (header[off_magic] != DDS_MAGIC) {
  20194. BABYLON.Tools.Error("Invalid magic number in DDS header");
  20195. return;
  20196. }
  20197. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  20198. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  20199. return;
  20200. }
  20201. if (info.isFourCC) {
  20202. fourCC = header[off_pfFourCC];
  20203. switch (fourCC) {
  20204. case FOURCC_DXT1:
  20205. blockBytes = 8;
  20206. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  20207. break;
  20208. case FOURCC_DXT3:
  20209. blockBytes = 16;
  20210. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  20211. break;
  20212. case FOURCC_DXT5:
  20213. blockBytes = 16;
  20214. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  20215. break;
  20216. default:
  20217. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  20218. return;
  20219. }
  20220. }
  20221. mipmapCount = 1;
  20222. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  20223. mipmapCount = Math.max(1, header[off_mipmapCount]);
  20224. }
  20225. var bpp = header[off_RGBbpp];
  20226. for (var face = 0; face < faces; face++) {
  20227. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  20228. width = header[off_width];
  20229. height = header[off_height];
  20230. dataOffset = header[off_size] + 4;
  20231. for (i = 0; i < mipmapCount; ++i) {
  20232. if (info.isRGB) {
  20233. if (bpp == 24) {
  20234. dataLength = width * height * 3;
  20235. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  20236. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  20237. } else {
  20238. dataLength = width * height * 4;
  20239. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  20240. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  20241. }
  20242. } else if (info.isLuminance) {
  20243. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  20244. var unpaddedRowSize = width;
  20245. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  20246. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  20247. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  20248. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  20249. } else {
  20250. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  20251. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  20252. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  20253. }
  20254. dataOffset += dataLength;
  20255. width *= 0.5;
  20256. height *= 0.5;
  20257. width = Math.max(1.0, width);
  20258. height = Math.max(1.0, height);
  20259. }
  20260. }
  20261. };
  20262. return DDSTools;
  20263. })();
  20264. Internals.DDSTools = DDSTools;
  20265. })(BABYLON.Internals || (BABYLON.Internals = {}));
  20266. var Internals = BABYLON.Internals;
  20267. })(BABYLON || (BABYLON = {}));
  20268. var BABYLON;
  20269. (function (BABYLON) {
  20270. var SmartArray = (function () {
  20271. function SmartArray(capacity) {
  20272. this.length = 0;
  20273. this._duplicateId = 0;
  20274. this.data = new Array(capacity);
  20275. this._id = SmartArray._GlobalId++;
  20276. }
  20277. SmartArray.prototype.push = function (value) {
  20278. this.data[this.length++] = value;
  20279. if (this.length > this.data.length) {
  20280. this.data.length *= 2;
  20281. }
  20282. if (!value.__smartArrayFlags) {
  20283. value.__smartArrayFlags = {};
  20284. }
  20285. value.__smartArrayFlags[this._id] = this._duplicateId;
  20286. };
  20287. SmartArray.prototype.pushNoDuplicate = function (value) {
  20288. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  20289. return;
  20290. }
  20291. this.push(value);
  20292. };
  20293. SmartArray.prototype.sort = function (compareFn) {
  20294. this.data.sort(compareFn);
  20295. };
  20296. SmartArray.prototype.reset = function () {
  20297. this.length = 0;
  20298. this._duplicateId++;
  20299. };
  20300. SmartArray.prototype.concat = function (array) {
  20301. if (array.length === 0) {
  20302. return;
  20303. }
  20304. if (this.length + array.length > this.data.length) {
  20305. this.data.length = (this.length + array.length) * 2;
  20306. }
  20307. for (var index = 0; index < array.length; index++) {
  20308. this.data[this.length++] = (array.data || array)[index];
  20309. }
  20310. };
  20311. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  20312. if (array.length === 0) {
  20313. return;
  20314. }
  20315. if (this.length + array.length > this.data.length) {
  20316. this.data.length = (this.length + array.length) * 2;
  20317. }
  20318. for (var index = 0; index < array.length; index++) {
  20319. var item = (array.data || array)[index];
  20320. this.pushNoDuplicate(item);
  20321. }
  20322. };
  20323. SmartArray.prototype.indexOf = function (value) {
  20324. var position = this.data.indexOf(value);
  20325. if (position >= this.length) {
  20326. return -1;
  20327. }
  20328. return position;
  20329. };
  20330. SmartArray._GlobalId = 0;
  20331. return SmartArray;
  20332. })();
  20333. BABYLON.SmartArray = SmartArray;
  20334. })(BABYLON || (BABYLON = {}));
  20335. var BABYLON;
  20336. (function (BABYLON) {
  20337. var CannonJSPlugin = (function () {
  20338. function CannonJSPlugin() {
  20339. this._registeredMeshes = [];
  20340. this._physicsMaterials = [];
  20341. this.updateBodyPosition = function (mesh) {
  20342. for (var index = 0; index < this._registeredMeshes.length; index++) {
  20343. var registeredMesh = this._registeredMeshes[index];
  20344. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  20345. var body = registeredMesh.body;
  20346. var center = mesh.getBoundingInfo().boundingBox.center;
  20347. body.position.set(center.x, center.z, center.y);
  20348. body.quaternion.x = mesh.rotationQuaternion.x;
  20349. body.quaternion.z = mesh.rotationQuaternion.y;
  20350. body.quaternion.y = mesh.rotationQuaternion.z;
  20351. body.quaternion.w = -mesh.rotationQuaternion.w;
  20352. return;
  20353. }
  20354. }
  20355. };
  20356. }
  20357. CannonJSPlugin.prototype.initialize = function (iterations) {
  20358. if (typeof iterations === "undefined") { iterations = 10; }
  20359. this._world = new CANNON.World();
  20360. this._world.broadphase = new CANNON.NaiveBroadphase();
  20361. this._world.solver.iterations = iterations;
  20362. };
  20363. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  20364. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  20365. };
  20366. CannonJSPlugin.prototype.runOneStep = function (delta) {
  20367. this._world.step(delta);
  20368. for (var index = 0; index < this._registeredMeshes.length; index++) {
  20369. var registeredMesh = this._registeredMeshes[index];
  20370. if (registeredMesh.isChild) {
  20371. continue;
  20372. }
  20373. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  20374. var deltaPos = registeredMesh.delta;
  20375. if (deltaPos) {
  20376. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  20377. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  20378. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  20379. } else {
  20380. registeredMesh.mesh.position.x = bodyX;
  20381. registeredMesh.mesh.position.y = bodyZ;
  20382. registeredMesh.mesh.position.z = bodyY;
  20383. }
  20384. if (!registeredMesh.mesh.rotationQuaternion) {
  20385. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  20386. }
  20387. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  20388. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  20389. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  20390. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  20391. }
  20392. };
  20393. CannonJSPlugin.prototype.setGravity = function (gravity) {
  20394. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  20395. };
  20396. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  20397. this.unregisterMesh(mesh);
  20398. mesh.computeWorldMatrix(true);
  20399. switch (impostor) {
  20400. case BABYLON.PhysicsEngine.SphereImpostor:
  20401. var bbox = mesh.getBoundingInfo().boundingBox;
  20402. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  20403. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  20404. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  20405. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  20406. case BABYLON.PhysicsEngine.BoxImpostor:
  20407. bbox = mesh.getBoundingInfo().boundingBox;
  20408. var min = bbox.minimumWorld;
  20409. var max = bbox.maximumWorld;
  20410. var box = max.subtract(min).scale(0.5);
  20411. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  20412. case BABYLON.PhysicsEngine.PlaneImpostor:
  20413. return this._createPlane(mesh, options);
  20414. case BABYLON.PhysicsEngine.MeshImpostor:
  20415. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20416. var rawFaces = mesh.getIndices();
  20417. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  20418. }
  20419. return null;
  20420. };
  20421. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  20422. var shape = new CANNON.Sphere(radius);
  20423. if (!options) {
  20424. return shape;
  20425. }
  20426. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  20427. };
  20428. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  20429. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  20430. if (!options) {
  20431. return shape;
  20432. }
  20433. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  20434. };
  20435. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  20436. var shape = new CANNON.Plane();
  20437. if (!options) {
  20438. return shape;
  20439. }
  20440. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  20441. };
  20442. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  20443. var verts = [], faces = [];
  20444. mesh.computeWorldMatrix(true);
  20445. for (var i = 0; i < rawVerts.length; i += 3) {
  20446. var transformed = BABYLON.Vector3.Zero();
  20447. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  20448. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  20449. }
  20450. for (var j = 0; j < rawFaces.length; j += 3) {
  20451. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  20452. }
  20453. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  20454. if (!options) {
  20455. return shape;
  20456. }
  20457. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  20458. };
  20459. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  20460. var index;
  20461. var mat;
  20462. for (index = 0; index < this._physicsMaterials.length; index++) {
  20463. mat = this._physicsMaterials[index];
  20464. if (mat.friction === friction && mat.restitution === restitution) {
  20465. return mat;
  20466. }
  20467. }
  20468. var currentMat = new CANNON.Material();
  20469. currentMat.friction = friction;
  20470. currentMat.restitution = restitution;
  20471. this._physicsMaterials.push(currentMat);
  20472. for (index = 0; index < this._physicsMaterials.length; index++) {
  20473. mat = this._physicsMaterials[index];
  20474. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  20475. contactMaterial.contactEquationStiffness = 1e10;
  20476. contactMaterial.contactEquationRegularizationTime = 10;
  20477. this._world.addContactMaterial(contactMaterial);
  20478. }
  20479. return currentMat;
  20480. };
  20481. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  20482. var initialRotation = null;
  20483. if (mesh.rotationQuaternion) {
  20484. initialRotation = mesh.rotationQuaternion.clone();
  20485. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  20486. }
  20487. var bbox = mesh.getBoundingInfo().boundingBox;
  20488. var deltaPosition = mesh.position.subtract(bbox.center);
  20489. var material = this._addMaterial(friction, restitution);
  20490. var body = new CANNON.RigidBody(mass, shape, material);
  20491. if (initialRotation) {
  20492. body.quaternion.x = initialRotation.x;
  20493. body.quaternion.z = initialRotation.y;
  20494. body.quaternion.y = initialRotation.z;
  20495. body.quaternion.w = -initialRotation.w;
  20496. }
  20497. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  20498. this._world.add(body);
  20499. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  20500. return body;
  20501. };
  20502. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  20503. var compoundShape = new CANNON.Compound();
  20504. for (var index = 0; index < parts.length; index++) {
  20505. var mesh = parts[index].mesh;
  20506. var shape = this.registerMesh(mesh, parts[index].impostor);
  20507. if (index == 0) {
  20508. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  20509. } else {
  20510. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  20511. }
  20512. }
  20513. var initialMesh = parts[0].mesh;
  20514. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  20515. body.parts = parts;
  20516. return body;
  20517. };
  20518. CannonJSPlugin.prototype._unbindBody = function (body) {
  20519. for (var index = 0; index < this._registeredMeshes.length; index++) {
  20520. var registeredMesh = this._registeredMeshes[index];
  20521. if (registeredMesh.body === body) {
  20522. registeredMesh.body = null;
  20523. registeredMesh.delta = 0;
  20524. }
  20525. }
  20526. };
  20527. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  20528. for (var index = 0; index < this._registeredMeshes.length; index++) {
  20529. var registeredMesh = this._registeredMeshes[index];
  20530. if (registeredMesh.mesh === mesh) {
  20531. if (registeredMesh.body) {
  20532. this._world.remove(registeredMesh.body);
  20533. this._unbindBody(registeredMesh.body);
  20534. }
  20535. this._registeredMeshes.splice(index, 1);
  20536. return;
  20537. }
  20538. }
  20539. };
  20540. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  20541. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  20542. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  20543. for (var index = 0; index < this._registeredMeshes.length; index++) {
  20544. var registeredMesh = this._registeredMeshes[index];
  20545. if (registeredMesh.mesh === mesh) {
  20546. registeredMesh.body.applyImpulse(impulse, worldPoint);
  20547. return;
  20548. }
  20549. }
  20550. };
  20551. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  20552. var body1 = null, body2 = null;
  20553. for (var index = 0; index < this._registeredMeshes.length; index++) {
  20554. var registeredMesh = this._registeredMeshes[index];
  20555. if (registeredMesh.mesh === mesh1) {
  20556. body1 = registeredMesh.body;
  20557. } else if (registeredMesh.mesh === mesh2) {
  20558. body2 = registeredMesh.body;
  20559. }
  20560. }
  20561. if (!body1 || !body2) {
  20562. return false;
  20563. }
  20564. 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));
  20565. this._world.addConstraint(constraint);
  20566. return true;
  20567. };
  20568. CannonJSPlugin.prototype.dispose = function () {
  20569. while (this._registeredMeshes.length) {
  20570. this.unregisterMesh(this._registeredMeshes[0].mesh);
  20571. }
  20572. };
  20573. CannonJSPlugin.prototype.isSupported = function () {
  20574. return window.CANNON !== undefined;
  20575. };
  20576. return CannonJSPlugin;
  20577. })();
  20578. BABYLON.CannonJSPlugin = CannonJSPlugin;
  20579. })(BABYLON || (BABYLON = {}));
  20580. var __extends = this.__extends || function (d, b) {
  20581. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20582. function __() { this.constructor = d; }
  20583. __.prototype = b.prototype;
  20584. d.prototype = new __();
  20585. };
  20586. var BABYLON;
  20587. (function (BABYLON) {
  20588. var Condition = (function () {
  20589. function Condition(actionManager) {
  20590. this._actionManager = actionManager;
  20591. }
  20592. Condition.prototype.isValid = function () {
  20593. return true;
  20594. };
  20595. Condition.prototype._getProperty = function (propertyPath) {
  20596. return this._actionManager._getProperty(propertyPath);
  20597. };
  20598. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  20599. return this._actionManager._getEffectiveTarget(target, propertyPath);
  20600. };
  20601. return Condition;
  20602. })();
  20603. BABYLON.Condition = Condition;
  20604. var ValueCondition = (function (_super) {
  20605. __extends(ValueCondition, _super);
  20606. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  20607. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  20608. _super.call(this, actionManager);
  20609. this.propertyPath = propertyPath;
  20610. this.value = value;
  20611. this.operator = operator;
  20612. this._target = this._getEffectiveTarget(target, this.propertyPath);
  20613. this._property = this._getProperty(this.propertyPath);
  20614. }
  20615. Object.defineProperty(ValueCondition, "IsEqual", {
  20616. get: function () {
  20617. return ValueCondition._IsEqual;
  20618. },
  20619. enumerable: true,
  20620. configurable: true
  20621. });
  20622. Object.defineProperty(ValueCondition, "IsDifferent", {
  20623. get: function () {
  20624. return ValueCondition._IsDifferent;
  20625. },
  20626. enumerable: true,
  20627. configurable: true
  20628. });
  20629. Object.defineProperty(ValueCondition, "IsGreater", {
  20630. get: function () {
  20631. return ValueCondition._IsGreater;
  20632. },
  20633. enumerable: true,
  20634. configurable: true
  20635. });
  20636. Object.defineProperty(ValueCondition, "IsLesser", {
  20637. get: function () {
  20638. return ValueCondition._IsLesser;
  20639. },
  20640. enumerable: true,
  20641. configurable: true
  20642. });
  20643. ValueCondition.prototype.isValid = function () {
  20644. switch (this.operator) {
  20645. case ValueCondition.IsGreater:
  20646. return this._target[this._property] > this.value;
  20647. case ValueCondition.IsLesser:
  20648. return this._target[this._property] < this.value;
  20649. case ValueCondition.IsEqual:
  20650. case ValueCondition.IsDifferent:
  20651. var check;
  20652. if (this.value.equals) {
  20653. check = this.value.equals(this._target[this._property]);
  20654. } else {
  20655. check = this.value === this._target[this._property];
  20656. }
  20657. return this.operator === ValueCondition.IsEqual ? check : !check;
  20658. }
  20659. return false;
  20660. };
  20661. ValueCondition._IsEqual = 0;
  20662. ValueCondition._IsDifferent = 1;
  20663. ValueCondition._IsGreater = 2;
  20664. ValueCondition._IsLesser = 3;
  20665. return ValueCondition;
  20666. })(Condition);
  20667. BABYLON.ValueCondition = ValueCondition;
  20668. var PredicateCondition = (function (_super) {
  20669. __extends(PredicateCondition, _super);
  20670. function PredicateCondition(actionManager, predicate) {
  20671. _super.call(this, actionManager);
  20672. this.predicate = predicate;
  20673. }
  20674. PredicateCondition.prototype.isValid = function () {
  20675. return this.predicate();
  20676. };
  20677. return PredicateCondition;
  20678. })(Condition);
  20679. BABYLON.PredicateCondition = PredicateCondition;
  20680. var StateCondition = (function (_super) {
  20681. __extends(StateCondition, _super);
  20682. function StateCondition(actionManager, target, value) {
  20683. _super.call(this, actionManager);
  20684. this.value = value;
  20685. this._target = target;
  20686. }
  20687. StateCondition.prototype.isValid = function () {
  20688. return this._target.state === this.value;
  20689. };
  20690. return StateCondition;
  20691. })(Condition);
  20692. BABYLON.StateCondition = StateCondition;
  20693. })(BABYLON || (BABYLON = {}));
  20694. var BABYLON;
  20695. (function (BABYLON) {
  20696. var Action = (function () {
  20697. function Action(triggerOptions, condition) {
  20698. this.triggerOptions = triggerOptions;
  20699. if (triggerOptions.parameter) {
  20700. this.trigger = triggerOptions.trigger;
  20701. this._triggerParameter = triggerOptions.parameter;
  20702. } else {
  20703. this.trigger = triggerOptions;
  20704. }
  20705. this._nextActiveAction = this;
  20706. this._condition = condition;
  20707. }
  20708. Action.prototype._prepare = function () {
  20709. };
  20710. Action.prototype.getTriggerParameter = function () {
  20711. return this._triggerParameter;
  20712. };
  20713. Action.prototype._executeCurrent = function (evt) {
  20714. if (this._condition) {
  20715. var currentRenderId = this._actionManager.getScene().getRenderId();
  20716. if (this._condition._evaluationId === currentRenderId) {
  20717. if (!this._condition._currentResult) {
  20718. return;
  20719. }
  20720. } else {
  20721. this._condition._evaluationId = currentRenderId;
  20722. if (!this._condition.isValid()) {
  20723. this._condition._currentResult = false;
  20724. return;
  20725. }
  20726. this._condition._currentResult = true;
  20727. }
  20728. }
  20729. this._nextActiveAction.execute(evt);
  20730. if (this._nextActiveAction._child) {
  20731. if (!this._nextActiveAction._child._actionManager) {
  20732. this._nextActiveAction._child._actionManager = this._actionManager;
  20733. }
  20734. this._nextActiveAction = this._nextActiveAction._child;
  20735. } else {
  20736. this._nextActiveAction = this;
  20737. }
  20738. };
  20739. Action.prototype.execute = function (evt) {
  20740. };
  20741. Action.prototype.then = function (action) {
  20742. this._child = action;
  20743. action._actionManager = this._actionManager;
  20744. action._prepare();
  20745. return action;
  20746. };
  20747. Action.prototype._getProperty = function (propertyPath) {
  20748. return this._actionManager._getProperty(propertyPath);
  20749. };
  20750. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  20751. return this._actionManager._getEffectiveTarget(target, propertyPath);
  20752. };
  20753. return Action;
  20754. })();
  20755. BABYLON.Action = Action;
  20756. })(BABYLON || (BABYLON = {}));
  20757. var BABYLON;
  20758. (function (BABYLON) {
  20759. var ActionEvent = (function () {
  20760. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  20761. this.source = source;
  20762. this.pointerX = pointerX;
  20763. this.pointerY = pointerY;
  20764. this.meshUnderPointer = meshUnderPointer;
  20765. this.sourceEvent = sourceEvent;
  20766. }
  20767. ActionEvent.CreateNew = function (source, evt) {
  20768. var scene = source.getScene();
  20769. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  20770. };
  20771. ActionEvent.CreateNewFromScene = function (scene, evt) {
  20772. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  20773. };
  20774. return ActionEvent;
  20775. })();
  20776. BABYLON.ActionEvent = ActionEvent;
  20777. var ActionManager = (function () {
  20778. function ActionManager(scene) {
  20779. this.actions = new Array();
  20780. this._scene = scene;
  20781. scene._actionManagers.push(this);
  20782. }
  20783. Object.defineProperty(ActionManager, "NothingTrigger", {
  20784. get: function () {
  20785. return ActionManager._NothingTrigger;
  20786. },
  20787. enumerable: true,
  20788. configurable: true
  20789. });
  20790. Object.defineProperty(ActionManager, "OnPickTrigger", {
  20791. get: function () {
  20792. return ActionManager._OnPickTrigger;
  20793. },
  20794. enumerable: true,
  20795. configurable: true
  20796. });
  20797. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  20798. get: function () {
  20799. return ActionManager._OnLeftPickTrigger;
  20800. },
  20801. enumerable: true,
  20802. configurable: true
  20803. });
  20804. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  20805. get: function () {
  20806. return ActionManager._OnRightPickTrigger;
  20807. },
  20808. enumerable: true,
  20809. configurable: true
  20810. });
  20811. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  20812. get: function () {
  20813. return ActionManager._OnCenterPickTrigger;
  20814. },
  20815. enumerable: true,
  20816. configurable: true
  20817. });
  20818. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  20819. get: function () {
  20820. return ActionManager._OnPointerOverTrigger;
  20821. },
  20822. enumerable: true,
  20823. configurable: true
  20824. });
  20825. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  20826. get: function () {
  20827. return ActionManager._OnPointerOutTrigger;
  20828. },
  20829. enumerable: true,
  20830. configurable: true
  20831. });
  20832. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  20833. get: function () {
  20834. return ActionManager._OnEveryFrameTrigger;
  20835. },
  20836. enumerable: true,
  20837. configurable: true
  20838. });
  20839. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  20840. get: function () {
  20841. return ActionManager._OnIntersectionEnterTrigger;
  20842. },
  20843. enumerable: true,
  20844. configurable: true
  20845. });
  20846. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  20847. get: function () {
  20848. return ActionManager._OnIntersectionExitTrigger;
  20849. },
  20850. enumerable: true,
  20851. configurable: true
  20852. });
  20853. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  20854. get: function () {
  20855. return ActionManager._OnKeyDownTrigger;
  20856. },
  20857. enumerable: true,
  20858. configurable: true
  20859. });
  20860. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  20861. get: function () {
  20862. return ActionManager._OnKeyUpTrigger;
  20863. },
  20864. enumerable: true,
  20865. configurable: true
  20866. });
  20867. ActionManager.prototype.dispose = function () {
  20868. var index = this._scene._actionManagers.indexOf(this);
  20869. if (index > -1) {
  20870. this._scene._actionManagers.splice(index, 1);
  20871. }
  20872. };
  20873. ActionManager.prototype.getScene = function () {
  20874. return this._scene;
  20875. };
  20876. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  20877. for (var index = 0; index < this.actions.length; index++) {
  20878. var action = this.actions[index];
  20879. if (triggers.indexOf(action.trigger) > -1) {
  20880. return true;
  20881. }
  20882. }
  20883. return false;
  20884. };
  20885. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  20886. get: function () {
  20887. for (var index = 0; index < this.actions.length; index++) {
  20888. var action = this.actions[index];
  20889. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  20890. return true;
  20891. }
  20892. }
  20893. return false;
  20894. },
  20895. enumerable: true,
  20896. configurable: true
  20897. });
  20898. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  20899. get: function () {
  20900. for (var index = 0; index < this.actions.length; index++) {
  20901. var action = this.actions[index];
  20902. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  20903. return true;
  20904. }
  20905. }
  20906. return false;
  20907. },
  20908. enumerable: true,
  20909. configurable: true
  20910. });
  20911. ActionManager.prototype.registerAction = function (action) {
  20912. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  20913. if (this.getScene().actionManager !== this) {
  20914. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  20915. return null;
  20916. }
  20917. }
  20918. this.actions.push(action);
  20919. action._actionManager = this;
  20920. action._prepare();
  20921. return action;
  20922. };
  20923. ActionManager.prototype.processTrigger = function (trigger, evt) {
  20924. for (var index = 0; index < this.actions.length; index++) {
  20925. var action = this.actions[index];
  20926. if (action.trigger === trigger) {
  20927. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  20928. var parameter = action.getTriggerParameter();
  20929. if (parameter) {
  20930. if (evt.sourceEvent.key !== parameter) {
  20931. continue;
  20932. }
  20933. }
  20934. }
  20935. action._executeCurrent(evt);
  20936. }
  20937. }
  20938. };
  20939. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  20940. var properties = propertyPath.split(".");
  20941. for (var index = 0; index < properties.length - 1; index++) {
  20942. target = target[properties[index]];
  20943. }
  20944. return target;
  20945. };
  20946. ActionManager.prototype._getProperty = function (propertyPath) {
  20947. var properties = propertyPath.split(".");
  20948. return properties[properties.length - 1];
  20949. };
  20950. ActionManager._NothingTrigger = 0;
  20951. ActionManager._OnPickTrigger = 1;
  20952. ActionManager._OnLeftPickTrigger = 2;
  20953. ActionManager._OnRightPickTrigger = 3;
  20954. ActionManager._OnCenterPickTrigger = 4;
  20955. ActionManager._OnPointerOverTrigger = 5;
  20956. ActionManager._OnPointerOutTrigger = 6;
  20957. ActionManager._OnEveryFrameTrigger = 7;
  20958. ActionManager._OnIntersectionEnterTrigger = 8;
  20959. ActionManager._OnIntersectionExitTrigger = 9;
  20960. ActionManager._OnKeyDownTrigger = 10;
  20961. ActionManager._OnKeyUpTrigger = 11;
  20962. return ActionManager;
  20963. })();
  20964. BABYLON.ActionManager = ActionManager;
  20965. })(BABYLON || (BABYLON = {}));
  20966. var __extends = this.__extends || function (d, b) {
  20967. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20968. function __() { this.constructor = d; }
  20969. __.prototype = b.prototype;
  20970. d.prototype = new __();
  20971. };
  20972. var BABYLON;
  20973. (function (BABYLON) {
  20974. var InterpolateValueAction = (function (_super) {
  20975. __extends(InterpolateValueAction, _super);
  20976. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  20977. if (typeof duration === "undefined") { duration = 1000; }
  20978. _super.call(this, triggerOptions, condition);
  20979. this.propertyPath = propertyPath;
  20980. this.value = value;
  20981. this.duration = duration;
  20982. this.stopOtherAnimations = stopOtherAnimations;
  20983. this._target = target;
  20984. }
  20985. InterpolateValueAction.prototype._prepare = function () {
  20986. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  20987. this._property = this._getProperty(this.propertyPath);
  20988. };
  20989. InterpolateValueAction.prototype.execute = function () {
  20990. var scene = this._actionManager.getScene();
  20991. var keys = [
  20992. {
  20993. frame: 0,
  20994. value: this._target[this._property]
  20995. }, {
  20996. frame: 100,
  20997. value: this.value
  20998. }
  20999. ];
  21000. var dataType;
  21001. if (typeof this.value === "number") {
  21002. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  21003. } else if (this.value instanceof BABYLON.Color3) {
  21004. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  21005. } else if (this.value instanceof BABYLON.Vector3) {
  21006. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  21007. } else if (this.value instanceof BABYLON.Matrix) {
  21008. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  21009. } else if (this.value instanceof BABYLON.Quaternion) {
  21010. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  21011. } else {
  21012. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  21013. return;
  21014. }
  21015. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  21016. animation.setKeys(keys);
  21017. if (this.stopOtherAnimations) {
  21018. scene.stopAnimation(this._target);
  21019. }
  21020. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  21021. };
  21022. return InterpolateValueAction;
  21023. })(BABYLON.Action);
  21024. BABYLON.InterpolateValueAction = InterpolateValueAction;
  21025. })(BABYLON || (BABYLON = {}));
  21026. var __extends = this.__extends || function (d, b) {
  21027. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21028. function __() { this.constructor = d; }
  21029. __.prototype = b.prototype;
  21030. d.prototype = new __();
  21031. };
  21032. var BABYLON;
  21033. (function (BABYLON) {
  21034. var SwitchBooleanAction = (function (_super) {
  21035. __extends(SwitchBooleanAction, _super);
  21036. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  21037. _super.call(this, triggerOptions, condition);
  21038. this.propertyPath = propertyPath;
  21039. this._target = target;
  21040. }
  21041. SwitchBooleanAction.prototype._prepare = function () {
  21042. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  21043. this._property = this._getProperty(this.propertyPath);
  21044. };
  21045. SwitchBooleanAction.prototype.execute = function () {
  21046. this._target[this._property] = !this._target[this._property];
  21047. };
  21048. return SwitchBooleanAction;
  21049. })(BABYLON.Action);
  21050. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  21051. var SetStateAction = (function (_super) {
  21052. __extends(SetStateAction, _super);
  21053. function SetStateAction(triggerOptions, target, value, condition) {
  21054. _super.call(this, triggerOptions, condition);
  21055. this.value = value;
  21056. this._target = target;
  21057. }
  21058. SetStateAction.prototype.execute = function () {
  21059. this._target.state = this.value;
  21060. };
  21061. return SetStateAction;
  21062. })(BABYLON.Action);
  21063. BABYLON.SetStateAction = SetStateAction;
  21064. var SetValueAction = (function (_super) {
  21065. __extends(SetValueAction, _super);
  21066. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  21067. _super.call(this, triggerOptions, condition);
  21068. this.propertyPath = propertyPath;
  21069. this.value = value;
  21070. this._target = target;
  21071. }
  21072. SetValueAction.prototype._prepare = function () {
  21073. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  21074. this._property = this._getProperty(this.propertyPath);
  21075. };
  21076. SetValueAction.prototype.execute = function () {
  21077. this._target[this._property] = this.value;
  21078. };
  21079. return SetValueAction;
  21080. })(BABYLON.Action);
  21081. BABYLON.SetValueAction = SetValueAction;
  21082. var IncrementValueAction = (function (_super) {
  21083. __extends(IncrementValueAction, _super);
  21084. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  21085. _super.call(this, triggerOptions, condition);
  21086. this.propertyPath = propertyPath;
  21087. this.value = value;
  21088. this._target = target;
  21089. }
  21090. IncrementValueAction.prototype._prepare = function () {
  21091. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  21092. this._property = this._getProperty(this.propertyPath);
  21093. if (typeof this._target[this._property] !== "number") {
  21094. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  21095. }
  21096. };
  21097. IncrementValueAction.prototype.execute = function () {
  21098. this._target[this._property] += this.value;
  21099. };
  21100. return IncrementValueAction;
  21101. })(BABYLON.Action);
  21102. BABYLON.IncrementValueAction = IncrementValueAction;
  21103. var PlayAnimationAction = (function (_super) {
  21104. __extends(PlayAnimationAction, _super);
  21105. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  21106. _super.call(this, triggerOptions, condition);
  21107. this.from = from;
  21108. this.to = to;
  21109. this.loop = loop;
  21110. this._target = target;
  21111. }
  21112. PlayAnimationAction.prototype._prepare = function () {
  21113. };
  21114. PlayAnimationAction.prototype.execute = function () {
  21115. var scene = this._actionManager.getScene();
  21116. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  21117. };
  21118. return PlayAnimationAction;
  21119. })(BABYLON.Action);
  21120. BABYLON.PlayAnimationAction = PlayAnimationAction;
  21121. var StopAnimationAction = (function (_super) {
  21122. __extends(StopAnimationAction, _super);
  21123. function StopAnimationAction(triggerOptions, target, condition) {
  21124. _super.call(this, triggerOptions, condition);
  21125. this._target = target;
  21126. }
  21127. StopAnimationAction.prototype._prepare = function () {
  21128. };
  21129. StopAnimationAction.prototype.execute = function () {
  21130. var scene = this._actionManager.getScene();
  21131. scene.stopAnimation(this._target);
  21132. };
  21133. return StopAnimationAction;
  21134. })(BABYLON.Action);
  21135. BABYLON.StopAnimationAction = StopAnimationAction;
  21136. var DoNothingAction = (function (_super) {
  21137. __extends(DoNothingAction, _super);
  21138. function DoNothingAction(triggerOptions, condition) {
  21139. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  21140. _super.call(this, triggerOptions, condition);
  21141. }
  21142. DoNothingAction.prototype.execute = function () {
  21143. };
  21144. return DoNothingAction;
  21145. })(BABYLON.Action);
  21146. BABYLON.DoNothingAction = DoNothingAction;
  21147. var CombineAction = (function (_super) {
  21148. __extends(CombineAction, _super);
  21149. function CombineAction(triggerOptions, children, condition) {
  21150. _super.call(this, triggerOptions, condition);
  21151. this.children = children;
  21152. }
  21153. CombineAction.prototype._prepare = function () {
  21154. for (var index = 0; index < this.children.length; index++) {
  21155. this.children[index]._actionManager = this._actionManager;
  21156. this.children[index]._prepare();
  21157. }
  21158. };
  21159. CombineAction.prototype.execute = function (evt) {
  21160. for (var index = 0; index < this.children.length; index++) {
  21161. this.children[index].execute(evt);
  21162. }
  21163. };
  21164. return CombineAction;
  21165. })(BABYLON.Action);
  21166. BABYLON.CombineAction = CombineAction;
  21167. var ExecuteCodeAction = (function (_super) {
  21168. __extends(ExecuteCodeAction, _super);
  21169. function ExecuteCodeAction(triggerOptions, func, condition) {
  21170. _super.call(this, triggerOptions, condition);
  21171. this.func = func;
  21172. }
  21173. ExecuteCodeAction.prototype.execute = function (evt) {
  21174. this.func(evt);
  21175. };
  21176. return ExecuteCodeAction;
  21177. })(BABYLON.Action);
  21178. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  21179. var SetParentAction = (function (_super) {
  21180. __extends(SetParentAction, _super);
  21181. function SetParentAction(triggerOptions, target, parent, condition) {
  21182. _super.call(this, triggerOptions, condition);
  21183. this._target = target;
  21184. this._parent = parent;
  21185. }
  21186. SetParentAction.prototype._prepare = function () {
  21187. };
  21188. SetParentAction.prototype.execute = function () {
  21189. if (this._target.parent === this._parent) {
  21190. return;
  21191. }
  21192. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  21193. invertParentWorldMatrix.invert();
  21194. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  21195. this._target.parent = this._parent;
  21196. };
  21197. return SetParentAction;
  21198. })(BABYLON.Action);
  21199. BABYLON.SetParentAction = SetParentAction;
  21200. })(BABYLON || (BABYLON = {}));
  21201. var __extends = this.__extends || function (d, b) {
  21202. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21203. function __() { this.constructor = d; }
  21204. __.prototype = b.prototype;
  21205. d.prototype = new __();
  21206. };
  21207. var BABYLON;
  21208. (function (BABYLON) {
  21209. var Geometry = (function () {
  21210. function Geometry(id, scene, vertexData, updatable, mesh) {
  21211. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21212. this._totalVertices = 0;
  21213. this._indices = [];
  21214. this.id = id;
  21215. this._engine = scene.getEngine();
  21216. this._meshes = [];
  21217. this._scene = scene;
  21218. if (vertexData) {
  21219. this.setAllVerticesData(vertexData, updatable);
  21220. } else {
  21221. this._totalVertices = 0;
  21222. this._indices = [];
  21223. }
  21224. if (mesh) {
  21225. this.applyToMesh(mesh);
  21226. }
  21227. }
  21228. Geometry.prototype.getScene = function () {
  21229. return this._scene;
  21230. };
  21231. Geometry.prototype.getEngine = function () {
  21232. return this._engine;
  21233. };
  21234. Geometry.prototype.isReady = function () {
  21235. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  21236. };
  21237. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  21238. vertexData.applyToGeometry(this, updatable);
  21239. };
  21240. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21241. this._vertexBuffers = this._vertexBuffers || {};
  21242. if (this._vertexBuffers[kind]) {
  21243. this._vertexBuffers[kind].dispose();
  21244. }
  21245. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  21246. if (kind === BABYLON.VertexBuffer.PositionKind) {
  21247. stride = this._vertexBuffers[kind].getStrideSize();
  21248. this._totalVertices = data.length / stride;
  21249. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  21250. var meshes = this._meshes;
  21251. var numOfMeshes = meshes.length;
  21252. for (var index = 0; index < numOfMeshes; index++) {
  21253. var mesh = meshes[index];
  21254. mesh._resetPointsArrayCache();
  21255. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21256. mesh._createGlobalSubMesh();
  21257. mesh.computeWorldMatrix(true);
  21258. }
  21259. }
  21260. };
  21261. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  21262. var vertexBuffer = this.getVertexBuffer(kind);
  21263. if (!vertexBuffer) {
  21264. return;
  21265. }
  21266. vertexBuffer.updateDirectly(data, offset);
  21267. };
  21268. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  21269. var vertexBuffer = this.getVertexBuffer(kind);
  21270. if (!vertexBuffer) {
  21271. return;
  21272. }
  21273. vertexBuffer.update(data);
  21274. if (kind === BABYLON.VertexBuffer.PositionKind) {
  21275. var extend;
  21276. var stride = vertexBuffer.getStrideSize();
  21277. this._totalVertices = data.length / stride;
  21278. if (updateExtends) {
  21279. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  21280. }
  21281. var meshes = this._meshes;
  21282. var numOfMeshes = meshes.length;
  21283. for (var index = 0; index < numOfMeshes; index++) {
  21284. var mesh = meshes[index];
  21285. mesh._resetPointsArrayCache();
  21286. if (updateExtends) {
  21287. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21288. }
  21289. }
  21290. }
  21291. };
  21292. Geometry.prototype.getTotalVertices = function () {
  21293. if (!this.isReady()) {
  21294. return 0;
  21295. }
  21296. return this._totalVertices;
  21297. };
  21298. Geometry.prototype.getVerticesData = function (kind) {
  21299. var vertexBuffer = this.getVertexBuffer(kind);
  21300. if (!vertexBuffer) {
  21301. return null;
  21302. }
  21303. return vertexBuffer.getData();
  21304. };
  21305. Geometry.prototype.getVertexBuffer = function (kind) {
  21306. if (!this.isReady()) {
  21307. return null;
  21308. }
  21309. return this._vertexBuffers[kind];
  21310. };
  21311. Geometry.prototype.getVertexBuffers = function () {
  21312. if (!this.isReady()) {
  21313. return null;
  21314. }
  21315. return this._vertexBuffers;
  21316. };
  21317. Geometry.prototype.isVerticesDataPresent = function (kind) {
  21318. if (!this._vertexBuffers) {
  21319. if (this._delayInfo) {
  21320. return this._delayInfo.indexOf(kind) !== -1;
  21321. }
  21322. return false;
  21323. }
  21324. return this._vertexBuffers[kind] !== undefined;
  21325. };
  21326. Geometry.prototype.getVerticesDataKinds = function () {
  21327. var result = [];
  21328. if (!this._vertexBuffers && this._delayInfo) {
  21329. for (var kind in this._delayInfo) {
  21330. result.push(kind);
  21331. }
  21332. } else {
  21333. for (kind in this._vertexBuffers) {
  21334. result.push(kind);
  21335. }
  21336. }
  21337. return result;
  21338. };
  21339. Geometry.prototype.setIndices = function (indices, totalVertices) {
  21340. if (this._indexBuffer) {
  21341. this._engine._releaseBuffer(this._indexBuffer);
  21342. }
  21343. this._indices = indices;
  21344. if (this._meshes.length !== 0 && this._indices) {
  21345. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  21346. }
  21347. if (totalVertices !== undefined) {
  21348. this._totalVertices = totalVertices;
  21349. }
  21350. var meshes = this._meshes;
  21351. var numOfMeshes = meshes.length;
  21352. for (var index = 0; index < numOfMeshes; index++) {
  21353. meshes[index]._createGlobalSubMesh();
  21354. }
  21355. };
  21356. Geometry.prototype.getTotalIndices = function () {
  21357. if (!this.isReady()) {
  21358. return 0;
  21359. }
  21360. return this._indices.length;
  21361. };
  21362. Geometry.prototype.getIndices = function () {
  21363. if (!this.isReady()) {
  21364. return null;
  21365. }
  21366. return this._indices;
  21367. };
  21368. Geometry.prototype.getIndexBuffer = function () {
  21369. if (!this.isReady()) {
  21370. return null;
  21371. }
  21372. return this._indexBuffer;
  21373. };
  21374. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  21375. var meshes = this._meshes;
  21376. var index = meshes.indexOf(mesh);
  21377. if (index === -1) {
  21378. return;
  21379. }
  21380. for (var kind in this._vertexBuffers) {
  21381. this._vertexBuffers[kind].dispose();
  21382. }
  21383. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  21384. this._indexBuffer = null;
  21385. }
  21386. meshes.splice(index, 1);
  21387. mesh._geometry = null;
  21388. if (meshes.length == 0 && shouldDispose) {
  21389. this.dispose();
  21390. }
  21391. };
  21392. Geometry.prototype.applyToMesh = function (mesh) {
  21393. if (mesh._geometry === this) {
  21394. return;
  21395. }
  21396. var previousGeometry = mesh._geometry;
  21397. if (previousGeometry) {
  21398. previousGeometry.releaseForMesh(mesh);
  21399. }
  21400. var meshes = this._meshes;
  21401. mesh._geometry = this;
  21402. this._scene.pushGeometry(this);
  21403. meshes.push(mesh);
  21404. if (this.isReady()) {
  21405. this._applyToMesh(mesh);
  21406. } else {
  21407. mesh._boundingInfo = this._boundingInfo;
  21408. }
  21409. };
  21410. Geometry.prototype._applyToMesh = function (mesh) {
  21411. var numOfMeshes = this._meshes.length;
  21412. for (var kind in this._vertexBuffers) {
  21413. if (numOfMeshes === 1) {
  21414. this._vertexBuffers[kind].create();
  21415. }
  21416. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  21417. if (kind === BABYLON.VertexBuffer.PositionKind) {
  21418. mesh._resetPointsArrayCache();
  21419. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  21420. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21421. mesh._createGlobalSubMesh();
  21422. }
  21423. }
  21424. if (numOfMeshes === 1 && this._indices) {
  21425. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  21426. }
  21427. if (this._indexBuffer) {
  21428. this._indexBuffer.references = numOfMeshes;
  21429. }
  21430. };
  21431. Geometry.prototype.load = function (scene, onLoaded) {
  21432. var _this = this;
  21433. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21434. return;
  21435. }
  21436. if (this.isReady()) {
  21437. if (onLoaded) {
  21438. onLoaded();
  21439. }
  21440. return;
  21441. }
  21442. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  21443. scene._addPendingData(this);
  21444. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  21445. _this._delayLoadingFunction(JSON.parse(data), _this);
  21446. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21447. _this._delayInfo = [];
  21448. scene._removePendingData(_this);
  21449. var meshes = _this._meshes;
  21450. var numOfMeshes = meshes.length;
  21451. for (var index = 0; index < numOfMeshes; index++) {
  21452. _this._applyToMesh(meshes[index]);
  21453. }
  21454. if (onLoaded) {
  21455. onLoaded();
  21456. }
  21457. }, function () {
  21458. }, scene.database);
  21459. };
  21460. Geometry.prototype.dispose = function () {
  21461. var meshes = this._meshes;
  21462. var numOfMeshes = meshes.length;
  21463. for (var index = 0; index < numOfMeshes; index++) {
  21464. this.releaseForMesh(meshes[index]);
  21465. }
  21466. this._meshes = [];
  21467. for (var kind in this._vertexBuffers) {
  21468. this._vertexBuffers[kind].dispose();
  21469. }
  21470. this._vertexBuffers = [];
  21471. this._totalVertices = 0;
  21472. if (this._indexBuffer) {
  21473. this._engine._releaseBuffer(this._indexBuffer);
  21474. }
  21475. this._indexBuffer = null;
  21476. this._indices = [];
  21477. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21478. this.delayLoadingFile = null;
  21479. this._delayLoadingFunction = null;
  21480. this._delayInfo = [];
  21481. this._boundingInfo = null;
  21482. var geometries = this._scene.getGeometries();
  21483. index = geometries.indexOf(this);
  21484. if (index > -1) {
  21485. geometries.splice(index, 1);
  21486. }
  21487. };
  21488. Geometry.prototype.copy = function (id) {
  21489. var vertexData = new BABYLON.VertexData();
  21490. vertexData.indices = [];
  21491. var indices = this.getIndices();
  21492. for (var index = 0; index < indices.length; index++) {
  21493. vertexData.indices.push(indices[index]);
  21494. }
  21495. var updatable = false;
  21496. var stopChecking = false;
  21497. for (var kind in this._vertexBuffers) {
  21498. vertexData.set(this.getVerticesData(kind), kind);
  21499. if (!stopChecking) {
  21500. updatable = this.getVertexBuffer(kind).isUpdatable();
  21501. stopChecking = !updatable;
  21502. }
  21503. }
  21504. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  21505. geometry.delayLoadState = this.delayLoadState;
  21506. geometry.delayLoadingFile = this.delayLoadingFile;
  21507. geometry._delayLoadingFunction = this._delayLoadingFunction;
  21508. for (kind in this._delayInfo) {
  21509. geometry._delayInfo = geometry._delayInfo || [];
  21510. geometry._delayInfo.push(kind);
  21511. }
  21512. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  21513. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21514. return geometry;
  21515. };
  21516. Geometry.ExtractFromMesh = function (mesh, id) {
  21517. var geometry = mesh._geometry;
  21518. if (!geometry) {
  21519. return null;
  21520. }
  21521. return geometry.copy(id);
  21522. };
  21523. Geometry.RandomId = function () {
  21524. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  21525. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  21526. return v.toString(16);
  21527. });
  21528. };
  21529. return Geometry;
  21530. })();
  21531. BABYLON.Geometry = Geometry;
  21532. (function (Geometry) {
  21533. (function (Primitives) {
  21534. var _Primitive = (function (_super) {
  21535. __extends(_Primitive, _super);
  21536. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  21537. this._beingRegenerated = true;
  21538. this._canBeRegenerated = canBeRegenerated;
  21539. _super.call(this, id, scene, vertexData, false, mesh);
  21540. this._beingRegenerated = false;
  21541. }
  21542. _Primitive.prototype.canBeRegenerated = function () {
  21543. return this._canBeRegenerated;
  21544. };
  21545. _Primitive.prototype.regenerate = function () {
  21546. if (!this._canBeRegenerated) {
  21547. return;
  21548. }
  21549. this._beingRegenerated = true;
  21550. this.setAllVerticesData(this._regenerateVertexData(), false);
  21551. this._beingRegenerated = false;
  21552. };
  21553. _Primitive.prototype.asNewGeometry = function (id) {
  21554. return _super.prototype.copy.call(this, id);
  21555. };
  21556. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  21557. if (!this._beingRegenerated) {
  21558. return;
  21559. }
  21560. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  21561. };
  21562. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  21563. if (!this._beingRegenerated) {
  21564. return;
  21565. }
  21566. _super.prototype.setVerticesData.call(this, kind, data, false);
  21567. };
  21568. _Primitive.prototype._regenerateVertexData = function () {
  21569. throw new Error("Abstract method");
  21570. };
  21571. _Primitive.prototype.copy = function (id) {
  21572. throw new Error("Must be overriden in sub-classes.");
  21573. };
  21574. return _Primitive;
  21575. })(Geometry);
  21576. Primitives._Primitive = _Primitive;
  21577. var Box = (function (_super) {
  21578. __extends(Box, _super);
  21579. function Box(id, scene, size, canBeRegenerated, mesh) {
  21580. this.size = size;
  21581. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21582. }
  21583. Box.prototype._regenerateVertexData = function () {
  21584. return BABYLON.VertexData.CreateBox(this.size);
  21585. };
  21586. Box.prototype.copy = function (id) {
  21587. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  21588. };
  21589. return Box;
  21590. })(_Primitive);
  21591. Primitives.Box = Box;
  21592. var Sphere = (function (_super) {
  21593. __extends(Sphere, _super);
  21594. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  21595. this.segments = segments;
  21596. this.diameter = diameter;
  21597. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21598. }
  21599. Sphere.prototype._regenerateVertexData = function () {
  21600. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  21601. };
  21602. Sphere.prototype.copy = function (id) {
  21603. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  21604. };
  21605. return Sphere;
  21606. })(_Primitive);
  21607. Primitives.Sphere = Sphere;
  21608. var Cylinder = (function (_super) {
  21609. __extends(Cylinder, _super);
  21610. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  21611. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  21612. this.height = height;
  21613. this.diameterTop = diameterTop;
  21614. this.diameterBottom = diameterBottom;
  21615. this.tessellation = tessellation;
  21616. this.subdivisions = subdivisions;
  21617. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21618. }
  21619. Cylinder.prototype._regenerateVertexData = function () {
  21620. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  21621. };
  21622. Cylinder.prototype.copy = function (id) {
  21623. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  21624. };
  21625. return Cylinder;
  21626. })(_Primitive);
  21627. Primitives.Cylinder = Cylinder;
  21628. var Torus = (function (_super) {
  21629. __extends(Torus, _super);
  21630. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  21631. this.diameter = diameter;
  21632. this.thickness = thickness;
  21633. this.tessellation = tessellation;
  21634. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21635. }
  21636. Torus.prototype._regenerateVertexData = function () {
  21637. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  21638. };
  21639. Torus.prototype.copy = function (id) {
  21640. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  21641. };
  21642. return Torus;
  21643. })(_Primitive);
  21644. Primitives.Torus = Torus;
  21645. var Ground = (function (_super) {
  21646. __extends(Ground, _super);
  21647. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  21648. this.width = width;
  21649. this.height = height;
  21650. this.subdivisions = subdivisions;
  21651. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21652. }
  21653. Ground.prototype._regenerateVertexData = function () {
  21654. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  21655. };
  21656. Ground.prototype.copy = function (id) {
  21657. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  21658. };
  21659. return Ground;
  21660. })(_Primitive);
  21661. Primitives.Ground = Ground;
  21662. var TiledGround = (function (_super) {
  21663. __extends(TiledGround, _super);
  21664. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  21665. this.xmin = xmin;
  21666. this.zmin = zmin;
  21667. this.xmax = xmax;
  21668. this.zmax = zmax;
  21669. this.subdivisions = subdivisions;
  21670. this.precision = precision;
  21671. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21672. }
  21673. TiledGround.prototype._regenerateVertexData = function () {
  21674. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  21675. };
  21676. TiledGround.prototype.copy = function (id) {
  21677. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  21678. };
  21679. return TiledGround;
  21680. })(_Primitive);
  21681. Primitives.TiledGround = TiledGround;
  21682. var Plane = (function (_super) {
  21683. __extends(Plane, _super);
  21684. function Plane(id, scene, size, canBeRegenerated, mesh) {
  21685. this.size = size;
  21686. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21687. }
  21688. Plane.prototype._regenerateVertexData = function () {
  21689. return BABYLON.VertexData.CreatePlane(this.size);
  21690. };
  21691. Plane.prototype.copy = function (id) {
  21692. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  21693. };
  21694. return Plane;
  21695. })(_Primitive);
  21696. Primitives.Plane = Plane;
  21697. var TorusKnot = (function (_super) {
  21698. __extends(TorusKnot, _super);
  21699. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  21700. this.radius = radius;
  21701. this.tube = tube;
  21702. this.radialSegments = radialSegments;
  21703. this.tubularSegments = tubularSegments;
  21704. this.p = p;
  21705. this.q = q;
  21706. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21707. }
  21708. TorusKnot.prototype._regenerateVertexData = function () {
  21709. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  21710. };
  21711. TorusKnot.prototype.copy = function (id) {
  21712. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  21713. };
  21714. return TorusKnot;
  21715. })(_Primitive);
  21716. Primitives.TorusKnot = TorusKnot;
  21717. })(Geometry.Primitives || (Geometry.Primitives = {}));
  21718. var Primitives = Geometry.Primitives;
  21719. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  21720. var Geometry = BABYLON.Geometry;
  21721. })(BABYLON || (BABYLON = {}));
  21722. var __extends = this.__extends || function (d, b) {
  21723. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21724. function __() { this.constructor = d; }
  21725. __.prototype = b.prototype;
  21726. d.prototype = new __();
  21727. };
  21728. var BABYLON;
  21729. (function (BABYLON) {
  21730. var Gamepads = (function () {
  21731. function Gamepads(ongamedpadconnected) {
  21732. var _this = this;
  21733. this.babylonGamepads = [];
  21734. this.oneGamepadConnected = false;
  21735. this.isMonitoring = false;
  21736. this.gamepadEventSupported = 'GamepadEvent' in window;
  21737. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  21738. 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=";
  21739. this._callbackGamepadConnected = ongamedpadconnected;
  21740. if (this.gamepadSupportAvailable) {
  21741. if (this.gamepadEventSupported) {
  21742. window.addEventListener('gamepadconnected', function (evt) {
  21743. _this._onGamepadConnected(evt);
  21744. }, false);
  21745. window.addEventListener('gamepaddisconnected', function (evt) {
  21746. _this._onGamepadDisconnected(evt);
  21747. }, false);
  21748. } else {
  21749. this._startMonitoringGamepads();
  21750. }
  21751. if (!this.oneGamepadConnected) {
  21752. this._insertGamepadDOMInstructions();
  21753. }
  21754. } else {
  21755. this._insertGamepadDOMNotSupported();
  21756. }
  21757. }
  21758. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  21759. Gamepads.gamepadDOMInfo = document.createElement("div");
  21760. var buttonAImage = document.createElement("img");
  21761. buttonAImage.src = this.buttonADataURL;
  21762. var spanMessage = document.createElement("span");
  21763. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  21764. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  21765. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  21766. Gamepads.gamepadDOMInfo.style.position = "absolute";
  21767. Gamepads.gamepadDOMInfo.style.width = "100%";
  21768. Gamepads.gamepadDOMInfo.style.height = "48px";
  21769. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  21770. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  21771. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  21772. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  21773. buttonAImage.style.position = "relative";
  21774. buttonAImage.style.bottom = "8px";
  21775. spanMessage.style.position = "relative";
  21776. spanMessage.style.fontSize = "32px";
  21777. spanMessage.style.bottom = "32px";
  21778. spanMessage.style.color = "green";
  21779. document.body.appendChild(Gamepads.gamepadDOMInfo);
  21780. };
  21781. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  21782. Gamepads.gamepadDOMInfo = document.createElement("div");
  21783. var spanMessage = document.createElement("span");
  21784. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  21785. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  21786. Gamepads.gamepadDOMInfo.style.position = "absolute";
  21787. Gamepads.gamepadDOMInfo.style.width = "100%";
  21788. Gamepads.gamepadDOMInfo.style.height = "40px";
  21789. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  21790. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  21791. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  21792. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  21793. spanMessage.style.position = "relative";
  21794. spanMessage.style.fontSize = "32px";
  21795. spanMessage.style.color = "red";
  21796. document.body.appendChild(Gamepads.gamepadDOMInfo);
  21797. };
  21798. Gamepads.prototype.dispose = function () {
  21799. document.body.removeChild(Gamepads.gamepadDOMInfo);
  21800. };
  21801. Gamepads.prototype._onGamepadConnected = function (evt) {
  21802. var newGamepad = this._addNewGamepad(evt.gamepad);
  21803. if (this._callbackGamepadConnected)
  21804. this._callbackGamepadConnected(newGamepad);
  21805. this._startMonitoringGamepads();
  21806. };
  21807. Gamepads.prototype._addNewGamepad = function (gamepad) {
  21808. if (!this.oneGamepadConnected) {
  21809. this.oneGamepadConnected = true;
  21810. if (Gamepads.gamepadDOMInfo) {
  21811. document.body.removeChild(Gamepads.gamepadDOMInfo);
  21812. Gamepads.gamepadDOMInfo = null;
  21813. }
  21814. }
  21815. var newGamepad;
  21816. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  21817. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  21818. } else {
  21819. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  21820. }
  21821. this.babylonGamepads.push(newGamepad);
  21822. return newGamepad;
  21823. };
  21824. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  21825. for (var i in this.babylonGamepads) {
  21826. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  21827. this.babylonGamepads.splice(i, 1);
  21828. break;
  21829. }
  21830. }
  21831. if (this.babylonGamepads.length == 0) {
  21832. this._stopMonitoringGamepads();
  21833. }
  21834. };
  21835. Gamepads.prototype._startMonitoringGamepads = function () {
  21836. if (!this.isMonitoring) {
  21837. this.isMonitoring = true;
  21838. this._checkGamepadsStatus();
  21839. }
  21840. };
  21841. Gamepads.prototype._stopMonitoringGamepads = function () {
  21842. this.isMonitoring = false;
  21843. };
  21844. Gamepads.prototype._checkGamepadsStatus = function () {
  21845. var _this = this;
  21846. this._updateGamepadObjects();
  21847. for (var i in this.babylonGamepads) {
  21848. this.babylonGamepads[i].update();
  21849. }
  21850. if (this.isMonitoring) {
  21851. if (window.requestAnimationFrame) {
  21852. window.requestAnimationFrame(function () {
  21853. _this._checkGamepadsStatus();
  21854. });
  21855. } else if (window.mozRequestAnimationFrame) {
  21856. window.mozRequestAnimationFrame(function () {
  21857. _this._checkGamepadsStatus();
  21858. });
  21859. } else if (window.webkitRequestAnimationFrame) {
  21860. window.webkitRequestAnimationFrame(function () {
  21861. _this._checkGamepadsStatus();
  21862. });
  21863. }
  21864. }
  21865. };
  21866. Gamepads.prototype._updateGamepadObjects = function () {
  21867. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  21868. for (var i = 0; i < gamepads.length; i++) {
  21869. if (gamepads[i]) {
  21870. if (!(gamepads[i].index in this.babylonGamepads)) {
  21871. var newGamepad = this._addNewGamepad(gamepads[i]);
  21872. if (this._callbackGamepadConnected) {
  21873. this._callbackGamepadConnected(newGamepad);
  21874. }
  21875. } else {
  21876. this.babylonGamepads[i].browserGamepad = gamepads[i];
  21877. }
  21878. }
  21879. }
  21880. };
  21881. return Gamepads;
  21882. })();
  21883. BABYLON.Gamepads = Gamepads;
  21884. var StickValues = (function () {
  21885. function StickValues(x, y) {
  21886. this.x = x;
  21887. this.y = y;
  21888. }
  21889. return StickValues;
  21890. })();
  21891. BABYLON.StickValues = StickValues;
  21892. var Gamepad = (function () {
  21893. function Gamepad(id, index, browserGamepad) {
  21894. this.id = id;
  21895. this.index = index;
  21896. this.browserGamepad = browserGamepad;
  21897. if (this.browserGamepad.axes.length >= 2) {
  21898. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  21899. }
  21900. if (this.browserGamepad.axes.length >= 4) {
  21901. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  21902. }
  21903. }
  21904. Gamepad.prototype.onleftstickchanged = function (callback) {
  21905. this._onleftstickchanged = callback;
  21906. };
  21907. Gamepad.prototype.onrightstickchanged = function (callback) {
  21908. this._onrightstickchanged = callback;
  21909. };
  21910. Object.defineProperty(Gamepad.prototype, "leftStick", {
  21911. get: function () {
  21912. return this._leftStick;
  21913. },
  21914. set: function (newValues) {
  21915. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  21916. this._onleftstickchanged(newValues);
  21917. }
  21918. this._leftStick = newValues;
  21919. },
  21920. enumerable: true,
  21921. configurable: true
  21922. });
  21923. Object.defineProperty(Gamepad.prototype, "rightStick", {
  21924. get: function () {
  21925. return this._rightStick;
  21926. },
  21927. set: function (newValues) {
  21928. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  21929. this._onrightstickchanged(newValues);
  21930. }
  21931. this._rightStick = newValues;
  21932. },
  21933. enumerable: true,
  21934. configurable: true
  21935. });
  21936. Gamepad.prototype.update = function () {
  21937. if (this._leftStick) {
  21938. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  21939. }
  21940. if (this._rightStick) {
  21941. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  21942. }
  21943. };
  21944. return Gamepad;
  21945. })();
  21946. BABYLON.Gamepad = Gamepad;
  21947. var GenericPad = (function (_super) {
  21948. __extends(GenericPad, _super);
  21949. function GenericPad(id, index, gamepad) {
  21950. _super.call(this, id, index, gamepad);
  21951. this.id = id;
  21952. this.index = index;
  21953. this.gamepad = gamepad;
  21954. this._buttons = new Array(gamepad.buttons.length);
  21955. }
  21956. GenericPad.prototype.onbuttondown = function (callback) {
  21957. this._onbuttondown = callback;
  21958. };
  21959. GenericPad.prototype.onbuttonup = function (callback) {
  21960. this._onbuttonup = callback;
  21961. };
  21962. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  21963. if (newValue !== currentValue) {
  21964. if (this._onbuttondown && newValue === 1) {
  21965. this._onbuttondown(buttonIndex);
  21966. }
  21967. if (this._onbuttonup && newValue === 0) {
  21968. this._onbuttonup(buttonIndex);
  21969. }
  21970. }
  21971. return newValue;
  21972. };
  21973. GenericPad.prototype.update = function () {
  21974. _super.prototype.update.call(this);
  21975. for (var index = 0; index < this._buttons.length; index++) {
  21976. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  21977. }
  21978. };
  21979. return GenericPad;
  21980. })(Gamepad);
  21981. BABYLON.GenericPad = GenericPad;
  21982. (function (Xbox360Button) {
  21983. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  21984. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  21985. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  21986. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  21987. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  21988. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  21989. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  21990. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  21991. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  21992. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  21993. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  21994. var Xbox360Button = BABYLON.Xbox360Button;
  21995. (function (Xbox360Dpad) {
  21996. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  21997. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  21998. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  21999. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  22000. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  22001. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  22002. var Xbox360Pad = (function (_super) {
  22003. __extends(Xbox360Pad, _super);
  22004. function Xbox360Pad() {
  22005. _super.apply(this, arguments);
  22006. this._leftTrigger = 0;
  22007. this._rightTrigger = 0;
  22008. this._buttonA = 0;
  22009. this._buttonB = 0;
  22010. this._buttonX = 0;
  22011. this._buttonY = 0;
  22012. this._buttonBack = 0;
  22013. this._buttonStart = 0;
  22014. this._buttonLB = 0;
  22015. this._buttonRB = 0;
  22016. this._buttonLeftStick = 0;
  22017. this._buttonRightStick = 0;
  22018. this._dPadUp = 0;
  22019. this._dPadDown = 0;
  22020. this._dPadLeft = 0;
  22021. this._dPadRight = 0;
  22022. }
  22023. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  22024. this._onlefttriggerchanged = callback;
  22025. };
  22026. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  22027. this._onrighttriggerchanged = callback;
  22028. };
  22029. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  22030. get: function () {
  22031. return this._leftTrigger;
  22032. },
  22033. set: function (newValue) {
  22034. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  22035. this._onlefttriggerchanged(newValue);
  22036. }
  22037. this._leftTrigger = newValue;
  22038. },
  22039. enumerable: true,
  22040. configurable: true
  22041. });
  22042. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  22043. get: function () {
  22044. return this._rightTrigger;
  22045. },
  22046. set: function (newValue) {
  22047. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  22048. this._onrighttriggerchanged(newValue);
  22049. }
  22050. this._rightTrigger = newValue;
  22051. },
  22052. enumerable: true,
  22053. configurable: true
  22054. });
  22055. Xbox360Pad.prototype.onbuttondown = function (callback) {
  22056. this._onbuttondown = callback;
  22057. };
  22058. Xbox360Pad.prototype.onbuttonup = function (callback) {
  22059. this._onbuttonup = callback;
  22060. };
  22061. Xbox360Pad.prototype.ondpaddown = function (callback) {
  22062. this._ondpaddown = callback;
  22063. };
  22064. Xbox360Pad.prototype.ondpadup = function (callback) {
  22065. this._ondpadup = callback;
  22066. };
  22067. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  22068. if (newValue !== currentValue) {
  22069. if (this._onbuttondown && newValue === 1) {
  22070. this._onbuttondown(buttonType);
  22071. }
  22072. if (this._onbuttonup && newValue === 0) {
  22073. this._onbuttonup(buttonType);
  22074. }
  22075. }
  22076. return newValue;
  22077. };
  22078. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  22079. if (newValue !== currentValue) {
  22080. if (this._ondpaddown && newValue === 1) {
  22081. this._ondpaddown(buttonType);
  22082. }
  22083. if (this._ondpadup && newValue === 0) {
  22084. this._ondpadup(buttonType);
  22085. }
  22086. }
  22087. return newValue;
  22088. };
  22089. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  22090. get: function () {
  22091. return this._buttonA;
  22092. },
  22093. set: function (value) {
  22094. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  22095. },
  22096. enumerable: true,
  22097. configurable: true
  22098. });
  22099. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  22100. get: function () {
  22101. return this._buttonB;
  22102. },
  22103. set: function (value) {
  22104. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  22105. },
  22106. enumerable: true,
  22107. configurable: true
  22108. });
  22109. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  22110. get: function () {
  22111. return this._buttonX;
  22112. },
  22113. set: function (value) {
  22114. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  22115. },
  22116. enumerable: true,
  22117. configurable: true
  22118. });
  22119. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  22120. get: function () {
  22121. return this._buttonY;
  22122. },
  22123. set: function (value) {
  22124. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  22125. },
  22126. enumerable: true,
  22127. configurable: true
  22128. });
  22129. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  22130. get: function () {
  22131. return this._buttonStart;
  22132. },
  22133. set: function (value) {
  22134. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  22135. },
  22136. enumerable: true,
  22137. configurable: true
  22138. });
  22139. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  22140. get: function () {
  22141. return this._buttonBack;
  22142. },
  22143. set: function (value) {
  22144. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  22145. },
  22146. enumerable: true,
  22147. configurable: true
  22148. });
  22149. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  22150. get: function () {
  22151. return this._buttonLB;
  22152. },
  22153. set: function (value) {
  22154. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  22155. },
  22156. enumerable: true,
  22157. configurable: true
  22158. });
  22159. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  22160. get: function () {
  22161. return this._buttonRB;
  22162. },
  22163. set: function (value) {
  22164. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  22165. },
  22166. enumerable: true,
  22167. configurable: true
  22168. });
  22169. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  22170. get: function () {
  22171. return this._buttonLeftStick;
  22172. },
  22173. set: function (value) {
  22174. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  22175. },
  22176. enumerable: true,
  22177. configurable: true
  22178. });
  22179. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  22180. get: function () {
  22181. return this._buttonRightStick;
  22182. },
  22183. set: function (value) {
  22184. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  22185. },
  22186. enumerable: true,
  22187. configurable: true
  22188. });
  22189. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  22190. get: function () {
  22191. return this._dPadUp;
  22192. },
  22193. set: function (value) {
  22194. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  22195. },
  22196. enumerable: true,
  22197. configurable: true
  22198. });
  22199. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  22200. get: function () {
  22201. return this._dPadDown;
  22202. },
  22203. set: function (value) {
  22204. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  22205. },
  22206. enumerable: true,
  22207. configurable: true
  22208. });
  22209. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  22210. get: function () {
  22211. return this._dPadLeft;
  22212. },
  22213. set: function (value) {
  22214. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  22215. },
  22216. enumerable: true,
  22217. configurable: true
  22218. });
  22219. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  22220. get: function () {
  22221. return this._dPadRight;
  22222. },
  22223. set: function (value) {
  22224. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  22225. },
  22226. enumerable: true,
  22227. configurable: true
  22228. });
  22229. Xbox360Pad.prototype.update = function () {
  22230. _super.prototype.update.call(this);
  22231. this.buttonA = this.browserGamepad.buttons[0].value;
  22232. this.buttonB = this.browserGamepad.buttons[1].value;
  22233. this.buttonX = this.browserGamepad.buttons[2].value;
  22234. this.buttonY = this.browserGamepad.buttons[3].value;
  22235. this.buttonLB = this.browserGamepad.buttons[4].value;
  22236. this.buttonRB = this.browserGamepad.buttons[5].value;
  22237. this.leftTrigger = this.browserGamepad.buttons[6].value;
  22238. this.rightTrigger = this.browserGamepad.buttons[7].value;
  22239. this.buttonBack = this.browserGamepad.buttons[8].value;
  22240. this.buttonStart = this.browserGamepad.buttons[9].value;
  22241. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  22242. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  22243. this.dPadUp = this.browserGamepad.buttons[12].value;
  22244. this.dPadDown = this.browserGamepad.buttons[13].value;
  22245. this.dPadLeft = this.browserGamepad.buttons[14].value;
  22246. this.dPadRight = this.browserGamepad.buttons[15].value;
  22247. };
  22248. return Xbox360Pad;
  22249. })(Gamepad);
  22250. BABYLON.Xbox360Pad = Xbox360Pad;
  22251. })(BABYLON || (BABYLON = {}));
  22252. var __extends = this.__extends || function (d, b) {
  22253. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22254. function __() { this.constructor = d; }
  22255. __.prototype = b.prototype;
  22256. d.prototype = new __();
  22257. };
  22258. var BABYLON;
  22259. (function (BABYLON) {
  22260. var GamepadCamera = (function (_super) {
  22261. __extends(GamepadCamera, _super);
  22262. function GamepadCamera(name, position, scene) {
  22263. var _this = this;
  22264. _super.call(this, name, position, scene);
  22265. this.angularSensibility = 200;
  22266. this.moveSensibility = 75;
  22267. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  22268. _this._onNewGameConnected(gamepad);
  22269. });
  22270. }
  22271. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  22272. if (gamepad.index === 0) {
  22273. this._gamepad = gamepad;
  22274. }
  22275. };
  22276. GamepadCamera.prototype._checkInputs = function () {
  22277. if (!this._gamepad) {
  22278. return;
  22279. }
  22280. var LSValues = this._gamepad.leftStick;
  22281. var normalizedLX = LSValues.x / this.moveSensibility;
  22282. var normalizedLY = LSValues.y / this.moveSensibility;
  22283. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  22284. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  22285. var RSValues = this._gamepad.rightStick;
  22286. var normalizedRX = RSValues.x / this.angularSensibility;
  22287. var normalizedRY = RSValues.y / this.angularSensibility;
  22288. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  22289. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  22290. ;
  22291. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  22292. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  22293. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  22294. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  22295. };
  22296. GamepadCamera.prototype.dispose = function () {
  22297. this._gamepads.dispose();
  22298. _super.prototype.dispose.call(this);
  22299. };
  22300. return GamepadCamera;
  22301. })(BABYLON.FreeCamera);
  22302. BABYLON.GamepadCamera = GamepadCamera;
  22303. })(BABYLON || (BABYLON = {}));
  22304. var __extends = this.__extends || function (d, b) {
  22305. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22306. function __() { this.constructor = d; }
  22307. __.prototype = b.prototype;
  22308. d.prototype = new __();
  22309. };
  22310. var BABYLON;
  22311. (function (BABYLON) {
  22312. var LinesMesh = (function (_super) {
  22313. __extends(LinesMesh, _super);
  22314. function LinesMesh(name, scene, updatable) {
  22315. if (typeof updatable === "undefined") { updatable = false; }
  22316. _super.call(this, name, scene);
  22317. this.color = new BABYLON.Color3(1, 1, 1);
  22318. this.alpha = 1;
  22319. this._indices = new Array();
  22320. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  22321. attributes: ["position"],
  22322. uniforms: ["worldViewProjection", "color"],
  22323. needAlphaBlending: true
  22324. });
  22325. }
  22326. Object.defineProperty(LinesMesh.prototype, "material", {
  22327. get: function () {
  22328. return this._colorShader;
  22329. },
  22330. enumerable: true,
  22331. configurable: true
  22332. });
  22333. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  22334. get: function () {
  22335. return false;
  22336. },
  22337. enumerable: true,
  22338. configurable: true
  22339. });
  22340. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  22341. get: function () {
  22342. return false;
  22343. },
  22344. enumerable: true,
  22345. configurable: true
  22346. });
  22347. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  22348. var engine = this.getScene().getEngine();
  22349. var indexToBind = this._geometry.getIndexBuffer();
  22350. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  22351. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  22352. };
  22353. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  22354. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22355. return;
  22356. }
  22357. var engine = this.getScene().getEngine();
  22358. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  22359. };
  22360. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  22361. return null;
  22362. };
  22363. LinesMesh.prototype.dispose = function (doNotRecurse) {
  22364. this._colorShader.dispose();
  22365. _super.prototype.dispose.call(this, doNotRecurse);
  22366. };
  22367. return LinesMesh;
  22368. })(BABYLON.Mesh);
  22369. BABYLON.LinesMesh = LinesMesh;
  22370. })(BABYLON || (BABYLON = {}));
  22371. var BABYLON;
  22372. (function (BABYLON) {
  22373. var OutlineRenderer = (function () {
  22374. function OutlineRenderer(scene) {
  22375. this._scene = scene;
  22376. }
  22377. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  22378. if (typeof useOverlay === "undefined") { useOverlay = false; }
  22379. var scene = this._scene;
  22380. var engine = this._scene.getEngine();
  22381. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  22382. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  22383. return;
  22384. }
  22385. var mesh = subMesh.getRenderingMesh();
  22386. var material = subMesh.getMaterial();
  22387. engine.enableEffect(this._effect);
  22388. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  22389. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  22390. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  22391. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  22392. if (useBones) {
  22393. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  22394. }
  22395. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  22396. if (material && material.needAlphaTesting()) {
  22397. var alphaTexture = material.getAlphaTestTexture();
  22398. this._effect.setTexture("diffuseSampler", alphaTexture);
  22399. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  22400. }
  22401. if (hardwareInstancedRendering) {
  22402. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  22403. } else {
  22404. if (batch.renderSelf[subMesh._id]) {
  22405. this._effect.setMatrix("world", mesh.getWorldMatrix());
  22406. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  22407. }
  22408. if (batch.visibleInstances[subMesh._id]) {
  22409. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  22410. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  22411. this._effect.setMatrix("world", instance.getWorldMatrix());
  22412. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  22413. }
  22414. }
  22415. }
  22416. };
  22417. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  22418. var defines = [];
  22419. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  22420. var mesh = subMesh.getMesh();
  22421. var material = subMesh.getMaterial();
  22422. if (material && material.needAlphaTesting()) {
  22423. defines.push("#define ALPHATEST");
  22424. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22425. attribs.push(BABYLON.VertexBuffer.UVKind);
  22426. defines.push("#define UV1");
  22427. }
  22428. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22429. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  22430. defines.push("#define UV2");
  22431. }
  22432. }
  22433. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22434. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22435. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22436. defines.push("#define BONES");
  22437. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  22438. }
  22439. if (useInstances) {
  22440. defines.push("#define INSTANCES");
  22441. attribs.push("world0");
  22442. attribs.push("world1");
  22443. attribs.push("world2");
  22444. attribs.push("world3");
  22445. }
  22446. var join = defines.join("\n");
  22447. if (this._cachedDefines != join) {
  22448. this._cachedDefines = join;
  22449. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  22450. }
  22451. return this._effect.isReady();
  22452. };
  22453. return OutlineRenderer;
  22454. })();
  22455. BABYLON.OutlineRenderer = OutlineRenderer;
  22456. })(BABYLON || (BABYLON = {}));
  22457. var BABYLON;
  22458. (function (BABYLON) {
  22459. var MeshAssetTask = (function () {
  22460. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  22461. this.name = name;
  22462. this.meshesNames = meshesNames;
  22463. this.rootUrl = rootUrl;
  22464. this.sceneFilename = sceneFilename;
  22465. this.isCompleted = false;
  22466. }
  22467. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  22468. var _this = this;
  22469. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  22470. _this.loadedMeshes = meshes;
  22471. _this.loadedParticleSystems = particleSystems;
  22472. _this.loadedSkeletons = skeletons;
  22473. _this.isCompleted = true;
  22474. if (_this.onSuccess) {
  22475. _this.onSuccess(_this);
  22476. }
  22477. onSuccess();
  22478. }, null, function () {
  22479. if (_this.onError) {
  22480. _this.onError(_this);
  22481. }
  22482. onError();
  22483. });
  22484. };
  22485. return MeshAssetTask;
  22486. })();
  22487. BABYLON.MeshAssetTask = MeshAssetTask;
  22488. var TextFileAssetTask = (function () {
  22489. function TextFileAssetTask(name, url) {
  22490. this.name = name;
  22491. this.url = url;
  22492. this.isCompleted = false;
  22493. }
  22494. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  22495. var _this = this;
  22496. BABYLON.Tools.LoadFile(this.url, function (data) {
  22497. _this.text = data;
  22498. _this.isCompleted = true;
  22499. if (_this.onSuccess) {
  22500. _this.onSuccess(_this);
  22501. }
  22502. onSuccess();
  22503. }, null, scene.database, false, function () {
  22504. if (_this.onError) {
  22505. _this.onError(_this);
  22506. }
  22507. onError();
  22508. });
  22509. };
  22510. return TextFileAssetTask;
  22511. })();
  22512. BABYLON.TextFileAssetTask = TextFileAssetTask;
  22513. var BinaryFileAssetTask = (function () {
  22514. function BinaryFileAssetTask(name, url) {
  22515. this.name = name;
  22516. this.url = url;
  22517. this.isCompleted = false;
  22518. }
  22519. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  22520. var _this = this;
  22521. BABYLON.Tools.LoadFile(this.url, function (data) {
  22522. _this.data = data;
  22523. _this.isCompleted = true;
  22524. if (_this.onSuccess) {
  22525. _this.onSuccess(_this);
  22526. }
  22527. onSuccess();
  22528. }, null, scene.database, true, function () {
  22529. if (_this.onError) {
  22530. _this.onError(_this);
  22531. }
  22532. onError();
  22533. });
  22534. };
  22535. return BinaryFileAssetTask;
  22536. })();
  22537. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  22538. var ImageAssetTask = (function () {
  22539. function ImageAssetTask(name, url) {
  22540. this.name = name;
  22541. this.url = url;
  22542. this.isCompleted = false;
  22543. }
  22544. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  22545. var _this = this;
  22546. var img = new Image();
  22547. img.onload = function () {
  22548. _this.image = img;
  22549. _this.isCompleted = true;
  22550. if (_this.onSuccess) {
  22551. _this.onSuccess(_this);
  22552. }
  22553. onSuccess();
  22554. };
  22555. img.onerror = function () {
  22556. if (_this.onError) {
  22557. _this.onError(_this);
  22558. }
  22559. onError();
  22560. };
  22561. img.src = this.url;
  22562. };
  22563. return ImageAssetTask;
  22564. })();
  22565. BABYLON.ImageAssetTask = ImageAssetTask;
  22566. var TextureAssetTask = (function () {
  22567. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  22568. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22569. this.name = name;
  22570. this.url = url;
  22571. this.noMipmap = noMipmap;
  22572. this.invertY = invertY;
  22573. this.samplingMode = samplingMode;
  22574. this.isCompleted = false;
  22575. }
  22576. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  22577. var _this = this;
  22578. var onload = function () {
  22579. _this.isCompleted = true;
  22580. if (_this.onSuccess) {
  22581. _this.onSuccess(_this);
  22582. }
  22583. onSuccess();
  22584. };
  22585. var onerror = function () {
  22586. if (_this.onError) {
  22587. _this.onError(_this);
  22588. }
  22589. onError();
  22590. };
  22591. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  22592. };
  22593. return TextureAssetTask;
  22594. })();
  22595. BABYLON.TextureAssetTask = TextureAssetTask;
  22596. var AssetsManager = (function () {
  22597. function AssetsManager(scene) {
  22598. this._tasks = new Array();
  22599. this._waitingTasksCount = 0;
  22600. this.useDefaultLoadingScreen = true;
  22601. this._scene = scene;
  22602. }
  22603. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  22604. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  22605. this._tasks.push(task);
  22606. return task;
  22607. };
  22608. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  22609. var task = new TextFileAssetTask(taskName, url);
  22610. this._tasks.push(task);
  22611. return task;
  22612. };
  22613. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  22614. var task = new BinaryFileAssetTask(taskName, url);
  22615. this._tasks.push(task);
  22616. return task;
  22617. };
  22618. AssetsManager.prototype.addImageTask = function (taskName, url) {
  22619. var task = new ImageAssetTask(taskName, url);
  22620. this._tasks.push(task);
  22621. return task;
  22622. };
  22623. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  22624. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22625. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  22626. this._tasks.push(task);
  22627. return task;
  22628. };
  22629. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  22630. this._waitingTasksCount--;
  22631. if (this._waitingTasksCount === 0) {
  22632. if (this.onFinish) {
  22633. this.onFinish(this._tasks);
  22634. }
  22635. this._scene.getEngine().hideLoadingUI();
  22636. }
  22637. };
  22638. AssetsManager.prototype._runTask = function (task) {
  22639. var _this = this;
  22640. task.run(this._scene, function () {
  22641. if (_this.onTaskSuccess) {
  22642. _this.onTaskSuccess(task);
  22643. }
  22644. _this._decreaseWaitingTasksCount();
  22645. }, function () {
  22646. if (_this.onTaskError) {
  22647. _this.onTaskError(task);
  22648. }
  22649. _this._decreaseWaitingTasksCount();
  22650. });
  22651. };
  22652. AssetsManager.prototype.reset = function () {
  22653. this._tasks = new Array();
  22654. return this;
  22655. };
  22656. AssetsManager.prototype.load = function () {
  22657. this._waitingTasksCount = this._tasks.length;
  22658. if (this._waitingTasksCount === 0) {
  22659. if (this.onFinish) {
  22660. this.onFinish(this._tasks);
  22661. }
  22662. return this;
  22663. }
  22664. if (this.useDefaultLoadingScreen) {
  22665. this._scene.getEngine().displayLoadingUI();
  22666. }
  22667. for (var index = 0; index < this._tasks.length; index++) {
  22668. var task = this._tasks[index];
  22669. this._runTask(task);
  22670. }
  22671. return this;
  22672. };
  22673. return AssetsManager;
  22674. })();
  22675. BABYLON.AssetsManager = AssetsManager;
  22676. })(BABYLON || (BABYLON = {}));
  22677. var __extends = this.__extends || function (d, b) {
  22678. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22679. function __() { this.constructor = d; }
  22680. __.prototype = b.prototype;
  22681. d.prototype = new __();
  22682. };
  22683. var BABYLON;
  22684. (function (BABYLON) {
  22685. var VRDeviceOrientationCamera = (function (_super) {
  22686. __extends(VRDeviceOrientationCamera, _super);
  22687. function VRDeviceOrientationCamera(name, position, scene) {
  22688. _super.call(this, name, position, scene);
  22689. this._alpha = 0;
  22690. this._beta = 0;
  22691. this._gamma = 0;
  22692. }
  22693. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  22694. this._alpha = +evt.alpha | 0;
  22695. this._beta = +evt.beta | 0;
  22696. this._gamma = +evt.gamma | 0;
  22697. if (this._gamma < 0) {
  22698. this._gamma = 90 + this._gamma;
  22699. } else {
  22700. this._gamma = 270 - this._gamma;
  22701. }
  22702. this.rotation.x = this._gamma / 180.0 * Math.PI;
  22703. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  22704. this.rotation.z = this._beta / 180.0 * Math.PI;
  22705. };
  22706. return VRDeviceOrientationCamera;
  22707. })(BABYLON.OculusCamera);
  22708. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  22709. })(BABYLON || (BABYLON = {}));
  22710. var __extends = this.__extends || function (d, b) {
  22711. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22712. function __() { this.constructor = d; }
  22713. __.prototype = b.prototype;
  22714. d.prototype = new __();
  22715. };
  22716. var BABYLON;
  22717. (function (BABYLON) {
  22718. var WebVRCamera = (function (_super) {
  22719. __extends(WebVRCamera, _super);
  22720. function WebVRCamera(name, position, scene) {
  22721. _super.call(this, name, position, scene);
  22722. this._hmdDevice = null;
  22723. this._sensorDevice = null;
  22724. this._cacheState = null;
  22725. this._cacheQuaternion = new BABYLON.Quaternion();
  22726. this._cacheRotation = BABYLON.Vector3.Zero();
  22727. this._vrEnabled = false;
  22728. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  22729. }
  22730. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  22731. var size = devices.length;
  22732. var i = 0;
  22733. this._sensorDevice = null;
  22734. this._hmdDevice = null;
  22735. while (i < size && this._hmdDevice === null) {
  22736. if (devices[i] instanceof HMDVRDevice) {
  22737. this._hmdDevice = devices[i];
  22738. }
  22739. i++;
  22740. }
  22741. i = 0;
  22742. while (i < size && this._sensorDevice === null) {
  22743. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  22744. this._sensorDevice = devices[i];
  22745. }
  22746. i++;
  22747. }
  22748. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  22749. };
  22750. WebVRCamera.prototype._update = function () {
  22751. if (this._vrEnabled) {
  22752. this._cacheState = this._sensorDevice.getState();
  22753. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  22754. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  22755. this.rotation.x = -this._cacheRotation.z;
  22756. this.rotation.y = -this._cacheRotation.y;
  22757. this.rotation.z = this._cacheRotation.x;
  22758. }
  22759. _super.prototype._update.call(this);
  22760. };
  22761. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  22762. _super.prototype.attachControl.call(this, element, noPreventDefault);
  22763. if (navigator.getVRDevices) {
  22764. navigator.getVRDevices().then(this._getWebVRDevices);
  22765. } else if (navigator.mozGetVRDevices) {
  22766. navigator.mozGetVRDevices(this._getWebVRDevices);
  22767. }
  22768. };
  22769. WebVRCamera.prototype.detachControl = function (element) {
  22770. _super.prototype.detachControl.call(this, element);
  22771. this._vrEnabled = false;
  22772. };
  22773. return WebVRCamera;
  22774. })(BABYLON.OculusCamera);
  22775. BABYLON.WebVRCamera = WebVRCamera;
  22776. })(BABYLON || (BABYLON = {}));
  22777. var __extends = this.__extends || function (d, b) {
  22778. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22779. function __() { this.constructor = d; }
  22780. __.prototype = b.prototype;
  22781. d.prototype = new __();
  22782. };
  22783. var BABYLON;
  22784. (function (BABYLON) {
  22785. var SceneOptimization = (function () {
  22786. function SceneOptimization(priority) {
  22787. if (typeof priority === "undefined") { priority = 0; }
  22788. this.priority = priority;
  22789. this.apply = function (scene) {
  22790. return true;
  22791. };
  22792. }
  22793. return SceneOptimization;
  22794. })();
  22795. BABYLON.SceneOptimization = SceneOptimization;
  22796. var TextureOptimization = (function (_super) {
  22797. __extends(TextureOptimization, _super);
  22798. function TextureOptimization(priority, maximumSize) {
  22799. if (typeof priority === "undefined") { priority = 0; }
  22800. if (typeof maximumSize === "undefined") { maximumSize = 1024; }
  22801. var _this = this;
  22802. _super.call(this, priority);
  22803. this.priority = priority;
  22804. this.maximumSize = maximumSize;
  22805. this.apply = function (scene) {
  22806. var allDone = true;
  22807. for (var index = 0; index < scene.textures.length; index++) {
  22808. var texture = scene.textures[index];
  22809. if (!texture.canRescale) {
  22810. continue;
  22811. }
  22812. var currentSize = texture.getSize();
  22813. var maxDimension = Math.max(currentSize.width, currentSize.height);
  22814. if (maxDimension > _this.maximumSize) {
  22815. texture.scale(0.5);
  22816. allDone = false;
  22817. }
  22818. }
  22819. return allDone;
  22820. };
  22821. }
  22822. return TextureOptimization;
  22823. })(SceneOptimization);
  22824. BABYLON.TextureOptimization = TextureOptimization;
  22825. var HardwareScalingOptimization = (function (_super) {
  22826. __extends(HardwareScalingOptimization, _super);
  22827. function HardwareScalingOptimization(priority, maximumScale) {
  22828. if (typeof priority === "undefined") { priority = 0; }
  22829. if (typeof maximumScale === "undefined") { maximumScale = 2; }
  22830. var _this = this;
  22831. _super.call(this, priority);
  22832. this.priority = priority;
  22833. this.maximumScale = maximumScale;
  22834. this._currentScale = 1;
  22835. this.apply = function (scene) {
  22836. _this._currentScale++;
  22837. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  22838. return _this._currentScale >= _this.maximumScale;
  22839. };
  22840. }
  22841. return HardwareScalingOptimization;
  22842. })(SceneOptimization);
  22843. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  22844. var ShadowsOptimization = (function (_super) {
  22845. __extends(ShadowsOptimization, _super);
  22846. function ShadowsOptimization() {
  22847. _super.apply(this, arguments);
  22848. this.apply = function (scene) {
  22849. scene.shadowsEnabled = false;
  22850. return true;
  22851. };
  22852. }
  22853. return ShadowsOptimization;
  22854. })(SceneOptimization);
  22855. BABYLON.ShadowsOptimization = ShadowsOptimization;
  22856. var PostProcessesOptimization = (function (_super) {
  22857. __extends(PostProcessesOptimization, _super);
  22858. function PostProcessesOptimization() {
  22859. _super.apply(this, arguments);
  22860. this.apply = function (scene) {
  22861. scene.postProcessesEnabled = false;
  22862. return true;
  22863. };
  22864. }
  22865. return PostProcessesOptimization;
  22866. })(SceneOptimization);
  22867. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  22868. var LensFlaresOptimization = (function (_super) {
  22869. __extends(LensFlaresOptimization, _super);
  22870. function LensFlaresOptimization() {
  22871. _super.apply(this, arguments);
  22872. this.apply = function (scene) {
  22873. scene.lensFlaresEnabled = false;
  22874. return true;
  22875. };
  22876. }
  22877. return LensFlaresOptimization;
  22878. })(SceneOptimization);
  22879. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  22880. var ParticlesOptimization = (function (_super) {
  22881. __extends(ParticlesOptimization, _super);
  22882. function ParticlesOptimization() {
  22883. _super.apply(this, arguments);
  22884. this.apply = function (scene) {
  22885. scene.particlesEnabled = false;
  22886. return true;
  22887. };
  22888. }
  22889. return ParticlesOptimization;
  22890. })(SceneOptimization);
  22891. BABYLON.ParticlesOptimization = ParticlesOptimization;
  22892. var RenderTargetsOptimization = (function (_super) {
  22893. __extends(RenderTargetsOptimization, _super);
  22894. function RenderTargetsOptimization() {
  22895. _super.apply(this, arguments);
  22896. this.apply = function (scene) {
  22897. scene.renderTargetsEnabled = false;
  22898. return true;
  22899. };
  22900. }
  22901. return RenderTargetsOptimization;
  22902. })(SceneOptimization);
  22903. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  22904. var MergeMeshesOptimization = (function (_super) {
  22905. __extends(MergeMeshesOptimization, _super);
  22906. function MergeMeshesOptimization() {
  22907. _super.apply(this, arguments);
  22908. var _this = this;
  22909. this._canBeMerged = function (abstractMesh) {
  22910. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  22911. return false;
  22912. }
  22913. var mesh = abstractMesh;
  22914. if (!mesh.isVisible || !mesh.isEnabled()) {
  22915. return false;
  22916. }
  22917. if (mesh.instances.length > 0) {
  22918. return false;
  22919. }
  22920. if (mesh.skeleton || mesh.hasLODLevels) {
  22921. return false;
  22922. }
  22923. return true;
  22924. };
  22925. this.apply = function (scene) {
  22926. var globalPool = scene.meshes.slice(0);
  22927. var globalLength = globalPool.length;
  22928. for (var index = 0; index < globalLength; index++) {
  22929. var currentPool = new Array();
  22930. var current = globalPool[index];
  22931. if (!_this._canBeMerged(current)) {
  22932. continue;
  22933. }
  22934. currentPool.push(current);
  22935. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  22936. var otherMesh = globalPool[subIndex];
  22937. if (!_this._canBeMerged(otherMesh)) {
  22938. continue;
  22939. }
  22940. if (otherMesh.material !== current.material) {
  22941. continue;
  22942. }
  22943. if (otherMesh.checkCollisions !== current.checkCollisions) {
  22944. continue;
  22945. }
  22946. currentPool.push(otherMesh);
  22947. globalLength--;
  22948. globalPool.splice(subIndex, 1);
  22949. subIndex--;
  22950. }
  22951. if (currentPool.length < 2) {
  22952. continue;
  22953. }
  22954. BABYLON.Mesh.MergeMeshes(currentPool);
  22955. }
  22956. return true;
  22957. };
  22958. }
  22959. return MergeMeshesOptimization;
  22960. })(SceneOptimization);
  22961. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  22962. var SceneOptimizerOptions = (function () {
  22963. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  22964. if (typeof targetFrameRate === "undefined") { targetFrameRate = 60; }
  22965. if (typeof trackerDuration === "undefined") { trackerDuration = 2000; }
  22966. this.targetFrameRate = targetFrameRate;
  22967. this.trackerDuration = trackerDuration;
  22968. this.optimizations = new Array();
  22969. }
  22970. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  22971. var result = new SceneOptimizerOptions(targetFrameRate);
  22972. var priority = 0;
  22973. result.optimizations.push(new MergeMeshesOptimization(priority));
  22974. result.optimizations.push(new ShadowsOptimization(priority));
  22975. result.optimizations.push(new LensFlaresOptimization(priority));
  22976. priority++;
  22977. result.optimizations.push(new PostProcessesOptimization(priority));
  22978. result.optimizations.push(new ParticlesOptimization(priority));
  22979. priority++;
  22980. result.optimizations.push(new TextureOptimization(priority, 1024));
  22981. return result;
  22982. };
  22983. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  22984. var result = new SceneOptimizerOptions(targetFrameRate);
  22985. var priority = 0;
  22986. result.optimizations.push(new MergeMeshesOptimization(priority));
  22987. result.optimizations.push(new ShadowsOptimization(priority));
  22988. result.optimizations.push(new LensFlaresOptimization(priority));
  22989. priority++;
  22990. result.optimizations.push(new PostProcessesOptimization(priority));
  22991. result.optimizations.push(new ParticlesOptimization(priority));
  22992. priority++;
  22993. result.optimizations.push(new TextureOptimization(priority, 512));
  22994. priority++;
  22995. result.optimizations.push(new RenderTargetsOptimization(priority));
  22996. priority++;
  22997. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  22998. return result;
  22999. };
  23000. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  23001. var result = new SceneOptimizerOptions(targetFrameRate);
  23002. var priority = 0;
  23003. result.optimizations.push(new MergeMeshesOptimization(priority));
  23004. result.optimizations.push(new ShadowsOptimization(priority));
  23005. result.optimizations.push(new LensFlaresOptimization(priority));
  23006. priority++;
  23007. result.optimizations.push(new PostProcessesOptimization(priority));
  23008. result.optimizations.push(new ParticlesOptimization(priority));
  23009. priority++;
  23010. result.optimizations.push(new TextureOptimization(priority, 256));
  23011. priority++;
  23012. result.optimizations.push(new RenderTargetsOptimization(priority));
  23013. priority++;
  23014. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  23015. return result;
  23016. };
  23017. return SceneOptimizerOptions;
  23018. })();
  23019. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  23020. var SceneOptimizer = (function () {
  23021. function SceneOptimizer() {
  23022. }
  23023. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  23024. if (BABYLON.Tools.GetFps() >= options.targetFrameRate) {
  23025. if (onSuccess) {
  23026. onSuccess();
  23027. }
  23028. return;
  23029. }
  23030. var allDone = true;
  23031. var noOptimizationApplied = true;
  23032. for (var index = 0; index < options.optimizations.length; index++) {
  23033. var optimization = options.optimizations[index];
  23034. if (optimization.priority === currentPriorityLevel) {
  23035. noOptimizationApplied = false;
  23036. allDone = allDone && optimization.apply(scene);
  23037. }
  23038. }
  23039. if (noOptimizationApplied) {
  23040. if (onFailure) {
  23041. onFailure();
  23042. }
  23043. return;
  23044. }
  23045. if (allDone) {
  23046. currentPriorityLevel++;
  23047. }
  23048. scene.executeWhenReady(function () {
  23049. setTimeout(function () {
  23050. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  23051. }, options.trackerDuration);
  23052. });
  23053. };
  23054. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  23055. if (!options) {
  23056. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  23057. }
  23058. scene.executeWhenReady(function () {
  23059. setTimeout(function () {
  23060. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  23061. }, options.trackerDuration);
  23062. });
  23063. };
  23064. return SceneOptimizer;
  23065. })();
  23066. BABYLON.SceneOptimizer = SceneOptimizer;
  23067. })(BABYLON || (BABYLON = {}));
  23068. var BABYLON;
  23069. (function (BABYLON) {
  23070. (function (Internals) {
  23071. var MeshLODLevel = (function () {
  23072. function MeshLODLevel(distance, mesh) {
  23073. this.distance = distance;
  23074. this.mesh = mesh;
  23075. }
  23076. return MeshLODLevel;
  23077. })();
  23078. Internals.MeshLODLevel = MeshLODLevel;
  23079. })(BABYLON.Internals || (BABYLON.Internals = {}));
  23080. var Internals = BABYLON.Internals;
  23081. })(BABYLON || (BABYLON = {}));
  23082. var BABYLON;
  23083. (function (BABYLON) {
  23084. var AudioEngine = (function () {
  23085. function AudioEngine() {
  23086. this.audioContext = null;
  23087. this.canUseWebAudio = false;
  23088. try {
  23089. if (typeof AudioContext !== 'undefined') {
  23090. this.audioContext = new AudioContext();
  23091. this.canUseWebAudio = true;
  23092. } else if (typeof webkitAudioContext !== 'undefined') {
  23093. this.audioContext = new webkitAudioContext();
  23094. this.canUseWebAudio = true;
  23095. }
  23096. } catch (e) {
  23097. this.canUseWebAudio = false;
  23098. }
  23099. if (this.canUseWebAudio) {
  23100. this.masterGain = this.audioContext.createGain();
  23101. this.masterGain.gain.value = 1;
  23102. this.masterGain.connect(this.audioContext.destination);
  23103. }
  23104. }
  23105. AudioEngine.prototype.getGlobalVolume = function () {
  23106. if (this.canUseWebAudio) {
  23107. return this.masterGain.gain.value;
  23108. } else {
  23109. return -1;
  23110. }
  23111. };
  23112. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  23113. if (this.canUseWebAudio) {
  23114. this.masterGain.gain.value = newVolume;
  23115. }
  23116. };
  23117. return AudioEngine;
  23118. })();
  23119. BABYLON.AudioEngine = AudioEngine;
  23120. })(BABYLON || (BABYLON = {}));
  23121. var BABYLON;
  23122. (function (BABYLON) {
  23123. var Sound = (function () {
  23124. /**
  23125. * Create a sound and attach it to a scene
  23126. * @param name Name of your sound
  23127. * @param url Url to the sound to load async
  23128. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  23129. * @param options Objects to provide with the current available options: autoplay, loop, distanceMax
  23130. */
  23131. function Sound(name, url, scene, readyToPlayCallback, options) {
  23132. var _this = this;
  23133. this.maxDistance = 20;
  23134. this.autoplay = false;
  23135. this.loop = false;
  23136. this.useBabylonJSAttenuation = true;
  23137. this._position = BABYLON.Vector3.Zero();
  23138. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  23139. this._volume = 1;
  23140. this._isLoaded = false;
  23141. this._isReadyToPlay = false;
  23142. this._isPlaying = false;
  23143. this._isDirectional = false;
  23144. this._coneInnerAngle = null;
  23145. this._coneOuterAngle = null;
  23146. this._coneOuterGain = null;
  23147. this._name = name;
  23148. this._scene = scene;
  23149. this._audioEngine = this._scene.getEngine().getAudioEngine();
  23150. this._readyToPlayCallback = readyToPlayCallback;
  23151. if (options) {
  23152. if (options.maxDistance) {
  23153. this.maxDistance = options.maxDistance;
  23154. }
  23155. if (options.autoplay) {
  23156. this.autoplay = options.autoplay;
  23157. }
  23158. if (options.loop) {
  23159. this.loop = options.loop;
  23160. }
  23161. if (options.volume) {
  23162. this._volume = options.volume;
  23163. }
  23164. if (options.useBabylonJSAttenuation) {
  23165. this.useBabylonJSAttenuation = options.useBabylonJSAttenuation;
  23166. }
  23167. }
  23168. if (this._audioEngine.canUseWebAudio) {
  23169. this._soundGain = this._audioEngine.audioContext.createGain();
  23170. this._soundGain.gain.value = this._volume;
  23171. this._soundPanner = this._audioEngine.audioContext.createPanner();
  23172. this._soundPanner.connect(this._soundGain);
  23173. this._scene.mainSoundTrack.AddSound(this);
  23174. BABYLON.Tools.LoadFile(url, function (data) {
  23175. _this._soundLoaded(data);
  23176. }, null, null, true);
  23177. }
  23178. }
  23179. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  23180. if (this._audioEngine.canUseWebAudio) {
  23181. this._soundGain.disconnect();
  23182. this._soundGain.connect(soundTrackAudioNode);
  23183. }
  23184. };
  23185. /**
  23186. * Transform this sound into a directional source
  23187. * @param coneInnerAngle Size of the inner cone in degree
  23188. * @param coneOuterAngle Size of the outer cone in degree
  23189. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  23190. */
  23191. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  23192. if (coneOuterAngle < coneInnerAngle) {
  23193. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  23194. return;
  23195. }
  23196. this._coneInnerAngle = coneInnerAngle;
  23197. this._coneOuterAngle = coneOuterAngle;
  23198. this._coneOuterGain = coneOuterGain;
  23199. this._isDirectional = true;
  23200. if (this._isPlaying && this.loop) {
  23201. this.stop();
  23202. this.play();
  23203. }
  23204. };
  23205. Sound.prototype.setPosition = function (newPosition) {
  23206. this._position = newPosition;
  23207. if (this._isPlaying) {
  23208. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  23209. }
  23210. };
  23211. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  23212. this._localDirection = newLocalDirection;
  23213. if (this._connectedMesh && this._isPlaying) {
  23214. this._updateDirection();
  23215. }
  23216. };
  23217. Sound.prototype._updateDirection = function () {
  23218. var mat = this._connectedMesh.getWorldMatrix();
  23219. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  23220. direction.normalize();
  23221. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  23222. };
  23223. Sound.prototype.updateDistanceFromListener = function () {
  23224. if (this._connectedMesh) {
  23225. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  23226. if (distance < 1)
  23227. distance = 1;
  23228. if (this.useBabylonJSAttenuation) {
  23229. if (distance < this.maxDistance) {
  23230. this._soundGain.gain.value = this._volume / distance;
  23231. } else {
  23232. this._soundGain.gain.value = 0;
  23233. }
  23234. }
  23235. }
  23236. };
  23237. /**
  23238. * Play the sound
  23239. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  23240. */
  23241. Sound.prototype.play = function (time) {
  23242. if (this._isReadyToPlay) {
  23243. try {
  23244. var startTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  23245. this._soundSource = this._audioEngine.audioContext.createBufferSource();
  23246. this._soundSource.buffer = this._audioBuffer;
  23247. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  23248. if (this._isDirectional) {
  23249. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  23250. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  23251. this._soundPanner.coneOuterGain = this._coneOuterGain;
  23252. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  23253. }
  23254. this._soundSource.connect(this._soundPanner);
  23255. this._soundSource.loop = this.loop;
  23256. this._soundSource.start(startTime);
  23257. this._isPlaying = true;
  23258. } catch (ex) {
  23259. BABYLON.Tools.Error("Error while trying to play audio: " + this._name + ", " + ex.message);
  23260. }
  23261. }
  23262. };
  23263. /**
  23264. * Stop the sound
  23265. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  23266. */
  23267. Sound.prototype.stop = function (time) {
  23268. var stopTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  23269. this._soundSource.stop(stopTime);
  23270. this._isPlaying = false;
  23271. };
  23272. Sound.prototype.pause = function () {
  23273. };
  23274. Sound.prototype.setVolume = function (newVolume) {
  23275. this._volume = newVolume;
  23276. };
  23277. Sound.prototype.getVolume = function () {
  23278. return this._volume;
  23279. };
  23280. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  23281. var _this = this;
  23282. this._connectedMesh = meshToConnectTo;
  23283. meshToConnectTo.registerAfterWorldMatrixUpdate(function (connectedMesh) {
  23284. return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh);
  23285. });
  23286. };
  23287. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  23288. this.setPosition(connectedMesh.position);
  23289. if (this._isDirectional && this._isPlaying) {
  23290. this._updateDirection();
  23291. }
  23292. };
  23293. Sound.prototype._soundLoaded = function (audioData) {
  23294. var _this = this;
  23295. this._isLoaded = true;
  23296. this._audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  23297. _this._audioBuffer = buffer;
  23298. _this._isReadyToPlay = true;
  23299. if (_this.autoplay) {
  23300. _this.play();
  23301. }
  23302. if (_this._readyToPlayCallback) {
  23303. _this._readyToPlayCallback();
  23304. }
  23305. }, function (error) {
  23306. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  23307. });
  23308. };
  23309. return Sound;
  23310. })();
  23311. BABYLON.Sound = Sound;
  23312. })(BABYLON || (BABYLON = {}));
  23313. var BABYLON;
  23314. (function (BABYLON) {
  23315. var SoundTrack = (function () {
  23316. function SoundTrack(scene, options) {
  23317. this.id = -1;
  23318. this._isMainTrack = false;
  23319. this._scene = scene;
  23320. this._audioEngine = scene.getEngine().getAudioEngine();
  23321. this.soundCollection = new Array();
  23322. if (this._audioEngine.canUseWebAudio) {
  23323. this._trackGain = this._audioEngine.audioContext.createGain();
  23324. this._trackGain.connect(this._audioEngine.masterGain);
  23325. if (options) {
  23326. if (options.volume) {
  23327. this._trackGain.gain.value = options.volume;
  23328. }
  23329. if (options.mainTrack) {
  23330. this._isMainTrack = options.mainTrack;
  23331. }
  23332. }
  23333. }
  23334. if (!this._isMainTrack) {
  23335. this._scene.soundTracks.push(this);
  23336. this.id = this._scene.soundTracks.length - 1;
  23337. }
  23338. }
  23339. SoundTrack.prototype.AddSound = function (sound) {
  23340. sound.connectToSoundTrackAudioNode(this._trackGain);
  23341. if (sound.soundTrackId) {
  23342. if (sound.soundTrackId === -1) {
  23343. this._scene.mainSoundTrack.RemoveSound(sound);
  23344. } else {
  23345. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  23346. }
  23347. }
  23348. this.soundCollection.push(sound);
  23349. sound.soundTrackId = this.id;
  23350. };
  23351. SoundTrack.prototype.RemoveSound = function (sound) {
  23352. var index = this.soundCollection.indexOf(sound);
  23353. if (index !== -1) {
  23354. this.soundCollection.splice(index, 1);
  23355. }
  23356. };
  23357. SoundTrack.prototype.setVolume = function (newVolume) {
  23358. if (this._audioEngine.canUseWebAudio) {
  23359. this._trackGain.gain.value = newVolume;
  23360. }
  23361. };
  23362. return SoundTrack;
  23363. })();
  23364. BABYLON.SoundTrack = SoundTrack;
  23365. })(BABYLON || (BABYLON = {}));
  23366. var BABYLON;
  23367. (function (BABYLON) {
  23368. var DebugLayer = (function () {
  23369. function DebugLayer(scene) {
  23370. var _this = this;
  23371. this._enabled = false;
  23372. this._labelsEnabled = false;
  23373. this._displayStatistics = true;
  23374. this._displayTree = false;
  23375. this._displayLogs = false;
  23376. this._identityMatrix = BABYLON.Matrix.Identity();
  23377. this.axisRatio = 0.02;
  23378. this._scene = scene;
  23379. this._syncPositions = function () {
  23380. var engine = _this._scene.getEngine();
  23381. var canvasRect = engine.getRenderingCanvasClientRect();
  23382. if (_this._showUI) {
  23383. _this._statsDiv.style.left = (canvasRect.width - 310) + "px";
  23384. _this._statsDiv.style.top = (canvasRect.height - 370) + "px";
  23385. _this._statsDiv.style.width = "300px";
  23386. _this._statsDiv.style.height = "360px";
  23387. _this._statsSubsetDiv.style.maxHeight = (canvasRect.height - 60) + "px";
  23388. _this._optionsDiv.style.left = "0px";
  23389. _this._optionsDiv.style.top = "10px";
  23390. _this._optionsDiv.style.width = "200px";
  23391. _this._optionsDiv.style.height = "auto";
  23392. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  23393. _this._logDiv.style.left = "0px";
  23394. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  23395. _this._logDiv.style.width = "600px";
  23396. _this._logDiv.style.height = "160px";
  23397. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  23398. _this._treeDiv.style.top = "10px";
  23399. _this._treeDiv.style.width = "300px";
  23400. _this._treeDiv.style.height = "auto";
  23401. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 490) + "px";
  23402. }
  23403. _this._globalDiv.style.left = canvasRect.left + "px";
  23404. _this._globalDiv.style.top = canvasRect.top + "px";
  23405. _this._drawingCanvas.style.left = "0px";
  23406. _this._drawingCanvas.style.top = "0px";
  23407. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  23408. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  23409. var devicePixelRatio = window.devicePixelRatio || 1;
  23410. var context = _this._drawingContext;
  23411. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  23412. _this._ratio = devicePixelRatio / backingStoreRatio;
  23413. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  23414. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  23415. };
  23416. this._onCanvasClick = function (evt) {
  23417. _this._clickPosition = {
  23418. x: evt.clientX * _this._ratio,
  23419. y: evt.clientY * _this._ratio
  23420. };
  23421. };
  23422. this._syncData = function () {
  23423. if (_this._showUI) {
  23424. if (_this._displayStatistics) {
  23425. _this._displayStats();
  23426. _this._statsDiv.style.display = "";
  23427. } else {
  23428. _this._statsDiv.style.display = "none";
  23429. }
  23430. if (_this._displayLogs) {
  23431. _this._logDiv.style.display = "";
  23432. } else {
  23433. _this._logDiv.style.display = "none";
  23434. }
  23435. if (_this._displayTree) {
  23436. _this._treeDiv.style.display = "";
  23437. if (_this._needToRefreshMeshesTree) {
  23438. _this._needToRefreshMeshesTree = false;
  23439. _this._refreshMeshesTreeContent();
  23440. }
  23441. } else {
  23442. _this._treeDiv.style.display = "none";
  23443. }
  23444. }
  23445. if (_this._labelsEnabled || !_this._showUI) {
  23446. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  23447. var engine = _this._scene.getEngine();
  23448. var viewport = _this._scene.activeCamera.viewport;
  23449. var globalViewport = viewport.toGlobal(engine);
  23450. var meshes = _this._scene.getActiveMeshes();
  23451. for (var index = 0; index < meshes.length; index++) {
  23452. var mesh = meshes.data[index];
  23453. var position = mesh.getBoundingInfo().boundingSphere.center;
  23454. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  23455. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  23456. _this._renderAxis(projectedPosition, mesh, globalViewport);
  23457. }
  23458. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  23459. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  23460. mesh.renderOverlay = !mesh.renderOverlay;
  23461. }, function () {
  23462. return mesh.renderOverlay ? 'red' : 'black';
  23463. });
  23464. }
  23465. }
  23466. var cameras = _this._scene.cameras;
  23467. for (index = 0; index < cameras.length; index++) {
  23468. var camera = cameras[index];
  23469. if (camera === _this._scene.activeCamera) {
  23470. continue;
  23471. }
  23472. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  23473. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  23474. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  23475. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  23476. _this._scene.activeCamera = camera;
  23477. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  23478. }, function () {
  23479. return "purple";
  23480. });
  23481. }
  23482. }
  23483. var lights = _this._scene.lights;
  23484. for (index = 0; index < lights.length; index++) {
  23485. var light = lights[index];
  23486. if (light.position) {
  23487. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  23488. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  23489. _this._renderLabel(light.name, projectedPosition, -20, function () {
  23490. light.setEnabled(!light.isEnabled());
  23491. }, function () {
  23492. return light.isEnabled() ? "orange" : "gray";
  23493. });
  23494. }
  23495. }
  23496. }
  23497. }
  23498. _this._clickPosition = undefined;
  23499. };
  23500. }
  23501. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  23502. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  23503. sortedArray.sort(function (a, b) {
  23504. if (a.name === b.name) {
  23505. return 0;
  23506. }
  23507. return (a.name > b.name) ? 1 : -1;
  23508. });
  23509. for (var index = 0; index < sortedArray.length; index++) {
  23510. var mesh = sortedArray[index];
  23511. if (!mesh.isEnabled()) {
  23512. continue;
  23513. }
  23514. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, mesh) {
  23515. mesh.isVisible = element.checked;
  23516. }, mesh);
  23517. }
  23518. };
  23519. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  23520. this._drawingContext.beginPath();
  23521. this._drawingContext.moveTo(zero.x, zero.y);
  23522. this._drawingContext.lineTo(unit.x, unit.y);
  23523. this._drawingContext.strokeStyle = color;
  23524. this._drawingContext.lineWidth = 4;
  23525. this._drawingContext.stroke();
  23526. this._drawingContext.font = "normal 14px Segoe UI";
  23527. this._drawingContext.fillStyle = color;
  23528. this._drawingContext.fillText(label, unitText.x, unitText.y);
  23529. };
  23530. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  23531. var position = mesh.getBoundingInfo().boundingSphere.center;
  23532. var worldMatrix = mesh.getWorldMatrix();
  23533. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._scene.getTransformMatrix());
  23534. var unit = (unprojectedVector.subtract(position)).length();
  23535. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  23536. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  23537. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  23538. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  23539. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  23540. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  23541. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  23542. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  23543. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  23544. };
  23545. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  23546. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  23547. this._drawingContext.font = "normal 12px Segoe UI";
  23548. var textMetrics = this._drawingContext.measureText(text);
  23549. var centerX = projectedPosition.x - textMetrics.width / 2;
  23550. var centerY = projectedPosition.y;
  23551. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  23552. onClick();
  23553. }
  23554. this._drawingContext.beginPath();
  23555. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  23556. this._drawingContext.fillStyle = getFillStyle();
  23557. this._drawingContext.globalAlpha = 0.5;
  23558. this._drawingContext.fill();
  23559. this._drawingContext.globalAlpha = 1.0;
  23560. this._drawingContext.strokeStyle = '#FFFFFF';
  23561. this._drawingContext.lineWidth = 1;
  23562. this._drawingContext.stroke();
  23563. this._drawingContext.fillStyle = "#FFFFFF";
  23564. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  23565. this._drawingContext.beginPath();
  23566. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  23567. this._drawingContext.fill();
  23568. }
  23569. };
  23570. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  23571. if (!this._clickPosition) {
  23572. return false;
  23573. }
  23574. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  23575. return false;
  23576. }
  23577. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  23578. return false;
  23579. }
  23580. return true;
  23581. };
  23582. DebugLayer.prototype.isVisible = function () {
  23583. return this._enabled;
  23584. };
  23585. DebugLayer.prototype.hide = function () {
  23586. if (!this._enabled) {
  23587. return;
  23588. }
  23589. this._enabled = false;
  23590. var engine = this._scene.getEngine();
  23591. this._scene.unregisterAfterRender(this._syncData);
  23592. document.body.removeChild(this._globalDiv);
  23593. window.removeEventListener("resize", this._syncPositions);
  23594. this._scene.forceShowBoundingBoxes = false;
  23595. this._scene.forceWireframe = false;
  23596. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  23597. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  23598. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  23599. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  23600. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  23601. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  23602. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  23603. this._scene.shadowsEnabled = true;
  23604. this._scene.particlesEnabled = true;
  23605. this._scene.postProcessesEnabled = true;
  23606. this._scene.collisionsEnabled = true;
  23607. this._scene.lightsEnabled = true;
  23608. this._scene.texturesEnabled = true;
  23609. this._scene.lensFlaresEnabled = true;
  23610. this._scene.proceduralTexturesEnabled = true;
  23611. this._scene.renderTargetsEnabled = true;
  23612. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  23613. };
  23614. DebugLayer.prototype.show = function (showUI) {
  23615. if (typeof showUI === "undefined") { showUI = true; }
  23616. if (this._enabled) {
  23617. return;
  23618. }
  23619. this._enabled = true;
  23620. this._showUI = showUI;
  23621. var engine = this._scene.getEngine();
  23622. this._globalDiv = document.createElement("div");
  23623. document.body.appendChild(this._globalDiv);
  23624. this._generateDOMelements();
  23625. window.addEventListener("resize", this._syncPositions);
  23626. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  23627. this._syncPositions();
  23628. this._scene.registerAfterRender(this._syncData);
  23629. };
  23630. DebugLayer.prototype._clearLabels = function () {
  23631. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  23632. for (var index = 0; index < this._scene.meshes.length; index++) {
  23633. var mesh = this._scene.meshes[index];
  23634. mesh.renderOverlay = false;
  23635. }
  23636. };
  23637. DebugLayer.prototype._generateheader = function (root, text) {
  23638. var header = document.createElement("div");
  23639. header.innerHTML = text + "&nbsp;";
  23640. header.style.textAlign = "right";
  23641. header.style.width = "100%";
  23642. header.style.color = "white";
  23643. header.style.backgroundColor = "Black";
  23644. header.style.padding = "5px 5px 4px 0px";
  23645. header.style.marginLeft = "-5px";
  23646. root.appendChild(header);
  23647. };
  23648. DebugLayer.prototype._generateTexBox = function (root, title) {
  23649. var label = document.createElement("label");
  23650. label.innerHTML = title;
  23651. root.appendChild(label);
  23652. root.appendChild(document.createElement("br"));
  23653. };
  23654. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  23655. if (typeof tag === "undefined") { tag = null; }
  23656. var label = document.createElement("label");
  23657. var boundingBoxesCheckbox = document.createElement("input");
  23658. boundingBoxesCheckbox.type = "checkbox";
  23659. boundingBoxesCheckbox.checked = initialState;
  23660. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  23661. task(evt.target, tag);
  23662. });
  23663. label.appendChild(boundingBoxesCheckbox);
  23664. var container = document.createElement("span");
  23665. var leftPart = document.createElement("span");
  23666. var rightPart = document.createElement("span");
  23667. rightPart.style.cssFloat = "right";
  23668. leftPart.innerHTML = leftTitle;
  23669. rightPart.innerHTML = rightTitle;
  23670. rightPart.style.maxWidth = "200px";
  23671. container.appendChild(leftPart);
  23672. container.appendChild(rightPart);
  23673. label.appendChild(container);
  23674. root.appendChild(label);
  23675. root.appendChild(document.createElement("br"));
  23676. };
  23677. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  23678. if (typeof tag === "undefined") { tag = null; }
  23679. var label = document.createElement("label");
  23680. var boundingBoxesCheckbox = document.createElement("input");
  23681. boundingBoxesCheckbox.type = "checkbox";
  23682. boundingBoxesCheckbox.checked = initialState;
  23683. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  23684. task(evt.target, tag);
  23685. });
  23686. label.appendChild(boundingBoxesCheckbox);
  23687. label.appendChild(document.createTextNode(title));
  23688. root.appendChild(label);
  23689. root.appendChild(document.createElement("br"));
  23690. };
  23691. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  23692. if (typeof tag === "undefined") { tag = null; }
  23693. var label = document.createElement("label");
  23694. var boundingBoxesRadio = document.createElement("input");
  23695. boundingBoxesRadio.type = "radio";
  23696. boundingBoxesRadio.name = name;
  23697. boundingBoxesRadio.checked = initialState;
  23698. boundingBoxesRadio.addEventListener("change", function (evt) {
  23699. task(evt.target, tag);
  23700. });
  23701. label.appendChild(boundingBoxesRadio);
  23702. label.appendChild(document.createTextNode(title));
  23703. root.appendChild(label);
  23704. root.appendChild(document.createElement("br"));
  23705. };
  23706. DebugLayer.prototype._generateDOMelements = function () {
  23707. var _this = this;
  23708. this._globalDiv.id = "DebugLayer";
  23709. this._globalDiv.style.position = "absolute";
  23710. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  23711. this._globalDiv.style.fontSize = "14px";
  23712. this._globalDiv.style.color = "white";
  23713. this._drawingCanvas = document.createElement("canvas");
  23714. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  23715. this._drawingCanvas.style.position = "absolute";
  23716. this._drawingCanvas.style.pointerEvents = "none";
  23717. this._drawingContext = this._drawingCanvas.getContext("2d");
  23718. this._globalDiv.appendChild(this._drawingCanvas);
  23719. if (this._showUI) {
  23720. var background = "rgba(128, 128, 128, 0.4)";
  23721. var border = "rgb(180, 180, 180) solid 1px";
  23722. this._statsDiv = document.createElement("div");
  23723. this._statsDiv.id = "DebugLayerStats";
  23724. this._statsDiv.style.border = border;
  23725. this._statsDiv.style.position = "absolute";
  23726. this._statsDiv.style.background = background;
  23727. this._statsDiv.style.padding = "0px 0px 0px 5px";
  23728. this._statsDiv.style.pointerEvents = "none";
  23729. this._statsDiv.style.overflowY = "auto";
  23730. this._generateheader(this._statsDiv, "Statistics");
  23731. this._statsSubsetDiv = document.createElement("div");
  23732. this._statsSubsetDiv.style.paddingTop = "5px";
  23733. this._statsSubsetDiv.style.paddingBottom = "5px";
  23734. this._statsDiv.appendChild(this._statsSubsetDiv);
  23735. this._treeDiv = document.createElement("div");
  23736. this._treeDiv.id = "DebugLayerTree";
  23737. this._treeDiv.style.border = border;
  23738. this._treeDiv.style.position = "absolute";
  23739. this._treeDiv.style.background = background;
  23740. this._treeDiv.style.padding = "0px 0px 0px 5px";
  23741. this._treeDiv.style.display = "none";
  23742. this._generateheader(this._treeDiv, "Meshes tree");
  23743. this._treeSubsetDiv = document.createElement("div");
  23744. this._treeSubsetDiv.style.paddingTop = "5px";
  23745. this._treeSubsetDiv.style.paddingRight = "5px";
  23746. this._treeSubsetDiv.style.overflowY = "auto";
  23747. this._treeSubsetDiv.style.maxHeight = "300px";
  23748. this._treeDiv.appendChild(this._treeSubsetDiv);
  23749. this._needToRefreshMeshesTree = true;
  23750. this._logDiv = document.createElement("div");
  23751. this._logDiv.style.border = border;
  23752. this._logDiv.id = "DebugLayerLogs";
  23753. this._logDiv.style.position = "absolute";
  23754. this._logDiv.style.background = background;
  23755. this._logDiv.style.padding = "0px 0px 0px 5px";
  23756. this._logDiv.style.display = "none";
  23757. this._generateheader(this._logDiv, "Logs");
  23758. this._logSubsetDiv = document.createElement("div");
  23759. this._logSubsetDiv.style.height = "127px";
  23760. this._logSubsetDiv.style.paddingTop = "5px";
  23761. this._logSubsetDiv.style.overflowY = "auto";
  23762. this._logSubsetDiv.style.fontSize = "12px";
  23763. this._logSubsetDiv.style.fontFamily = "consolas";
  23764. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  23765. this._logDiv.appendChild(this._logSubsetDiv);
  23766. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  23767. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  23768. };
  23769. this._optionsDiv = document.createElement("div");
  23770. this._optionsDiv.id = "DebugLayerOptions";
  23771. this._optionsDiv.style.border = border;
  23772. this._optionsDiv.style.position = "absolute";
  23773. this._optionsDiv.style.background = background;
  23774. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  23775. this._optionsDiv.style.overflowY = "auto";
  23776. this._generateheader(this._optionsDiv, "Options");
  23777. this._optionsSubsetDiv = document.createElement("div");
  23778. this._optionsSubsetDiv.style.paddingTop = "5px";
  23779. this._optionsSubsetDiv.style.paddingBottom = "5px";
  23780. this._optionsSubsetDiv.style.overflowY = "auto";
  23781. this._optionsSubsetDiv.style.maxHeight = "200px";
  23782. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  23783. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>");
  23784. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  23785. _this._displayStatistics = element.checked;
  23786. });
  23787. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  23788. _this._displayLogs = element.checked;
  23789. });
  23790. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  23791. _this._displayTree = element.checked;
  23792. _this._needToRefreshMeshesTree = true;
  23793. });
  23794. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  23795. _this._scene.forceShowBoundingBoxes = element.checked;
  23796. });
  23797. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  23798. _this._labelsEnabled = element.checked;
  23799. if (!_this._labelsEnabled) {
  23800. _this._clearLabels();
  23801. }
  23802. });
  23803. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  23804. if (element.checked) {
  23805. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  23806. } else {
  23807. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  23808. }
  23809. });
  23810. ;
  23811. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  23812. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>");
  23813. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  23814. if (element.checked) {
  23815. _this._scene.forceWireframe = false;
  23816. _this._scene.forcePointsCloud = false;
  23817. }
  23818. });
  23819. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  23820. if (element.checked) {
  23821. _this._scene.forceWireframe = true;
  23822. _this._scene.forcePointsCloud = false;
  23823. }
  23824. });
  23825. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  23826. if (element.checked) {
  23827. _this._scene.forceWireframe = false;
  23828. _this._scene.forcePointsCloud = true;
  23829. }
  23830. });
  23831. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  23832. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>");
  23833. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  23834. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  23835. });
  23836. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  23837. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  23838. });
  23839. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  23840. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  23841. });
  23842. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  23843. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  23844. });
  23845. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  23846. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  23847. });
  23848. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  23849. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  23850. });
  23851. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  23852. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  23853. });
  23854. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  23855. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  23856. });
  23857. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  23858. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>");
  23859. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  23860. _this._scene.animationsEnabled = element.checked;
  23861. });
  23862. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  23863. _this._scene.collisionsEnabled = element.checked;
  23864. });
  23865. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  23866. _this._scene.fogEnabled = element.checked;
  23867. });
  23868. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  23869. _this._scene.lensFlaresEnabled = element.checked;
  23870. });
  23871. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  23872. _this._scene.lightsEnabled = element.checked;
  23873. });
  23874. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  23875. _this._scene.particlesEnabled = element.checked;
  23876. });
  23877. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  23878. _this._scene.postProcessesEnabled = element.checked;
  23879. });
  23880. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  23881. _this._scene.proceduralTexturesEnabled = element.checked;
  23882. });
  23883. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  23884. _this._scene.renderTargetsEnabled = element.checked;
  23885. });
  23886. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  23887. _this._scene.shadowsEnabled = element.checked;
  23888. });
  23889. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  23890. _this._scene.skeletonsEnabled = element.checked;
  23891. });
  23892. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  23893. _this._scene.texturesEnabled = element.checked;
  23894. });
  23895. this._globalDiv.appendChild(this._statsDiv);
  23896. this._globalDiv.appendChild(this._logDiv);
  23897. this._globalDiv.appendChild(this._optionsDiv);
  23898. this._globalDiv.appendChild(this._treeDiv);
  23899. }
  23900. };
  23901. DebugLayer.prototype._displayStats = function () {
  23902. var scene = this._scene;
  23903. var engine = scene.getEngine();
  23904. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(BABYLON.Tools.GetFps(), 0) + " fps</b><br><br>" + "Total meshes: " + scene.meshes.length + "<br>" + "Total vertices: " + scene.getTotalVertices() + "<br>" + "Active meshes: " + scene.getActiveMeshes().length + "<br>" + "Active vertices: " + scene.getActiveVertices() + "<br>" + "Active bones: " + scene.getActiveBones() + "<br>" + "Active particles: " + scene.getActiveParticles() + "<br><br>" + "Frame duration: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>" + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>" + "<i>Evaluate Active Meshes duration:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>" + "<i>Render Targets duration:</i> " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>" + "<i>Particles duration:</i> " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>" + "<i>Sprites duration:</i> " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br>" + "<i>Render duration:</i> <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b>";
  23905. };
  23906. return DebugLayer;
  23907. })();
  23908. BABYLON.DebugLayer = DebugLayer;
  23909. })(BABYLON || (BABYLON = {}));