babylon.2.0-alpha.debug.js 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var Color3 = (function () {
  4. function Color3(r, g, b) {
  5. if (typeof r === "undefined") { r = 0; }
  6. if (typeof g === "undefined") { g = 0; }
  7. if (typeof b === "undefined") { b = 0; }
  8. this.r = r;
  9. this.g = g;
  10. this.b = b;
  11. }
  12. Color3.prototype.toString = function () {
  13. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  14. };
  15. Color3.prototype.toArray = function (array, index) {
  16. if (index === undefined) {
  17. index = 0;
  18. }
  19. array[index] = this.r;
  20. array[index + 1] = this.g;
  21. array[index + 2] = this.b;
  22. };
  23. Color3.prototype.toColor4 = function (alpha) {
  24. if (typeof alpha === "undefined") { alpha = 1; }
  25. return new Color4(this.r, this.g, this.b, alpha);
  26. };
  27. Color3.prototype.asArray = function () {
  28. var result = [];
  29. this.toArray(result, 0);
  30. return result;
  31. };
  32. Color3.prototype.toLuminance = function () {
  33. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  34. };
  35. Color3.prototype.multiply = function (otherColor) {
  36. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  37. };
  38. Color3.prototype.multiplyToRef = function (otherColor, result) {
  39. result.r = this.r * otherColor.r;
  40. result.g = this.g * otherColor.g;
  41. result.b = this.b * otherColor.b;
  42. };
  43. Color3.prototype.equals = function (otherColor) {
  44. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  45. };
  46. Color3.prototype.scale = function (scale) {
  47. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  48. };
  49. Color3.prototype.scaleToRef = function (scale, result) {
  50. result.r = this.r * scale;
  51. result.g = this.g * scale;
  52. result.b = this.b * scale;
  53. };
  54. Color3.prototype.add = function (otherColor) {
  55. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  56. };
  57. Color3.prototype.addToRef = function (otherColor, result) {
  58. result.r = this.r + otherColor.r;
  59. result.g = this.g + otherColor.g;
  60. result.b = this.b + otherColor.b;
  61. };
  62. Color3.prototype.subtract = function (otherColor) {
  63. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  64. };
  65. Color3.prototype.subtractToRef = function (otherColor, result) {
  66. result.r = this.r - otherColor.r;
  67. result.g = this.g - otherColor.g;
  68. result.b = this.b - otherColor.b;
  69. };
  70. Color3.prototype.clone = function () {
  71. return new Color3(this.r, this.g, this.b);
  72. };
  73. Color3.prototype.copyFrom = function (source) {
  74. this.r = source.r;
  75. this.g = source.g;
  76. this.b = source.b;
  77. };
  78. Color3.prototype.copyFromFloats = function (r, g, b) {
  79. this.r = r;
  80. this.g = g;
  81. this.b = b;
  82. };
  83. Color3.FromArray = function (array) {
  84. return new Color3(array[0], array[1], array[2]);
  85. };
  86. Color3.FromInts = function (r, g, b) {
  87. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  88. };
  89. Color3.Lerp = function (start, end, amount) {
  90. var r = start.r + ((end.r - start.r) * amount);
  91. var g = start.g + ((end.g - start.g) * amount);
  92. var b = start.b + ((end.b - start.b) * amount);
  93. return new Color3(r, g, b);
  94. };
  95. Color3.Red = function () {
  96. return new Color3(1, 0, 0);
  97. };
  98. Color3.Green = function () {
  99. return new Color3(0, 1, 0);
  100. };
  101. Color3.Blue = function () {
  102. return new Color3(0, 0, 1);
  103. };
  104. Color3.Black = function () {
  105. return new Color3(0, 0, 0);
  106. };
  107. Color3.White = function () {
  108. return new Color3(1, 1, 1);
  109. };
  110. Color3.Purple = function () {
  111. return new Color3(0.5, 0, 0.5);
  112. };
  113. Color3.Magenta = function () {
  114. return new Color3(1, 0, 1);
  115. };
  116. Color3.Yellow = function () {
  117. return new Color3(1, 1, 0);
  118. };
  119. Color3.Gray = function () {
  120. return new Color3(0.5, 0.5, 0.5);
  121. };
  122. return Color3;
  123. })();
  124. BABYLON.Color3 = Color3;
  125. var Color4 = (function () {
  126. function Color4(r, g, b, a) {
  127. this.r = r;
  128. this.g = g;
  129. this.b = b;
  130. this.a = a;
  131. }
  132. Color4.prototype.addInPlace = function (right) {
  133. this.r += right.r;
  134. this.g += right.g;
  135. this.b += right.b;
  136. this.a += right.a;
  137. };
  138. Color4.prototype.asArray = function () {
  139. var result = [];
  140. this.toArray(result, 0);
  141. return result;
  142. };
  143. Color4.prototype.toArray = function (array, index) {
  144. if (index === undefined) {
  145. index = 0;
  146. }
  147. array[index] = this.r;
  148. array[index + 1] = this.g;
  149. array[index + 2] = this.b;
  150. array[index + 3] = this.a;
  151. };
  152. Color4.prototype.add = function (right) {
  153. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  154. };
  155. Color4.prototype.subtract = function (right) {
  156. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  157. };
  158. Color4.prototype.subtractToRef = function (right, result) {
  159. result.r = this.r - right.r;
  160. result.g = this.g - right.g;
  161. result.b = this.b - right.b;
  162. result.a = this.a - right.a;
  163. };
  164. Color4.prototype.scale = function (scale) {
  165. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  166. };
  167. Color4.prototype.scaleToRef = function (scale, result) {
  168. result.r = this.r * scale;
  169. result.g = this.g * scale;
  170. result.b = this.b * scale;
  171. result.a = this.a * scale;
  172. };
  173. Color4.prototype.toString = function () {
  174. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  175. };
  176. Color4.prototype.clone = function () {
  177. return new Color4(this.r, this.g, this.b, this.a);
  178. };
  179. Color4.Lerp = function (left, right, amount) {
  180. var result = new Color4(0, 0, 0, 0);
  181. BABYLON.Color4.LerpToRef(left, right, amount, result);
  182. return result;
  183. };
  184. Color4.LerpToRef = function (left, right, amount, result) {
  185. result.r = left.r + (right.r - left.r) * amount;
  186. result.g = left.g + (right.g - left.g) * amount;
  187. result.b = left.b + (right.b - left.b) * amount;
  188. result.a = left.a + (right.a - left.a) * amount;
  189. };
  190. Color4.FromArray = function (array, offset) {
  191. if (typeof offset === "undefined") { offset = 0; }
  192. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  193. };
  194. Color4.FromInts = function (r, g, b, a) {
  195. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  196. };
  197. return Color4;
  198. })();
  199. BABYLON.Color4 = Color4;
  200. var Vector2 = (function () {
  201. function Vector2(x, y) {
  202. this.x = x;
  203. this.y = y;
  204. }
  205. Vector2.prototype.toString = function () {
  206. return "{X: " + this.x + " Y:" + this.y + "}";
  207. };
  208. Vector2.prototype.toArray = function (array, index) {
  209. if (index === undefined) {
  210. index = 0;
  211. }
  212. array[index] = this.x;
  213. array[index + 1] = this.y;
  214. };
  215. Vector2.prototype.asArray = function () {
  216. var result = [];
  217. this.toArray(result, 0);
  218. return result;
  219. };
  220. Vector2.prototype.copyFrom = function (source) {
  221. this.x = source.x;
  222. this.y = source.y;
  223. };
  224. Vector2.prototype.copyFromFloats = function (x, y) {
  225. this.x = x;
  226. this.y = y;
  227. };
  228. Vector2.prototype.add = function (otherVector) {
  229. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  230. };
  231. Vector2.prototype.addVector3 = function (otherVector) {
  232. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  233. };
  234. Vector2.prototype.subtract = function (otherVector) {
  235. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  236. };
  237. Vector2.prototype.subtractInPlace = function (otherVector) {
  238. this.x -= otherVector.x;
  239. this.y -= otherVector.y;
  240. };
  241. Vector2.prototype.multiplyInPlace = function (otherVector) {
  242. this.x *= otherVector.x;
  243. this.y *= otherVector.y;
  244. };
  245. Vector2.prototype.multiply = function (otherVector) {
  246. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  247. };
  248. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  249. result.x = this.x * otherVector.x;
  250. result.y = this.y * otherVector.y;
  251. };
  252. Vector2.prototype.multiplyByFloats = function (x, y) {
  253. return new Vector2(this.x * x, this.y * y);
  254. };
  255. Vector2.prototype.divide = function (otherVector) {
  256. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  257. };
  258. Vector2.prototype.divideToRef = function (otherVector, result) {
  259. result.x = this.x / otherVector.x;
  260. result.y = this.y / otherVector.y;
  261. };
  262. Vector2.prototype.negate = function () {
  263. return new Vector2(-this.x, -this.y);
  264. };
  265. Vector2.prototype.scaleInPlace = function (scale) {
  266. this.x *= scale;
  267. this.y *= scale;
  268. return this;
  269. };
  270. Vector2.prototype.scale = function (scale) {
  271. return new Vector2(this.x * scale, this.y * scale);
  272. };
  273. Vector2.prototype.equals = function (otherVector) {
  274. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  275. };
  276. Vector2.prototype.length = function () {
  277. return Math.sqrt(this.x * this.x + this.y * this.y);
  278. };
  279. Vector2.prototype.lengthSquared = function () {
  280. return (this.x * this.x + this.y * this.y);
  281. };
  282. Vector2.prototype.normalize = function () {
  283. var len = this.length();
  284. if (len === 0)
  285. return this;
  286. var num = 1.0 / len;
  287. this.x *= num;
  288. this.y *= num;
  289. return this;
  290. };
  291. Vector2.prototype.clone = function () {
  292. return new Vector2(this.x, this.y);
  293. };
  294. Vector2.Zero = function () {
  295. return new Vector2(0, 0);
  296. };
  297. Vector2.FromArray = function (array, offset) {
  298. if (!offset) {
  299. offset = 0;
  300. }
  301. return new Vector2(array[offset], array[offset + 1]);
  302. };
  303. Vector2.FromArrayToRef = function (array, offset, result) {
  304. result.x = array[offset];
  305. result.y = array[offset + 1];
  306. };
  307. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  308. var squared = amount * amount;
  309. var cubed = amount * squared;
  310. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  311. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  312. return new Vector2(x, y);
  313. };
  314. Vector2.Clamp = function (value, min, max) {
  315. var x = value.x;
  316. x = (x > max.x) ? max.x : x;
  317. x = (x < min.x) ? min.x : x;
  318. var y = value.y;
  319. y = (y > max.y) ? max.y : y;
  320. y = (y < min.y) ? min.y : y;
  321. return new Vector2(x, y);
  322. };
  323. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  324. var squared = amount * amount;
  325. var cubed = amount * squared;
  326. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  327. var part2 = (-2.0 * cubed) + (3.0 * squared);
  328. var part3 = (cubed - (2.0 * squared)) + amount;
  329. var part4 = cubed - squared;
  330. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  331. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  332. return new Vector2(x, y);
  333. };
  334. Vector2.Lerp = function (start, end, amount) {
  335. var x = start.x + ((end.x - start.x) * amount);
  336. var y = start.y + ((end.y - start.y) * amount);
  337. return new Vector2(x, y);
  338. };
  339. Vector2.Dot = function (left, right) {
  340. return left.x * right.x + left.y * right.y;
  341. };
  342. Vector2.Normalize = function (vector) {
  343. var newVector = vector.clone();
  344. newVector.normalize();
  345. return newVector;
  346. };
  347. Vector2.Minimize = function (left, right) {
  348. var x = (left.x < right.x) ? left.x : right.x;
  349. var y = (left.y < right.y) ? left.y : right.y;
  350. return new Vector2(x, y);
  351. };
  352. Vector2.Maximize = function (left, right) {
  353. var x = (left.x > right.x) ? left.x : right.x;
  354. var y = (left.y > right.y) ? left.y : right.y;
  355. return new Vector2(x, y);
  356. };
  357. Vector2.Transform = function (vector, transformation) {
  358. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  359. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  360. return new Vector2(x, y);
  361. };
  362. Vector2.Distance = function (value1, value2) {
  363. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  364. };
  365. Vector2.DistanceSquared = function (value1, value2) {
  366. var x = value1.x - value2.x;
  367. var y = value1.y - value2.y;
  368. return (x * x) + (y * y);
  369. };
  370. return Vector2;
  371. })();
  372. BABYLON.Vector2 = Vector2;
  373. var Vector3 = (function () {
  374. function Vector3(x, y, z) {
  375. this.x = x;
  376. this.y = y;
  377. this.z = z;
  378. }
  379. Vector3.prototype.toString = function () {
  380. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  381. };
  382. Vector3.prototype.asArray = function () {
  383. var result = [];
  384. this.toArray(result, 0);
  385. return result;
  386. };
  387. Vector3.prototype.toArray = function (array, index) {
  388. if (index === undefined) {
  389. index = 0;
  390. }
  391. array[index] = this.x;
  392. array[index + 1] = this.y;
  393. array[index + 2] = this.z;
  394. };
  395. Vector3.prototype.addInPlace = function (otherVector) {
  396. this.x += otherVector.x;
  397. this.y += otherVector.y;
  398. this.z += otherVector.z;
  399. };
  400. Vector3.prototype.add = function (otherVector) {
  401. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  402. };
  403. Vector3.prototype.addToRef = function (otherVector, result) {
  404. result.x = this.x + otherVector.x;
  405. result.y = this.y + otherVector.y;
  406. result.z = this.z + otherVector.z;
  407. };
  408. Vector3.prototype.subtractInPlace = function (otherVector) {
  409. this.x -= otherVector.x;
  410. this.y -= otherVector.y;
  411. this.z -= otherVector.z;
  412. };
  413. Vector3.prototype.subtract = function (otherVector) {
  414. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  415. };
  416. Vector3.prototype.subtractToRef = function (otherVector, result) {
  417. result.x = this.x - otherVector.x;
  418. result.y = this.y - otherVector.y;
  419. result.z = this.z - otherVector.z;
  420. };
  421. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  422. return new Vector3(this.x - x, this.y - y, this.z - z);
  423. };
  424. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  425. result.x = this.x - x;
  426. result.y = this.y - y;
  427. result.z = this.z - z;
  428. };
  429. Vector3.prototype.negate = function () {
  430. return new Vector3(-this.x, -this.y, -this.z);
  431. };
  432. Vector3.prototype.scaleInPlace = function (scale) {
  433. this.x *= scale;
  434. this.y *= scale;
  435. this.z *= scale;
  436. return this;
  437. };
  438. Vector3.prototype.scale = function (scale) {
  439. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  440. };
  441. Vector3.prototype.scaleToRef = function (scale, result) {
  442. result.x = this.x * scale;
  443. result.y = this.y * scale;
  444. result.z = this.z * scale;
  445. };
  446. Vector3.prototype.equals = function (otherVector) {
  447. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  448. };
  449. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  450. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  451. };
  452. Vector3.prototype.equalsToFloats = function (x, y, z) {
  453. return this.x === x && this.y === y && this.z === z;
  454. };
  455. Vector3.prototype.multiplyInPlace = function (otherVector) {
  456. this.x *= otherVector.x;
  457. this.y *= otherVector.y;
  458. this.z *= otherVector.z;
  459. };
  460. Vector3.prototype.multiply = function (otherVector) {
  461. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  462. };
  463. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  464. result.x = this.x * otherVector.x;
  465. result.y = this.y * otherVector.y;
  466. result.z = this.z * otherVector.z;
  467. };
  468. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  469. return new Vector3(this.x * x, this.y * y, this.z * z);
  470. };
  471. Vector3.prototype.divide = function (otherVector) {
  472. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  473. };
  474. Vector3.prototype.divideToRef = function (otherVector, result) {
  475. result.x = this.x / otherVector.x;
  476. result.y = this.y / otherVector.y;
  477. result.z = this.z / otherVector.z;
  478. };
  479. Vector3.prototype.MinimizeInPlace = function (other) {
  480. if (other.x < this.x)
  481. this.x = other.x;
  482. if (other.y < this.y)
  483. this.y = other.y;
  484. if (other.z < this.z)
  485. this.z = other.z;
  486. };
  487. Vector3.prototype.MaximizeInPlace = function (other) {
  488. if (other.x > this.x)
  489. this.x = other.x;
  490. if (other.y > this.y)
  491. this.y = other.y;
  492. if (other.z > this.z)
  493. this.z = other.z;
  494. };
  495. Vector3.prototype.length = function () {
  496. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  497. };
  498. Vector3.prototype.lengthSquared = function () {
  499. return (this.x * this.x + this.y * this.y + this.z * this.z);
  500. };
  501. Vector3.prototype.normalize = function () {
  502. var len = this.length();
  503. if (len === 0)
  504. return this;
  505. var num = 1.0 / len;
  506. this.x *= num;
  507. this.y *= num;
  508. this.z *= num;
  509. return this;
  510. };
  511. Vector3.prototype.clone = function () {
  512. return new Vector3(this.x, this.y, this.z);
  513. };
  514. Vector3.prototype.copyFrom = function (source) {
  515. this.x = source.x;
  516. this.y = source.y;
  517. this.z = source.z;
  518. };
  519. Vector3.prototype.copyFromFloats = function (x, y, z) {
  520. this.x = x;
  521. this.y = y;
  522. this.z = z;
  523. };
  524. Vector3.FromArray = function (array, offset) {
  525. if (!offset) {
  526. offset = 0;
  527. }
  528. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  529. };
  530. Vector3.FromArrayToRef = function (array, offset, result) {
  531. result.x = array[offset];
  532. result.y = array[offset + 1];
  533. result.z = array[offset + 2];
  534. };
  535. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  536. result.x = array[offset];
  537. result.y = array[offset + 1];
  538. result.z = array[offset + 2];
  539. };
  540. Vector3.FromFloatsToRef = function (x, y, z, result) {
  541. result.x = x;
  542. result.y = y;
  543. result.z = z;
  544. };
  545. Vector3.Zero = function () {
  546. return new Vector3(0, 0, 0);
  547. };
  548. Vector3.Up = function () {
  549. return new Vector3(0, 1.0, 0);
  550. };
  551. Vector3.TransformCoordinates = function (vector, transformation) {
  552. var result = Vector3.Zero();
  553. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  554. return result;
  555. };
  556. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  557. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  558. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  559. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  560. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  561. result.x = x / w;
  562. result.y = y / w;
  563. result.z = z / w;
  564. };
  565. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  566. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  567. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  568. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  569. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  570. result.x = rx / rw;
  571. result.y = ry / rw;
  572. result.z = rz / rw;
  573. };
  574. Vector3.TransformNormal = function (vector, transformation) {
  575. var result = Vector3.Zero();
  576. Vector3.TransformNormalToRef(vector, transformation, result);
  577. return result;
  578. };
  579. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  580. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  581. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  582. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  583. };
  584. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  585. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  586. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  587. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  588. };
  589. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  590. var squared = amount * amount;
  591. var cubed = amount * squared;
  592. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  593. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  594. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  595. return new Vector3(x, y, z);
  596. };
  597. Vector3.Clamp = function (value, min, max) {
  598. var x = value.x;
  599. x = (x > max.x) ? max.x : x;
  600. x = (x < min.x) ? min.x : x;
  601. var y = value.y;
  602. y = (y > max.y) ? max.y : y;
  603. y = (y < min.y) ? min.y : y;
  604. var z = value.z;
  605. z = (z > max.z) ? max.z : z;
  606. z = (z < min.z) ? min.z : z;
  607. return new Vector3(x, y, z);
  608. };
  609. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  610. var squared = amount * amount;
  611. var cubed = amount * squared;
  612. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  613. var part2 = (-2.0 * cubed) + (3.0 * squared);
  614. var part3 = (cubed - (2.0 * squared)) + amount;
  615. var part4 = cubed - squared;
  616. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  617. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  618. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  619. return new Vector3(x, y, z);
  620. };
  621. Vector3.Lerp = function (start, end, amount) {
  622. var x = start.x + ((end.x - start.x) * amount);
  623. var y = start.y + ((end.y - start.y) * amount);
  624. var z = start.z + ((end.z - start.z) * amount);
  625. return new Vector3(x, y, z);
  626. };
  627. Vector3.Dot = function (left, right) {
  628. return (left.x * right.x + left.y * right.y + left.z * right.z);
  629. };
  630. Vector3.Cross = function (left, right) {
  631. var result = Vector3.Zero();
  632. Vector3.CrossToRef(left, right, result);
  633. return result;
  634. };
  635. Vector3.CrossToRef = function (left, right, result) {
  636. result.x = left.y * right.z - left.z * right.y;
  637. result.y = left.z * right.x - left.x * right.z;
  638. result.z = left.x * right.y - left.y * right.x;
  639. };
  640. Vector3.Normalize = function (vector) {
  641. var result = Vector3.Zero();
  642. Vector3.NormalizeToRef(vector, result);
  643. return result;
  644. };
  645. Vector3.NormalizeToRef = function (vector, result) {
  646. result.copyFrom(vector);
  647. result.normalize();
  648. };
  649. Vector3.Project = function (vector, world, transform, viewport) {
  650. var cw = viewport.width;
  651. var ch = viewport.height;
  652. var cx = viewport.x;
  653. var cy = viewport.y;
  654. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  655. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  656. return Vector3.TransformCoordinates(vector, finalMatrix);
  657. };
  658. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  659. var matrix = world.multiply(view).multiply(projection);
  660. matrix.invert();
  661. source.x = source.x / viewportWidth * 2 - 1;
  662. source.y = -(source.y / viewportHeight * 2 - 1);
  663. var vector = BABYLON.Vector3.TransformCoordinates(source, matrix);
  664. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  665. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  666. vector = vector.scale(1.0 / num);
  667. }
  668. return vector;
  669. };
  670. Vector3.Minimize = function (left, right) {
  671. var min = left.clone();
  672. min.MinimizeInPlace(right);
  673. return min;
  674. };
  675. Vector3.Maximize = function (left, right) {
  676. var max = left.clone();
  677. max.MaximizeInPlace(right);
  678. return max;
  679. };
  680. Vector3.Distance = function (value1, value2) {
  681. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  682. };
  683. Vector3.DistanceSquared = function (value1, value2) {
  684. var x = value1.x - value2.x;
  685. var y = value1.y - value2.y;
  686. var z = value1.z - value2.z;
  687. return (x * x) + (y * y) + (z * z);
  688. };
  689. Vector3.Center = function (value1, value2) {
  690. var center = value1.add(value2);
  691. center.scaleInPlace(0.5);
  692. return center;
  693. };
  694. return Vector3;
  695. })();
  696. BABYLON.Vector3 = Vector3;
  697. var Vector4 = (function () {
  698. function Vector4(x, y, z, w) {
  699. this.x = x;
  700. this.y = y;
  701. this.z = z;
  702. this.w = w;
  703. }
  704. Vector4.prototype.toString = function () {
  705. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  706. };
  707. Vector4.prototype.asArray = function () {
  708. var result = [];
  709. this.toArray(result, 0);
  710. return result;
  711. };
  712. Vector4.prototype.toArray = function (array, index) {
  713. if (index === undefined) {
  714. index = 0;
  715. }
  716. array[index] = this.x;
  717. array[index + 1] = this.y;
  718. array[index + 2] = this.z;
  719. array[index + 3] = this.w;
  720. };
  721. Vector4.prototype.addInPlace = function (otherVector) {
  722. this.x += otherVector.x;
  723. this.y += otherVector.y;
  724. this.z += otherVector.z;
  725. this.w += otherVector.w;
  726. };
  727. Vector4.prototype.add = function (otherVector) {
  728. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  729. };
  730. Vector4.prototype.addToRef = function (otherVector, result) {
  731. result.x = this.x + otherVector.x;
  732. result.y = this.y + otherVector.y;
  733. result.z = this.z + otherVector.z;
  734. result.w = this.w + otherVector.w;
  735. };
  736. Vector4.prototype.subtractInPlace = function (otherVector) {
  737. this.x -= otherVector.x;
  738. this.y -= otherVector.y;
  739. this.z -= otherVector.z;
  740. this.w -= otherVector.w;
  741. };
  742. Vector4.prototype.subtract = function (otherVector) {
  743. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  744. };
  745. Vector4.prototype.subtractToRef = function (otherVector, result) {
  746. result.x = this.x - otherVector.x;
  747. result.y = this.y - otherVector.y;
  748. result.z = this.z - otherVector.z;
  749. result.w = this.w - otherVector.w;
  750. };
  751. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  752. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  753. };
  754. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  755. result.x = this.x - x;
  756. result.y = this.y - y;
  757. result.z = this.z - z;
  758. result.w = this.w - w;
  759. };
  760. Vector4.prototype.negate = function () {
  761. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  762. };
  763. Vector4.prototype.scaleInPlace = function (scale) {
  764. this.x *= scale;
  765. this.y *= scale;
  766. this.z *= scale;
  767. this.w *= scale;
  768. return this;
  769. };
  770. Vector4.prototype.scale = function (scale) {
  771. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  772. };
  773. Vector4.prototype.scaleToRef = function (scale, result) {
  774. result.x = this.x * scale;
  775. result.y = this.y * scale;
  776. result.z = this.z * scale;
  777. result.w = this.w * scale;
  778. };
  779. Vector4.prototype.equals = function (otherVector) {
  780. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  781. };
  782. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  783. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  784. };
  785. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  786. return this.x === x && this.y === y && this.z === z && this.w === w;
  787. };
  788. Vector4.prototype.multiplyInPlace = function (otherVector) {
  789. this.x *= otherVector.x;
  790. this.y *= otherVector.y;
  791. this.z *= otherVector.z;
  792. this.w *= otherVector.w;
  793. };
  794. Vector4.prototype.multiply = function (otherVector) {
  795. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  796. };
  797. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  798. result.x = this.x * otherVector.x;
  799. result.y = this.y * otherVector.y;
  800. result.z = this.z * otherVector.z;
  801. result.w = this.w * otherVector.w;
  802. };
  803. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  804. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  805. };
  806. Vector4.prototype.divide = function (otherVector) {
  807. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  808. };
  809. Vector4.prototype.divideToRef = function (otherVector, result) {
  810. result.x = this.x / otherVector.x;
  811. result.y = this.y / otherVector.y;
  812. result.z = this.z / otherVector.z;
  813. result.w = this.w / otherVector.w;
  814. };
  815. Vector4.prototype.MinimizeInPlace = function (other) {
  816. if (other.x < this.x)
  817. this.x = other.x;
  818. if (other.y < this.y)
  819. this.y = other.y;
  820. if (other.z < this.z)
  821. this.z = other.z;
  822. if (other.w < this.w)
  823. this.w = other.w;
  824. };
  825. Vector4.prototype.MaximizeInPlace = function (other) {
  826. if (other.x > this.x)
  827. this.x = other.x;
  828. if (other.y > this.y)
  829. this.y = other.y;
  830. if (other.z > this.z)
  831. this.z = other.z;
  832. if (other.w > this.w)
  833. this.w = other.w;
  834. };
  835. Vector4.prototype.length = function () {
  836. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  837. };
  838. Vector4.prototype.lengthSquared = function () {
  839. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  840. };
  841. Vector4.prototype.normalize = function () {
  842. var len = this.length();
  843. if (len === 0)
  844. return this;
  845. var num = 1.0 / len;
  846. this.x *= num;
  847. this.y *= num;
  848. this.z *= num;
  849. this.w *= num;
  850. return this;
  851. };
  852. Vector4.prototype.clone = function () {
  853. return new Vector4(this.x, this.y, this.z, this.w);
  854. };
  855. Vector4.prototype.copyFrom = function (source) {
  856. this.x = source.x;
  857. this.y = source.y;
  858. this.z = source.z;
  859. this.w = source.w;
  860. };
  861. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  862. this.x = x;
  863. this.y = y;
  864. this.z = z;
  865. this.w = w;
  866. };
  867. Vector4.FromArray = function (array, offset) {
  868. if (!offset) {
  869. offset = 0;
  870. }
  871. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  872. };
  873. Vector4.FromArrayToRef = function (array, offset, result) {
  874. result.x = array[offset];
  875. result.y = array[offset + 1];
  876. result.z = array[offset + 2];
  877. result.w = array[offset + 3];
  878. };
  879. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  880. result.x = array[offset];
  881. result.y = array[offset + 1];
  882. result.z = array[offset + 2];
  883. result.w = array[offset + 3];
  884. };
  885. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  886. result.x = x;
  887. result.y = y;
  888. result.z = z;
  889. result.w = w;
  890. };
  891. Vector4.Zero = function () {
  892. return new Vector4(0, 0, 0, 0);
  893. };
  894. Vector4.Normalize = function (vector) {
  895. var result = Vector4.Zero();
  896. Vector4.NormalizeToRef(vector, result);
  897. return result;
  898. };
  899. Vector4.NormalizeToRef = function (vector, result) {
  900. result.copyFrom(vector);
  901. result.normalize();
  902. };
  903. Vector4.Minimize = function (left, right) {
  904. var min = left.clone();
  905. min.MinimizeInPlace(right);
  906. return min;
  907. };
  908. Vector4.Maximize = function (left, right) {
  909. var max = left.clone();
  910. max.MaximizeInPlace(right);
  911. return max;
  912. };
  913. Vector4.Distance = function (value1, value2) {
  914. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  915. };
  916. Vector4.DistanceSquared = function (value1, value2) {
  917. var x = value1.x - value2.x;
  918. var y = value1.y - value2.y;
  919. var z = value1.z - value2.z;
  920. var w = value1.w - value2.w;
  921. return (x * x) + (y * y) + (z * z) + (w * w);
  922. };
  923. Vector4.Center = function (value1, value2) {
  924. var center = value1.add(value2);
  925. center.scaleInPlace(0.5);
  926. return center;
  927. };
  928. return Vector4;
  929. })();
  930. BABYLON.Vector4 = Vector4;
  931. var Quaternion = (function () {
  932. function Quaternion(x, y, z, w) {
  933. if (typeof x === "undefined") { x = 0; }
  934. if (typeof y === "undefined") { y = 0; }
  935. if (typeof z === "undefined") { z = 0; }
  936. if (typeof w === "undefined") { w = 1; }
  937. this.x = x;
  938. this.y = y;
  939. this.z = z;
  940. this.w = w;
  941. }
  942. Quaternion.prototype.toString = function () {
  943. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  944. };
  945. Quaternion.prototype.asArray = function () {
  946. return [this.x, this.y, this.z, this.w];
  947. };
  948. Quaternion.prototype.equals = function (otherQuaternion) {
  949. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  950. };
  951. Quaternion.prototype.clone = function () {
  952. return new Quaternion(this.x, this.y, this.z, this.w);
  953. };
  954. Quaternion.prototype.copyFrom = function (other) {
  955. this.x = other.x;
  956. this.y = other.y;
  957. this.z = other.z;
  958. this.w = other.w;
  959. };
  960. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  961. this.x = x;
  962. this.y = y;
  963. this.z = z;
  964. this.w = w;
  965. };
  966. Quaternion.prototype.add = function (other) {
  967. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  968. };
  969. Quaternion.prototype.subtract = function (other) {
  970. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  971. };
  972. Quaternion.prototype.scale = function (value) {
  973. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  974. };
  975. Quaternion.prototype.multiply = function (q1) {
  976. var result = new Quaternion(0, 0, 0, 1.0);
  977. this.multiplyToRef(q1, result);
  978. return result;
  979. };
  980. Quaternion.prototype.multiplyToRef = function (q1, result) {
  981. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  982. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  983. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  984. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  985. };
  986. Quaternion.prototype.length = function () {
  987. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  988. };
  989. Quaternion.prototype.normalize = function () {
  990. var length = 1.0 / this.length();
  991. this.x *= length;
  992. this.y *= length;
  993. this.z *= length;
  994. this.w *= length;
  995. };
  996. Quaternion.prototype.toEulerAngles = function () {
  997. var result = Vector3.Zero();
  998. this.toEulerAnglesToRef(result);
  999. return result;
  1000. };
  1001. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1002. var qx = this.x;
  1003. var qy = this.y;
  1004. var qz = this.z;
  1005. var qw = this.w;
  1006. var qxy = qx * qy;
  1007. var qxz = qx * qz;
  1008. var qwy = qw * qy;
  1009. var qwz = qw * qz;
  1010. var qwx = qw * qx;
  1011. var qyz = qy * qz;
  1012. var sqx = qx * qx;
  1013. var sqy = qy * qy;
  1014. var determinant = sqx + sqy;
  1015. if (determinant != 0.000 && determinant != 1.000) {
  1016. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1017. result.y = Math.acos(1 - 2 * determinant);
  1018. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1019. } else {
  1020. if (determinant == 0.000) {
  1021. result.x = 0.0;
  1022. result.y = 0.0;
  1023. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz);
  1024. } else {
  1025. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz);
  1026. result.y = Math.PI;
  1027. result.z = 0.0;
  1028. }
  1029. }
  1030. };
  1031. Quaternion.prototype.toRotationMatrix = function (result) {
  1032. var xx = this.x * this.x;
  1033. var yy = this.y * this.y;
  1034. var zz = this.z * this.z;
  1035. var xy = this.x * this.y;
  1036. var zw = this.z * this.w;
  1037. var zx = this.z * this.x;
  1038. var yw = this.y * this.w;
  1039. var yz = this.y * this.z;
  1040. var xw = this.x * this.w;
  1041. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1042. result.m[1] = 2.0 * (xy + zw);
  1043. result.m[2] = 2.0 * (zx - yw);
  1044. result.m[3] = 0;
  1045. result.m[4] = 2.0 * (xy - zw);
  1046. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1047. result.m[6] = 2.0 * (yz + xw);
  1048. result.m[7] = 0;
  1049. result.m[8] = 2.0 * (zx + yw);
  1050. result.m[9] = 2.0 * (yz - xw);
  1051. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1052. result.m[11] = 0;
  1053. result.m[12] = 0;
  1054. result.m[13] = 0;
  1055. result.m[14] = 0;
  1056. result.m[15] = 1.0;
  1057. };
  1058. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1059. var data = matrix.m;
  1060. var m11 = data[0], m12 = data[4], m13 = data[8];
  1061. var m21 = data[1], m22 = data[5], m23 = data[9];
  1062. var m31 = data[2], m32 = data[6], m33 = data[10];
  1063. var trace = m11 + m22 + m33;
  1064. var s;
  1065. if (trace > 0) {
  1066. s = 0.5 / Math.sqrt(trace + 1.0);
  1067. this.w = 0.25 / s;
  1068. this.x = (m32 - m23) * s;
  1069. this.y = (m13 - m31) * s;
  1070. this.z = (m21 - m12) * s;
  1071. return;
  1072. }
  1073. if (m11 > m22 && m11 > m33) {
  1074. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1075. this.w = (m32 - m23) / s;
  1076. this.x = 0.25 * s;
  1077. this.y = (m12 + m21) / s;
  1078. this.z = (m13 + m31) / s;
  1079. return;
  1080. }
  1081. if (m22 > m33) {
  1082. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1083. this.w = (m13 - m31) / s;
  1084. this.x = (m12 + m21) / s;
  1085. this.y = 0.25 * s;
  1086. this.z = (m23 + m32) / s;
  1087. return;
  1088. }
  1089. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1090. this.w = (m21 - m12) / s;
  1091. this.x = (m13 + m31) / s;
  1092. this.y = (m23 + m32) / s;
  1093. this.z = 0.25 * s;
  1094. };
  1095. Quaternion.Inverse = function (q) {
  1096. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1097. };
  1098. Quaternion.RotationAxis = function (axis, angle) {
  1099. var result = new Quaternion();
  1100. var sin = Math.sin(angle / 2);
  1101. result.w = Math.cos(angle / 2);
  1102. result.x = axis.x * sin;
  1103. result.y = axis.y * sin;
  1104. result.z = axis.z * sin;
  1105. return result;
  1106. };
  1107. Quaternion.FromArray = function (array, offset) {
  1108. if (!offset) {
  1109. offset = 0;
  1110. }
  1111. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1112. };
  1113. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1114. var result = new Quaternion();
  1115. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1116. return result;
  1117. };
  1118. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1119. var halfRoll = roll * 0.5;
  1120. var halfPitch = pitch * 0.5;
  1121. var halfYaw = yaw * 0.5;
  1122. var sinRoll = Math.sin(halfRoll);
  1123. var cosRoll = Math.cos(halfRoll);
  1124. var sinPitch = Math.sin(halfPitch);
  1125. var cosPitch = Math.cos(halfPitch);
  1126. var sinYaw = Math.sin(halfYaw);
  1127. var cosYaw = Math.cos(halfYaw);
  1128. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1129. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1130. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1131. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1132. };
  1133. Quaternion.Slerp = function (left, right, amount) {
  1134. var num2;
  1135. var num3;
  1136. var num = amount;
  1137. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1138. var flag = false;
  1139. if (num4 < 0) {
  1140. flag = true;
  1141. num4 = -num4;
  1142. }
  1143. if (num4 > 0.999999) {
  1144. num3 = 1 - num;
  1145. num2 = flag ? -num : num;
  1146. } else {
  1147. var num5 = Math.acos(num4);
  1148. var num6 = (1.0 / Math.sin(num5));
  1149. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1150. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1151. }
  1152. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1153. };
  1154. return Quaternion;
  1155. })();
  1156. BABYLON.Quaternion = Quaternion;
  1157. var Matrix = (function () {
  1158. function Matrix() {
  1159. this.m = new Float32Array(16);
  1160. }
  1161. Matrix.prototype.isIdentity = function () {
  1162. if (this.m[0] != 1.0 || this.m[5] != 1.0 || this.m[10] != 1.0 || this.m[15] != 1.0)
  1163. return false;
  1164. if (this.m[1] != 0.0 || this.m[2] != 0.0 || this.m[3] != 0.0 || this.m[4] != 0.0 || this.m[6] != 0.0 || this.m[7] != 0.0 || this.m[8] != 0.0 || this.m[9] != 0.0 || this.m[11] != 0.0 || this.m[12] != 0.0 || this.m[13] != 0.0 || this.m[14] != 0.0)
  1165. return false;
  1166. return true;
  1167. };
  1168. Matrix.prototype.determinant = function () {
  1169. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1170. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1171. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1172. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1173. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1174. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1175. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1176. };
  1177. Matrix.prototype.toArray = function () {
  1178. return this.m;
  1179. };
  1180. Matrix.prototype.asArray = function () {
  1181. return this.toArray();
  1182. };
  1183. Matrix.prototype.invert = function () {
  1184. this.invertToRef(this);
  1185. };
  1186. Matrix.prototype.invertToRef = function (other) {
  1187. var l1 = this.m[0];
  1188. var l2 = this.m[1];
  1189. var l3 = this.m[2];
  1190. var l4 = this.m[3];
  1191. var l5 = this.m[4];
  1192. var l6 = this.m[5];
  1193. var l7 = this.m[6];
  1194. var l8 = this.m[7];
  1195. var l9 = this.m[8];
  1196. var l10 = this.m[9];
  1197. var l11 = this.m[10];
  1198. var l12 = this.m[11];
  1199. var l13 = this.m[12];
  1200. var l14 = this.m[13];
  1201. var l15 = this.m[14];
  1202. var l16 = this.m[15];
  1203. var l17 = (l11 * l16) - (l12 * l15);
  1204. var l18 = (l10 * l16) - (l12 * l14);
  1205. var l19 = (l10 * l15) - (l11 * l14);
  1206. var l20 = (l9 * l16) - (l12 * l13);
  1207. var l21 = (l9 * l15) - (l11 * l13);
  1208. var l22 = (l9 * l14) - (l10 * l13);
  1209. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1210. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1211. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1212. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1213. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1214. var l28 = (l7 * l16) - (l8 * l15);
  1215. var l29 = (l6 * l16) - (l8 * l14);
  1216. var l30 = (l6 * l15) - (l7 * l14);
  1217. var l31 = (l5 * l16) - (l8 * l13);
  1218. var l32 = (l5 * l15) - (l7 * l13);
  1219. var l33 = (l5 * l14) - (l6 * l13);
  1220. var l34 = (l7 * l12) - (l8 * l11);
  1221. var l35 = (l6 * l12) - (l8 * l10);
  1222. var l36 = (l6 * l11) - (l7 * l10);
  1223. var l37 = (l5 * l12) - (l8 * l9);
  1224. var l38 = (l5 * l11) - (l7 * l9);
  1225. var l39 = (l5 * l10) - (l6 * l9);
  1226. other.m[0] = l23 * l27;
  1227. other.m[4] = l24 * l27;
  1228. other.m[8] = l25 * l27;
  1229. other.m[12] = l26 * l27;
  1230. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1231. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1232. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1233. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1234. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1235. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1236. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1237. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1238. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1239. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1240. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1241. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1242. };
  1243. Matrix.prototype.setTranslation = function (vector3) {
  1244. this.m[12] = vector3.x;
  1245. this.m[13] = vector3.y;
  1246. this.m[14] = vector3.z;
  1247. };
  1248. Matrix.prototype.multiply = function (other) {
  1249. var result = new Matrix();
  1250. this.multiplyToRef(other, result);
  1251. return result;
  1252. };
  1253. Matrix.prototype.copyFrom = function (other) {
  1254. for (var index = 0; index < 16; index++) {
  1255. this.m[index] = other.m[index];
  1256. }
  1257. };
  1258. Matrix.prototype.copyToArray = function (array, offset) {
  1259. if (typeof offset === "undefined") { offset = 0; }
  1260. for (var index = 0; index < 16; index++) {
  1261. array[offset + index] = this.m[index];
  1262. }
  1263. };
  1264. Matrix.prototype.multiplyToRef = function (other, result) {
  1265. this.multiplyToArray(other, result.m, 0);
  1266. };
  1267. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1268. var tm0 = this.m[0];
  1269. var tm1 = this.m[1];
  1270. var tm2 = this.m[2];
  1271. var tm3 = this.m[3];
  1272. var tm4 = this.m[4];
  1273. var tm5 = this.m[5];
  1274. var tm6 = this.m[6];
  1275. var tm7 = this.m[7];
  1276. var tm8 = this.m[8];
  1277. var tm9 = this.m[9];
  1278. var tm10 = this.m[10];
  1279. var tm11 = this.m[11];
  1280. var tm12 = this.m[12];
  1281. var tm13 = this.m[13];
  1282. var tm14 = this.m[14];
  1283. var tm15 = this.m[15];
  1284. var om0 = other.m[0];
  1285. var om1 = other.m[1];
  1286. var om2 = other.m[2];
  1287. var om3 = other.m[3];
  1288. var om4 = other.m[4];
  1289. var om5 = other.m[5];
  1290. var om6 = other.m[6];
  1291. var om7 = other.m[7];
  1292. var om8 = other.m[8];
  1293. var om9 = other.m[9];
  1294. var om10 = other.m[10];
  1295. var om11 = other.m[11];
  1296. var om12 = other.m[12];
  1297. var om13 = other.m[13];
  1298. var om14 = other.m[14];
  1299. var om15 = other.m[15];
  1300. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1301. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1302. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1303. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1304. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1305. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1306. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1307. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1308. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1309. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1310. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1311. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1312. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1313. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1314. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1315. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1316. };
  1317. Matrix.prototype.equals = function (value) {
  1318. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1319. };
  1320. Matrix.prototype.clone = function () {
  1321. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1322. };
  1323. Matrix.FromArray = function (array, offset) {
  1324. var result = new Matrix();
  1325. if (!offset) {
  1326. offset = 0;
  1327. }
  1328. Matrix.FromArrayToRef(array, offset, result);
  1329. return result;
  1330. };
  1331. Matrix.FromArrayToRef = function (array, offset, result) {
  1332. for (var index = 0; index < 16; index++) {
  1333. result.m[index] = array[index + offset];
  1334. }
  1335. };
  1336. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1337. result.m[0] = initialM11;
  1338. result.m[1] = initialM12;
  1339. result.m[2] = initialM13;
  1340. result.m[3] = initialM14;
  1341. result.m[4] = initialM21;
  1342. result.m[5] = initialM22;
  1343. result.m[6] = initialM23;
  1344. result.m[7] = initialM24;
  1345. result.m[8] = initialM31;
  1346. result.m[9] = initialM32;
  1347. result.m[10] = initialM33;
  1348. result.m[11] = initialM34;
  1349. result.m[12] = initialM41;
  1350. result.m[13] = initialM42;
  1351. result.m[14] = initialM43;
  1352. result.m[15] = initialM44;
  1353. };
  1354. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1355. var result = new Matrix();
  1356. result.m[0] = initialM11;
  1357. result.m[1] = initialM12;
  1358. result.m[2] = initialM13;
  1359. result.m[3] = initialM14;
  1360. result.m[4] = initialM21;
  1361. result.m[5] = initialM22;
  1362. result.m[6] = initialM23;
  1363. result.m[7] = initialM24;
  1364. result.m[8] = initialM31;
  1365. result.m[9] = initialM32;
  1366. result.m[10] = initialM33;
  1367. result.m[11] = initialM34;
  1368. result.m[12] = initialM41;
  1369. result.m[13] = initialM42;
  1370. result.m[14] = initialM43;
  1371. result.m[15] = initialM44;
  1372. return result;
  1373. };
  1374. Matrix.Identity = function () {
  1375. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1376. };
  1377. Matrix.IdentityToRef = function (result) {
  1378. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1379. };
  1380. Matrix.Zero = function () {
  1381. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1382. };
  1383. Matrix.RotationX = function (angle) {
  1384. var result = new Matrix();
  1385. Matrix.RotationXToRef(angle, result);
  1386. return result;
  1387. };
  1388. Matrix.RotationXToRef = function (angle, result) {
  1389. var s = Math.sin(angle);
  1390. var c = Math.cos(angle);
  1391. result.m[0] = 1.0;
  1392. result.m[15] = 1.0;
  1393. result.m[5] = c;
  1394. result.m[10] = c;
  1395. result.m[9] = -s;
  1396. result.m[6] = s;
  1397. result.m[1] = 0;
  1398. result.m[2] = 0;
  1399. result.m[3] = 0;
  1400. result.m[4] = 0;
  1401. result.m[7] = 0;
  1402. result.m[8] = 0;
  1403. result.m[11] = 0;
  1404. result.m[12] = 0;
  1405. result.m[13] = 0;
  1406. result.m[14] = 0;
  1407. };
  1408. Matrix.RotationY = function (angle) {
  1409. var result = new Matrix();
  1410. Matrix.RotationYToRef(angle, result);
  1411. return result;
  1412. };
  1413. Matrix.RotationYToRef = function (angle, result) {
  1414. var s = Math.sin(angle);
  1415. var c = Math.cos(angle);
  1416. result.m[5] = 1.0;
  1417. result.m[15] = 1.0;
  1418. result.m[0] = c;
  1419. result.m[2] = -s;
  1420. result.m[8] = s;
  1421. result.m[10] = c;
  1422. result.m[1] = 0;
  1423. result.m[3] = 0;
  1424. result.m[4] = 0;
  1425. result.m[6] = 0;
  1426. result.m[7] = 0;
  1427. result.m[9] = 0;
  1428. result.m[11] = 0;
  1429. result.m[12] = 0;
  1430. result.m[13] = 0;
  1431. result.m[14] = 0;
  1432. };
  1433. Matrix.RotationZ = function (angle) {
  1434. var result = new Matrix();
  1435. Matrix.RotationZToRef(angle, result);
  1436. return result;
  1437. };
  1438. Matrix.RotationZToRef = function (angle, result) {
  1439. var s = Math.sin(angle);
  1440. var c = Math.cos(angle);
  1441. result.m[10] = 1.0;
  1442. result.m[15] = 1.0;
  1443. result.m[0] = c;
  1444. result.m[1] = s;
  1445. result.m[4] = -s;
  1446. result.m[5] = c;
  1447. result.m[2] = 0;
  1448. result.m[3] = 0;
  1449. result.m[6] = 0;
  1450. result.m[7] = 0;
  1451. result.m[8] = 0;
  1452. result.m[9] = 0;
  1453. result.m[11] = 0;
  1454. result.m[12] = 0;
  1455. result.m[13] = 0;
  1456. result.m[14] = 0;
  1457. };
  1458. Matrix.RotationAxis = function (axis, angle) {
  1459. var s = Math.sin(-angle);
  1460. var c = Math.cos(-angle);
  1461. var c1 = 1 - c;
  1462. axis.normalize();
  1463. var result = Matrix.Zero();
  1464. result.m[0] = (axis.x * axis.x) * c1 + c;
  1465. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1466. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1467. result.m[3] = 0.0;
  1468. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1469. result.m[5] = (axis.y * axis.y) * c1 + c;
  1470. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1471. result.m[7] = 0.0;
  1472. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1473. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1474. result.m[10] = (axis.z * axis.z) * c1 + c;
  1475. result.m[11] = 0.0;
  1476. result.m[15] = 1.0;
  1477. return result;
  1478. };
  1479. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1480. var result = new Matrix();
  1481. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1482. return result;
  1483. };
  1484. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1485. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1486. this._tempQuaternion.toRotationMatrix(result);
  1487. };
  1488. Matrix.Scaling = function (x, y, z) {
  1489. var result = Matrix.Zero();
  1490. Matrix.ScalingToRef(x, y, z, result);
  1491. return result;
  1492. };
  1493. Matrix.ScalingToRef = function (x, y, z, result) {
  1494. result.m[0] = x;
  1495. result.m[1] = 0;
  1496. result.m[2] = 0;
  1497. result.m[3] = 0;
  1498. result.m[4] = 0;
  1499. result.m[5] = y;
  1500. result.m[6] = 0;
  1501. result.m[7] = 0;
  1502. result.m[8] = 0;
  1503. result.m[9] = 0;
  1504. result.m[10] = z;
  1505. result.m[11] = 0;
  1506. result.m[12] = 0;
  1507. result.m[13] = 0;
  1508. result.m[14] = 0;
  1509. result.m[15] = 1.0;
  1510. };
  1511. Matrix.Translation = function (x, y, z) {
  1512. var result = Matrix.Identity();
  1513. Matrix.TranslationToRef(x, y, z, result);
  1514. return result;
  1515. };
  1516. Matrix.TranslationToRef = function (x, y, z, result) {
  1517. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1518. };
  1519. Matrix.LookAtLH = function (eye, target, up) {
  1520. var result = Matrix.Zero();
  1521. Matrix.LookAtLHToRef(eye, target, up, result);
  1522. return result;
  1523. };
  1524. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1525. target.subtractToRef(eye, this._zAxis);
  1526. this._zAxis.normalize();
  1527. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1528. this._xAxis.normalize();
  1529. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1530. this._yAxis.normalize();
  1531. var ex = -Vector3.Dot(this._xAxis, eye);
  1532. var ey = -Vector3.Dot(this._yAxis, eye);
  1533. var ez = -Vector3.Dot(this._zAxis, eye);
  1534. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1535. };
  1536. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1537. var hw = 2.0 / width;
  1538. var hh = 2.0 / height;
  1539. var id = 1.0 / (zfar - znear);
  1540. var nid = znear / (znear - zfar);
  1541. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1542. };
  1543. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1544. var matrix = Matrix.Zero();
  1545. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1546. return matrix;
  1547. };
  1548. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1549. result.m[0] = 2.0 / (right - left);
  1550. result.m[1] = result.m[2] = result.m[3] = 0;
  1551. result.m[5] = 2.0 / (top - bottom);
  1552. result.m[4] = result.m[6] = result.m[7] = 0;
  1553. result.m[10] = -1.0 / (znear - zfar);
  1554. result.m[8] = result.m[9] = result.m[11] = 0;
  1555. result.m[12] = (left + right) / (left - right);
  1556. result.m[13] = (top + bottom) / (bottom - top);
  1557. result.m[14] = znear / (znear - zfar);
  1558. result.m[15] = 1.0;
  1559. };
  1560. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1561. var matrix = Matrix.Zero();
  1562. matrix.m[0] = (2.0 * znear) / width;
  1563. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1564. matrix.m[5] = (2.0 * znear) / height;
  1565. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1566. matrix.m[10] = -zfar / (znear - zfar);
  1567. matrix.m[8] = matrix.m[9] = 0.0;
  1568. matrix.m[11] = 1.0;
  1569. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1570. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1571. return matrix;
  1572. };
  1573. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1574. var matrix = Matrix.Zero();
  1575. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1576. return matrix;
  1577. };
  1578. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1579. var tan = 1.0 / (Math.tan(fov * 0.5));
  1580. result.m[0] = tan / aspect;
  1581. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1582. result.m[5] = tan;
  1583. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1584. result.m[8] = result.m[9] = 0.0;
  1585. result.m[10] = -zfar / (znear - zfar);
  1586. result.m[11] = 1.0;
  1587. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1588. result.m[14] = (znear * zfar) / (znear - zfar);
  1589. };
  1590. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1591. var cw = viewport.width;
  1592. var ch = viewport.height;
  1593. var cx = viewport.x;
  1594. var cy = viewport.y;
  1595. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  1596. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1597. };
  1598. Matrix.Transpose = function (matrix) {
  1599. var result = new Matrix();
  1600. result.m[0] = matrix.m[0];
  1601. result.m[1] = matrix.m[4];
  1602. result.m[2] = matrix.m[8];
  1603. result.m[3] = matrix.m[12];
  1604. result.m[4] = matrix.m[1];
  1605. result.m[5] = matrix.m[5];
  1606. result.m[6] = matrix.m[9];
  1607. result.m[7] = matrix.m[13];
  1608. result.m[8] = matrix.m[2];
  1609. result.m[9] = matrix.m[6];
  1610. result.m[10] = matrix.m[10];
  1611. result.m[11] = matrix.m[14];
  1612. result.m[12] = matrix.m[3];
  1613. result.m[13] = matrix.m[7];
  1614. result.m[14] = matrix.m[11];
  1615. result.m[15] = matrix.m[15];
  1616. return result;
  1617. };
  1618. Matrix.Reflection = function (plane) {
  1619. var matrix = new Matrix();
  1620. Matrix.ReflectionToRef(plane, matrix);
  1621. return matrix;
  1622. };
  1623. Matrix.ReflectionToRef = function (plane, result) {
  1624. plane.normalize();
  1625. var x = plane.normal.x;
  1626. var y = plane.normal.y;
  1627. var z = plane.normal.z;
  1628. var temp = -2 * x;
  1629. var temp2 = -2 * y;
  1630. var temp3 = -2 * z;
  1631. result.m[0] = (temp * x) + 1;
  1632. result.m[1] = temp2 * x;
  1633. result.m[2] = temp3 * x;
  1634. result.m[3] = 0.0;
  1635. result.m[4] = temp * y;
  1636. result.m[5] = (temp2 * y) + 1;
  1637. result.m[6] = temp3 * y;
  1638. result.m[7] = 0.0;
  1639. result.m[8] = temp * z;
  1640. result.m[9] = temp2 * z;
  1641. result.m[10] = (temp3 * z) + 1;
  1642. result.m[11] = 0.0;
  1643. result.m[12] = temp * plane.d;
  1644. result.m[13] = temp2 * plane.d;
  1645. result.m[14] = temp3 * plane.d;
  1646. result.m[15] = 1.0;
  1647. };
  1648. Matrix._tempQuaternion = new Quaternion();
  1649. Matrix._xAxis = Vector3.Zero();
  1650. Matrix._yAxis = Vector3.Zero();
  1651. Matrix._zAxis = Vector3.Zero();
  1652. return Matrix;
  1653. })();
  1654. BABYLON.Matrix = Matrix;
  1655. var Plane = (function () {
  1656. function Plane(a, b, c, d) {
  1657. this.normal = new Vector3(a, b, c);
  1658. this.d = d;
  1659. }
  1660. Plane.prototype.asArray = function () {
  1661. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1662. };
  1663. Plane.prototype.clone = function () {
  1664. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1665. };
  1666. Plane.prototype.normalize = function () {
  1667. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1668. var magnitude = 0;
  1669. if (norm != 0) {
  1670. magnitude = 1.0 / norm;
  1671. }
  1672. this.normal.x *= magnitude;
  1673. this.normal.y *= magnitude;
  1674. this.normal.z *= magnitude;
  1675. this.d *= magnitude;
  1676. };
  1677. Plane.prototype.transform = function (transformation) {
  1678. var transposedMatrix = BABYLON.Matrix.Transpose(transformation);
  1679. var x = this.normal.x;
  1680. var y = this.normal.y;
  1681. var z = this.normal.z;
  1682. var d = this.d;
  1683. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1684. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1685. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1686. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1687. return new BABYLON.Plane(normalX, normalY, normalZ, finalD);
  1688. };
  1689. Plane.prototype.dotCoordinate = function (point) {
  1690. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1691. };
  1692. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1693. var x1 = point2.x - point1.x;
  1694. var y1 = point2.y - point1.y;
  1695. var z1 = point2.z - point1.z;
  1696. var x2 = point3.x - point1.x;
  1697. var y2 = point3.y - point1.y;
  1698. var z2 = point3.z - point1.z;
  1699. var yz = (y1 * z2) - (z1 * y2);
  1700. var xz = (z1 * x2) - (x1 * z2);
  1701. var xy = (x1 * y2) - (y1 * x2);
  1702. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1703. var invPyth;
  1704. if (pyth != 0) {
  1705. invPyth = 1.0 / pyth;
  1706. } else {
  1707. invPyth = 0;
  1708. }
  1709. this.normal.x = yz * invPyth;
  1710. this.normal.y = xz * invPyth;
  1711. this.normal.z = xy * invPyth;
  1712. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1713. };
  1714. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1715. var dot = Vector3.Dot(this.normal, direction);
  1716. return (dot <= epsilon);
  1717. };
  1718. Plane.prototype.signedDistanceTo = function (point) {
  1719. return Vector3.Dot(point, this.normal) + this.d;
  1720. };
  1721. Plane.FromArray = function (array) {
  1722. return new BABYLON.Plane(array[0], array[1], array[2], array[3]);
  1723. };
  1724. Plane.FromPoints = function (point1, point2, point3) {
  1725. var result = new BABYLON.Plane(0, 0, 0, 0);
  1726. result.copyFromPoints(point1, point2, point3);
  1727. return result;
  1728. };
  1729. Plane.FromPositionAndNormal = function (origin, normal) {
  1730. var result = new BABYLON.Plane(0, 0, 0, 0);
  1731. normal.normalize();
  1732. result.normal = normal;
  1733. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1734. return result;
  1735. };
  1736. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1737. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1738. return Vector3.Dot(point, normal) + d;
  1739. };
  1740. return Plane;
  1741. })();
  1742. BABYLON.Plane = Plane;
  1743. var Viewport = (function () {
  1744. function Viewport(x, y, width, height) {
  1745. this.x = x;
  1746. this.y = y;
  1747. this.width = width;
  1748. this.height = height;
  1749. }
  1750. Viewport.prototype.toGlobal = function (engine) {
  1751. var width = engine.getRenderWidth();
  1752. var height = engine.getRenderHeight();
  1753. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1754. };
  1755. return Viewport;
  1756. })();
  1757. BABYLON.Viewport = Viewport;
  1758. var Frustum = (function () {
  1759. function Frustum() {
  1760. }
  1761. Frustum.GetPlanes = function (transform) {
  1762. var frustumPlanes = [];
  1763. for (var index = 0; index < 6; index++) {
  1764. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1765. }
  1766. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1767. return frustumPlanes;
  1768. };
  1769. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1770. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1771. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1772. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1773. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1774. frustumPlanes[0].normalize();
  1775. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1776. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1777. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1778. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1779. frustumPlanes[1].normalize();
  1780. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1781. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1782. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1783. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1784. frustumPlanes[2].normalize();
  1785. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1786. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1787. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1788. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1789. frustumPlanes[3].normalize();
  1790. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1791. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1792. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1793. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1794. frustumPlanes[4].normalize();
  1795. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1796. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1797. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1798. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1799. frustumPlanes[5].normalize();
  1800. };
  1801. return Frustum;
  1802. })();
  1803. BABYLON.Frustum = Frustum;
  1804. var Ray = (function () {
  1805. function Ray(origin, direction) {
  1806. this.origin = origin;
  1807. this.direction = direction;
  1808. }
  1809. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1810. var d = 0.0;
  1811. var maxValue = Number.MAX_VALUE;
  1812. if (Math.abs(this.direction.x) < 0.0000001) {
  1813. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1814. return false;
  1815. }
  1816. } else {
  1817. var inv = 1.0 / this.direction.x;
  1818. var min = (minimum.x - this.origin.x) * inv;
  1819. var max = (maximum.x - this.origin.x) * inv;
  1820. if (min > max) {
  1821. var temp = min;
  1822. min = max;
  1823. max = temp;
  1824. }
  1825. d = Math.max(min, d);
  1826. maxValue = Math.min(max, maxValue);
  1827. if (d > maxValue) {
  1828. return false;
  1829. }
  1830. }
  1831. if (Math.abs(this.direction.y) < 0.0000001) {
  1832. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1833. return false;
  1834. }
  1835. } else {
  1836. inv = 1.0 / this.direction.y;
  1837. min = (minimum.y - this.origin.y) * inv;
  1838. max = (maximum.y - this.origin.y) * inv;
  1839. if (min > max) {
  1840. temp = min;
  1841. min = max;
  1842. max = temp;
  1843. }
  1844. d = Math.max(min, d);
  1845. maxValue = Math.min(max, maxValue);
  1846. if (d > maxValue) {
  1847. return false;
  1848. }
  1849. }
  1850. if (Math.abs(this.direction.z) < 0.0000001) {
  1851. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1852. return false;
  1853. }
  1854. } else {
  1855. inv = 1.0 / this.direction.z;
  1856. min = (minimum.z - this.origin.z) * inv;
  1857. max = (maximum.z - this.origin.z) * inv;
  1858. if (min > max) {
  1859. temp = min;
  1860. min = max;
  1861. max = temp;
  1862. }
  1863. d = Math.max(min, d);
  1864. maxValue = Math.min(max, maxValue);
  1865. if (d > maxValue) {
  1866. return false;
  1867. }
  1868. }
  1869. return true;
  1870. };
  1871. Ray.prototype.intersectsBox = function (box) {
  1872. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1873. };
  1874. Ray.prototype.intersectsSphere = function (sphere) {
  1875. var x = sphere.center.x - this.origin.x;
  1876. var y = sphere.center.y - this.origin.y;
  1877. var z = sphere.center.z - this.origin.z;
  1878. var pyth = (x * x) + (y * y) + (z * z);
  1879. var rr = sphere.radius * sphere.radius;
  1880. if (pyth <= rr) {
  1881. return true;
  1882. }
  1883. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1884. if (dot < 0.0) {
  1885. return false;
  1886. }
  1887. var temp = pyth - (dot * dot);
  1888. return temp <= rr;
  1889. };
  1890. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1891. if (!this._edge1) {
  1892. this._edge1 = BABYLON.Vector3.Zero();
  1893. this._edge2 = BABYLON.Vector3.Zero();
  1894. this._pvec = BABYLON.Vector3.Zero();
  1895. this._tvec = BABYLON.Vector3.Zero();
  1896. this._qvec = BABYLON.Vector3.Zero();
  1897. }
  1898. vertex1.subtractToRef(vertex0, this._edge1);
  1899. vertex2.subtractToRef(vertex0, this._edge2);
  1900. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1901. var det = Vector3.Dot(this._edge1, this._pvec);
  1902. if (det === 0) {
  1903. return null;
  1904. }
  1905. var invdet = 1 / det;
  1906. this.origin.subtractToRef(vertex0, this._tvec);
  1907. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1908. if (bu < 0 || bu > 1.0) {
  1909. return null;
  1910. }
  1911. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1912. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1913. if (bv < 0 || bu + bv > 1.0) {
  1914. return null;
  1915. }
  1916. return new BABYLON.IntersectionInfo(bu, bv, Vector3.Dot(this._edge2, this._qvec) * invdet);
  1917. };
  1918. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1919. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1920. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1921. var direction = end.subtract(start);
  1922. direction.normalize();
  1923. return new Ray(start, direction);
  1924. };
  1925. Ray.Transform = function (ray, matrix) {
  1926. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  1927. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  1928. return new Ray(newOrigin, newDirection);
  1929. };
  1930. return Ray;
  1931. })();
  1932. BABYLON.Ray = Ray;
  1933. (function (Space) {
  1934. Space[Space["LOCAL"] = 0] = "LOCAL";
  1935. Space[Space["WORLD"] = 1] = "WORLD";
  1936. })(BABYLON.Space || (BABYLON.Space = {}));
  1937. var Space = BABYLON.Space;
  1938. var Axis = (function () {
  1939. function Axis() {
  1940. }
  1941. Axis.X = new BABYLON.Vector3(1, 0, 0);
  1942. Axis.Y = new BABYLON.Vector3(0, 1, 0);
  1943. Axis.Z = new BABYLON.Vector3(0, 0, 1);
  1944. return Axis;
  1945. })();
  1946. BABYLON.Axis = Axis;
  1947. ;
  1948. })(BABYLON || (BABYLON = {}));
  1949. var BABYLON;
  1950. (function (BABYLON) {
  1951. var screenshotCanvas;
  1952. var fpsRange = 60;
  1953. var previousFramesDuration = [];
  1954. var fps = 60;
  1955. var deltaTime = 0;
  1956. var cloneValue = function (source, destinationObject) {
  1957. if (!source)
  1958. return null;
  1959. if (source instanceof BABYLON.Mesh) {
  1960. return null;
  1961. }
  1962. if (source instanceof BABYLON.SubMesh) {
  1963. return source.clone(destinationObject);
  1964. } else if (source.clone) {
  1965. return source.clone();
  1966. }
  1967. return null;
  1968. };
  1969. var Tools = (function () {
  1970. function Tools() {
  1971. }
  1972. Tools.GetFilename = function (path) {
  1973. var index = path.lastIndexOf("/");
  1974. if (index < 0)
  1975. return path;
  1976. return path.substring(index + 1);
  1977. };
  1978. Tools.GetDOMTextContent = function (element) {
  1979. var result = "";
  1980. var child = element.firstChild;
  1981. while (child) {
  1982. if (child.nodeType == 3) {
  1983. result += child.textContent;
  1984. }
  1985. child = child.nextSibling;
  1986. }
  1987. return result;
  1988. };
  1989. Tools.ToDegrees = function (angle) {
  1990. return angle * 180 / Math.PI;
  1991. };
  1992. Tools.ToRadians = function (angle) {
  1993. return angle * Math.PI / 180;
  1994. };
  1995. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  1996. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1997. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1998. for (var index = indexStart; index < indexStart + indexCount; index++) {
  1999. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2000. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2001. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2002. }
  2003. return {
  2004. minimum: minimum,
  2005. maximum: maximum
  2006. };
  2007. };
  2008. Tools.ExtractMinAndMax = function (positions, start, count) {
  2009. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2010. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2011. for (var index = start; index < start + count; index++) {
  2012. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2013. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2014. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2015. }
  2016. return {
  2017. minimum: minimum,
  2018. maximum: maximum
  2019. };
  2020. };
  2021. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2022. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2023. return undefined;
  2024. return Array.isArray(obj) ? obj : [obj];
  2025. };
  2026. Tools.GetPointerPrefix = function () {
  2027. var eventPrefix = "pointer";
  2028. if (!navigator.pointerEnabled) {
  2029. eventPrefix = "mouse";
  2030. }
  2031. return eventPrefix;
  2032. };
  2033. Tools.QueueNewFrame = function (func) {
  2034. if (window.requestAnimationFrame)
  2035. window.requestAnimationFrame(func);
  2036. else if (window.msRequestAnimationFrame)
  2037. window.msRequestAnimationFrame(func);
  2038. else if (window.webkitRequestAnimationFrame)
  2039. window.webkitRequestAnimationFrame(func);
  2040. else if (window.mozRequestAnimationFrame)
  2041. window.mozRequestAnimationFrame(func);
  2042. else if (window.oRequestAnimationFrame)
  2043. window.oRequestAnimationFrame(func);
  2044. else {
  2045. window.setTimeout(func, 16);
  2046. }
  2047. };
  2048. Tools.RequestFullscreen = function (element) {
  2049. if (element.requestFullscreen)
  2050. element.requestFullscreen();
  2051. else if (element.msRequestFullscreen)
  2052. element.msRequestFullscreen();
  2053. else if (element.webkitRequestFullscreen)
  2054. element.webkitRequestFullscreen();
  2055. else if (element.mozRequestFullScreen)
  2056. element.mozRequestFullScreen();
  2057. };
  2058. Tools.ExitFullscreen = function () {
  2059. if (document.exitFullscreen) {
  2060. document.exitFullscreen();
  2061. } else if (document.mozCancelFullScreen) {
  2062. document.mozCancelFullScreen();
  2063. } else if (document.webkitCancelFullScreen) {
  2064. document.webkitCancelFullScreen();
  2065. } else if (document.msCancelFullScreen) {
  2066. document.msCancelFullScreen();
  2067. }
  2068. };
  2069. Tools.CleanUrl = function (url) {
  2070. url = url.replace(/#/mg, "%23");
  2071. return url;
  2072. };
  2073. Tools.LoadImage = function (url, onload, onerror, database) {
  2074. url = Tools.CleanUrl(url);
  2075. var img = new Image();
  2076. if (url.substr(0, 5) != "data:")
  2077. img.crossOrigin = 'anonymous';
  2078. img.onload = function () {
  2079. onload(img);
  2080. };
  2081. img.onerror = function (err) {
  2082. onerror(img, err);
  2083. };
  2084. var noIndexedDB = function () {
  2085. img.src = url;
  2086. };
  2087. var loadFromIndexedDB = function () {
  2088. database.loadImageFromDB(url, img);
  2089. };
  2090. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2091. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2092. } else {
  2093. if (url.indexOf("file:") === -1) {
  2094. noIndexedDB();
  2095. } else {
  2096. try {
  2097. var textureName = url.substring(5);
  2098. var blobURL;
  2099. try {
  2100. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2101. } catch (ex) {
  2102. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2103. }
  2104. img.src = blobURL;
  2105. } catch (e) {
  2106. Tools.Log("Error while trying to load texture: " + textureName);
  2107. img.src = null;
  2108. }
  2109. }
  2110. }
  2111. return img;
  2112. };
  2113. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2114. url = Tools.CleanUrl(url);
  2115. var noIndexedDB = function () {
  2116. var request = new XMLHttpRequest();
  2117. var loadUrl = Tools.BaseUrl + url;
  2118. request.open('GET', loadUrl, true);
  2119. if (useArrayBuffer) {
  2120. request.responseType = "arraybuffer";
  2121. }
  2122. request.onprogress = progressCallBack;
  2123. request.onreadystatechange = function () {
  2124. if (request.readyState == 4) {
  2125. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2126. callback(!useArrayBuffer ? request.responseText : request.response);
  2127. } else {
  2128. if (onError) {
  2129. onError();
  2130. } else {
  2131. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2132. }
  2133. }
  2134. }
  2135. };
  2136. request.send(null);
  2137. };
  2138. var loadFromIndexedDB = function () {
  2139. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2140. };
  2141. if (url.indexOf("file:") !== -1) {
  2142. var fileName = url.substring(5);
  2143. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2144. } else {
  2145. if (database && database.enableSceneOffline) {
  2146. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2147. } else {
  2148. noIndexedDB();
  2149. }
  2150. }
  2151. };
  2152. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2153. var reader = new FileReader();
  2154. reader.onload = function (e) {
  2155. callback(e.target.result);
  2156. };
  2157. reader.onprogress = progressCallback;
  2158. reader.readAsDataURL(fileToLoad);
  2159. };
  2160. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2161. var reader = new FileReader();
  2162. reader.onload = function (e) {
  2163. callback(e.target.result);
  2164. };
  2165. reader.onprogress = progressCallBack;
  2166. if (!useArrayBuffer) {
  2167. reader.readAsText(fileToLoad);
  2168. } else {
  2169. reader.readAsArrayBuffer(fileToLoad);
  2170. }
  2171. };
  2172. Tools.CheckExtends = function (v, min, max) {
  2173. if (v.x < min.x)
  2174. min.x = v.x;
  2175. if (v.y < min.y)
  2176. min.y = v.y;
  2177. if (v.z < min.z)
  2178. min.z = v.z;
  2179. if (v.x > max.x)
  2180. max.x = v.x;
  2181. if (v.y > max.y)
  2182. max.y = v.y;
  2183. if (v.z > max.z)
  2184. max.z = v.z;
  2185. };
  2186. Tools.WithinEpsilon = function (a, b) {
  2187. var num = a - b;
  2188. return -1.401298E-45 <= num && num <= 1.401298E-45;
  2189. };
  2190. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2191. for (var prop in source) {
  2192. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2193. continue;
  2194. }
  2195. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2196. continue;
  2197. }
  2198. var sourceValue = source[prop];
  2199. var typeOfSourceValue = typeof sourceValue;
  2200. if (typeOfSourceValue == "function") {
  2201. continue;
  2202. }
  2203. if (typeOfSourceValue == "object") {
  2204. if (sourceValue instanceof Array) {
  2205. destination[prop] = [];
  2206. if (sourceValue.length > 0) {
  2207. if (typeof sourceValue[0] == "object") {
  2208. for (var index = 0; index < sourceValue.length; index++) {
  2209. var clonedValue = cloneValue(sourceValue[index], destination);
  2210. if (destination[prop].indexOf(clonedValue) === -1) {
  2211. destination[prop].push(clonedValue);
  2212. }
  2213. }
  2214. } else {
  2215. destination[prop] = sourceValue.slice(0);
  2216. }
  2217. }
  2218. } else {
  2219. destination[prop] = cloneValue(sourceValue, destination);
  2220. }
  2221. } else {
  2222. destination[prop] = sourceValue;
  2223. }
  2224. }
  2225. };
  2226. Tools.IsEmpty = function (obj) {
  2227. for (var i in obj) {
  2228. return false;
  2229. }
  2230. return true;
  2231. };
  2232. Tools.RegisterTopRootEvents = function (events) {
  2233. for (var index = 0; index < events.length; index++) {
  2234. var event = events[index];
  2235. window.addEventListener(event.name, event.handler, false);
  2236. try {
  2237. if (window.parent) {
  2238. window.parent.addEventListener(event.name, event.handler, false);
  2239. }
  2240. } catch (e) {
  2241. }
  2242. }
  2243. };
  2244. Tools.UnregisterTopRootEvents = function (events) {
  2245. for (var index = 0; index < events.length; index++) {
  2246. var event = events[index];
  2247. window.removeEventListener(event.name, event.handler);
  2248. try {
  2249. if (window.parent) {
  2250. window.parent.removeEventListener(event.name, event.handler);
  2251. }
  2252. } catch (e) {
  2253. }
  2254. }
  2255. };
  2256. Tools.GetFps = function () {
  2257. return fps;
  2258. };
  2259. Tools.GetDeltaTime = function () {
  2260. return deltaTime;
  2261. };
  2262. Tools._MeasureFps = function () {
  2263. previousFramesDuration.push(Tools.Now);
  2264. var length = previousFramesDuration.length;
  2265. if (length >= 2) {
  2266. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  2267. }
  2268. if (length >= fpsRange) {
  2269. if (length > fpsRange) {
  2270. previousFramesDuration.splice(0, 1);
  2271. length = previousFramesDuration.length;
  2272. }
  2273. var sum = 0;
  2274. for (var id = 0; id < length - 1; id++) {
  2275. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  2276. }
  2277. fps = 1000.0 / (sum / (length - 1));
  2278. }
  2279. };
  2280. Tools.CreateScreenshot = function (engine, camera, size) {
  2281. var width;
  2282. var height;
  2283. var scene = camera.getScene();
  2284. var previousCamera = null;
  2285. if (scene.activeCamera !== camera) {
  2286. previousCamera = scene.activeCamera;
  2287. scene.activeCamera = camera;
  2288. }
  2289. if (size.precision) {
  2290. width = Math.round(engine.getRenderWidth() * size.precision);
  2291. height = Math.round(width / engine.getAspectRatio(camera));
  2292. size = { width: width, height: height };
  2293. } else if (size.width && size.height) {
  2294. width = size.width;
  2295. height = size.height;
  2296. } else if (size.width && !size.height) {
  2297. width = size.width;
  2298. height = Math.round(width / engine.getAspectRatio(camera));
  2299. size = { width: width, height: height };
  2300. } else if (size.height && !size.width) {
  2301. height = size.height;
  2302. width = Math.round(height * engine.getAspectRatio(camera));
  2303. size = { width: width, height: height };
  2304. } else if (!isNaN(size)) {
  2305. height = size;
  2306. width = size;
  2307. } else {
  2308. Tools.Error("Invalid 'size' parameter !");
  2309. return;
  2310. }
  2311. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2312. texture.renderList = engine.scenes[0].meshes;
  2313. texture.onAfterRender = function () {
  2314. var numberOfChannelsByLine = width * 4;
  2315. var halfHeight = height / 2;
  2316. var data = engine.readPixels(0, 0, width, height);
  2317. for (var i = 0; i < halfHeight; i++) {
  2318. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2319. var currentCell = j + i * numberOfChannelsByLine;
  2320. var targetLine = height - i - 1;
  2321. var targetCell = j + targetLine * numberOfChannelsByLine;
  2322. var temp = data[currentCell];
  2323. data[currentCell] = data[targetCell];
  2324. data[targetCell] = temp;
  2325. }
  2326. }
  2327. if (!screenshotCanvas) {
  2328. screenshotCanvas = document.createElement('canvas');
  2329. }
  2330. screenshotCanvas.width = width;
  2331. screenshotCanvas.height = height;
  2332. var context = screenshotCanvas.getContext('2d');
  2333. var imageData = context.createImageData(width, height);
  2334. imageData.data.set(data);
  2335. context.putImageData(imageData, 0, 0);
  2336. var base64Image = screenshotCanvas.toDataURL();
  2337. if (("download" in document.createElement("a"))) {
  2338. var a = window.document.createElement("a");
  2339. a.href = base64Image;
  2340. var date = new Date();
  2341. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2342. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2343. window.document.body.appendChild(a);
  2344. a.addEventListener("click", function () {
  2345. a.parentElement.removeChild(a);
  2346. });
  2347. a.click();
  2348. } else {
  2349. var newWindow = window.open("");
  2350. var img = newWindow.document.createElement("img");
  2351. img.src = base64Image;
  2352. newWindow.document.body.appendChild(img);
  2353. }
  2354. };
  2355. texture.render(true);
  2356. texture.dispose();
  2357. if (previousCamera) {
  2358. scene.activeCamera = previousCamera;
  2359. }
  2360. };
  2361. Tools.ValidateXHRData = function (xhr, dataType) {
  2362. if (typeof dataType === "undefined") { dataType = 7; }
  2363. try {
  2364. if (dataType & 1) {
  2365. if (xhr.responseText && xhr.responseText.length > 0) {
  2366. return true;
  2367. } else if (dataType === 1) {
  2368. return false;
  2369. }
  2370. }
  2371. if (dataType & 2) {
  2372. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2373. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2374. return true;
  2375. } else if (dataType === 2) {
  2376. return false;
  2377. }
  2378. }
  2379. if (dataType & 4) {
  2380. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2381. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2382. return true;
  2383. } else {
  2384. return false;
  2385. }
  2386. }
  2387. } catch (e) {
  2388. }
  2389. return false;
  2390. };
  2391. Object.defineProperty(Tools, "NoneLogLevel", {
  2392. get: function () {
  2393. return Tools._NoneLogLevel;
  2394. },
  2395. enumerable: true,
  2396. configurable: true
  2397. });
  2398. Object.defineProperty(Tools, "MessageLogLevel", {
  2399. get: function () {
  2400. return Tools._MessageLogLevel;
  2401. },
  2402. enumerable: true,
  2403. configurable: true
  2404. });
  2405. Object.defineProperty(Tools, "WarningLogLevel", {
  2406. get: function () {
  2407. return Tools._WarningLogLevel;
  2408. },
  2409. enumerable: true,
  2410. configurable: true
  2411. });
  2412. Object.defineProperty(Tools, "ErrorLogLevel", {
  2413. get: function () {
  2414. return Tools._ErrorLogLevel;
  2415. },
  2416. enumerable: true,
  2417. configurable: true
  2418. });
  2419. Object.defineProperty(Tools, "AllLogLevel", {
  2420. get: function () {
  2421. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2422. },
  2423. enumerable: true,
  2424. configurable: true
  2425. });
  2426. Tools._FormatMessage = function (message) {
  2427. var padStr = function (i) {
  2428. return (i < 10) ? "0" + i : "" + i;
  2429. };
  2430. var date = new Date();
  2431. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2432. };
  2433. Tools._LogDisabled = function (message) {
  2434. };
  2435. Tools._LogEnabled = function (message) {
  2436. console.log(Tools._FormatMessage(message));
  2437. };
  2438. Tools._WarnDisabled = function (message) {
  2439. };
  2440. Tools._WarnEnabled = function (message) {
  2441. console.warn(Tools._FormatMessage(message));
  2442. };
  2443. Tools._ErrorDisabled = function (message) {
  2444. };
  2445. Tools._ErrorEnabled = function (message) {
  2446. console.error(Tools._FormatMessage(message));
  2447. };
  2448. Object.defineProperty(Tools, "LogLevels", {
  2449. set: function (level) {
  2450. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2451. Tools.Log = Tools._LogEnabled;
  2452. } else {
  2453. Tools.Log = Tools._LogDisabled;
  2454. }
  2455. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2456. Tools.Warn = Tools._WarnEnabled;
  2457. } else {
  2458. Tools.Warn = Tools._WarnDisabled;
  2459. }
  2460. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2461. Tools.Error = Tools._ErrorEnabled;
  2462. } else {
  2463. Tools.Error = Tools._ErrorDisabled;
  2464. }
  2465. },
  2466. enumerable: true,
  2467. configurable: true
  2468. });
  2469. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2470. get: function () {
  2471. return Tools._PerformanceNoneLogLevel;
  2472. },
  2473. enumerable: true,
  2474. configurable: true
  2475. });
  2476. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2477. get: function () {
  2478. return Tools._PerformanceUserMarkLogLevel;
  2479. },
  2480. enumerable: true,
  2481. configurable: true
  2482. });
  2483. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2484. get: function () {
  2485. return Tools._PerformanceConsoleLogLevel;
  2486. },
  2487. enumerable: true,
  2488. configurable: true
  2489. });
  2490. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2491. set: function (level) {
  2492. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2493. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2494. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2495. return;
  2496. }
  2497. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2498. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2499. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2500. return;
  2501. }
  2502. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2503. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2504. },
  2505. enumerable: true,
  2506. configurable: true
  2507. });
  2508. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2509. };
  2510. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2511. };
  2512. Tools._StartUserMark = function (counterName, condition) {
  2513. if (typeof condition === "undefined") { condition = true; }
  2514. if (!condition || !Tools._performance.mark) {
  2515. return;
  2516. }
  2517. Tools._performance.mark(counterName + "-Begin");
  2518. };
  2519. Tools._EndUserMark = function (counterName, condition) {
  2520. if (typeof condition === "undefined") { condition = true; }
  2521. if (!condition || !Tools._performance.mark) {
  2522. return;
  2523. }
  2524. Tools._performance.mark(counterName + "-End");
  2525. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2526. };
  2527. Tools._StartPerformanceConsole = function (counterName, condition) {
  2528. if (typeof condition === "undefined") { condition = true; }
  2529. if (!condition) {
  2530. return;
  2531. }
  2532. Tools._StartUserMark(counterName, condition);
  2533. if (console.time) {
  2534. console.time(counterName);
  2535. }
  2536. };
  2537. Tools._EndPerformanceConsole = function (counterName, condition) {
  2538. if (typeof condition === "undefined") { condition = true; }
  2539. if (!condition) {
  2540. return;
  2541. }
  2542. Tools._EndUserMark(counterName, condition);
  2543. if (console.time) {
  2544. console.timeEnd(counterName);
  2545. }
  2546. };
  2547. Object.defineProperty(Tools, "Now", {
  2548. get: function () {
  2549. if (window.performance.now) {
  2550. return window.performance.now();
  2551. }
  2552. return new Date().getTime();
  2553. },
  2554. enumerable: true,
  2555. configurable: true
  2556. });
  2557. Tools.BaseUrl = "";
  2558. Tools.GetExponantOfTwo = function (value, max) {
  2559. var count = 1;
  2560. do {
  2561. count *= 2;
  2562. } while(count < value);
  2563. if (count > max)
  2564. count = max;
  2565. return count;
  2566. };
  2567. Tools._NoneLogLevel = 0;
  2568. Tools._MessageLogLevel = 1;
  2569. Tools._WarningLogLevel = 2;
  2570. Tools._ErrorLogLevel = 4;
  2571. Tools.Log = Tools._LogEnabled;
  2572. Tools.Warn = Tools._WarnEnabled;
  2573. Tools.Error = Tools._ErrorEnabled;
  2574. Tools._PerformanceNoneLogLevel = 0;
  2575. Tools._PerformanceUserMarkLogLevel = 1;
  2576. Tools._PerformanceConsoleLogLevel = 2;
  2577. Tools._performance = window.performance;
  2578. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2579. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2580. return Tools;
  2581. })();
  2582. BABYLON.Tools = Tools;
  2583. })(BABYLON || (BABYLON = {}));
  2584. var BABYLON;
  2585. (function (BABYLON) {
  2586. var _DepthCullingState = (function () {
  2587. function _DepthCullingState() {
  2588. this._isDepthTestDirty = false;
  2589. this._isDepthMaskDirty = false;
  2590. this._isDepthFuncDirty = false;
  2591. this._isCullFaceDirty = false;
  2592. this._isCullDirty = false;
  2593. }
  2594. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2595. get: function () {
  2596. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2597. },
  2598. enumerable: true,
  2599. configurable: true
  2600. });
  2601. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2602. get: function () {
  2603. return this._cullFace;
  2604. },
  2605. set: function (value) {
  2606. if (this._cullFace === value) {
  2607. return;
  2608. }
  2609. this._cullFace = value;
  2610. this._isCullFaceDirty = true;
  2611. },
  2612. enumerable: true,
  2613. configurable: true
  2614. });
  2615. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2616. get: function () {
  2617. return this._cull;
  2618. },
  2619. set: function (value) {
  2620. if (this._cull === value) {
  2621. return;
  2622. }
  2623. this._cull = value;
  2624. this._isCullDirty = true;
  2625. },
  2626. enumerable: true,
  2627. configurable: true
  2628. });
  2629. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2630. get: function () {
  2631. return this._depthFunc;
  2632. },
  2633. set: function (value) {
  2634. if (this._depthFunc === value) {
  2635. return;
  2636. }
  2637. this._depthFunc = value;
  2638. this._isDepthFuncDirty = true;
  2639. },
  2640. enumerable: true,
  2641. configurable: true
  2642. });
  2643. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2644. get: function () {
  2645. return this._depthMask;
  2646. },
  2647. set: function (value) {
  2648. if (this._depthMask === value) {
  2649. return;
  2650. }
  2651. this._depthMask = value;
  2652. this._isDepthMaskDirty = true;
  2653. },
  2654. enumerable: true,
  2655. configurable: true
  2656. });
  2657. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  2658. get: function () {
  2659. return this._depthTest;
  2660. },
  2661. set: function (value) {
  2662. if (this._depthTest === value) {
  2663. return;
  2664. }
  2665. this._depthTest = value;
  2666. this._isDepthTestDirty = true;
  2667. },
  2668. enumerable: true,
  2669. configurable: true
  2670. });
  2671. _DepthCullingState.prototype.reset = function () {
  2672. this._depthMask = true;
  2673. this._depthTest = true;
  2674. this._depthFunc = null;
  2675. this._cull = null;
  2676. this._cullFace = null;
  2677. this._isDepthTestDirty = true;
  2678. this._isDepthMaskDirty = true;
  2679. this._isDepthFuncDirty = false;
  2680. this._isCullFaceDirty = false;
  2681. this._isCullDirty = false;
  2682. };
  2683. _DepthCullingState.prototype.apply = function (gl) {
  2684. if (!this.isDirty) {
  2685. return;
  2686. }
  2687. if (this._isCullDirty) {
  2688. if (this.cull === true) {
  2689. gl.enable(gl.CULL_FACE);
  2690. } else if (this.cull === false) {
  2691. gl.disable(gl.CULL_FACE);
  2692. }
  2693. this._isCullDirty = false;
  2694. }
  2695. if (this._isCullFaceDirty) {
  2696. gl.cullFace(this.cullFace);
  2697. this._isCullFaceDirty = false;
  2698. }
  2699. if (this._isDepthMaskDirty) {
  2700. gl.depthMask(this.depthMask);
  2701. this._isDepthMaskDirty = false;
  2702. }
  2703. if (this._isDepthTestDirty) {
  2704. if (this.depthTest === true) {
  2705. gl.enable(gl.DEPTH_TEST);
  2706. } else if (this.depthTest === false) {
  2707. gl.disable(gl.DEPTH_TEST);
  2708. }
  2709. this._isDepthTestDirty = false;
  2710. }
  2711. if (this._isDepthFuncDirty) {
  2712. gl.depthFunc(this.depthFunc);
  2713. this._isDepthFuncDirty = false;
  2714. }
  2715. };
  2716. return _DepthCullingState;
  2717. })();
  2718. BABYLON._DepthCullingState = _DepthCullingState;
  2719. var _AlphaState = (function () {
  2720. function _AlphaState() {
  2721. this._isAlphaBlendDirty = false;
  2722. this._isBlendFunctionParametersDirty = false;
  2723. this._alphaBlend = false;
  2724. this._blendFunctionParameters = new Array(4);
  2725. }
  2726. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  2727. get: function () {
  2728. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  2729. },
  2730. enumerable: true,
  2731. configurable: true
  2732. });
  2733. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  2734. get: function () {
  2735. return this._alphaBlend;
  2736. },
  2737. set: function (value) {
  2738. if (this._alphaBlend === value) {
  2739. return;
  2740. }
  2741. this._alphaBlend = value;
  2742. this._isAlphaBlendDirty = true;
  2743. },
  2744. enumerable: true,
  2745. configurable: true
  2746. });
  2747. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  2748. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  2749. return;
  2750. }
  2751. this._blendFunctionParameters[0] = value0;
  2752. this._blendFunctionParameters[1] = value1;
  2753. this._blendFunctionParameters[2] = value2;
  2754. this._blendFunctionParameters[3] = value3;
  2755. this._isBlendFunctionParametersDirty = true;
  2756. };
  2757. _AlphaState.prototype.reset = function () {
  2758. this._alphaBlend = false;
  2759. this._blendFunctionParameters[0] = null;
  2760. this._blendFunctionParameters[1] = null;
  2761. this._blendFunctionParameters[2] = null;
  2762. this._blendFunctionParameters[3] = null;
  2763. this._isAlphaBlendDirty = true;
  2764. this._isBlendFunctionParametersDirty = false;
  2765. };
  2766. _AlphaState.prototype.apply = function (gl) {
  2767. if (!this.isDirty) {
  2768. return;
  2769. }
  2770. if (this._isAlphaBlendDirty) {
  2771. if (this._alphaBlend === true) {
  2772. gl.enable(gl.BLEND);
  2773. } else if (this._alphaBlend === false) {
  2774. gl.disable(gl.BLEND);
  2775. }
  2776. this._isAlphaBlendDirty = false;
  2777. }
  2778. if (this._isBlendFunctionParametersDirty) {
  2779. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  2780. this._isBlendFunctionParametersDirty = false;
  2781. }
  2782. };
  2783. return _AlphaState;
  2784. })();
  2785. BABYLON._AlphaState = _AlphaState;
  2786. var compileShader = function (gl, source, type, defines) {
  2787. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2788. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  2789. gl.compileShader(shader);
  2790. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2791. throw new Error(gl.getShaderInfoLog(shader));
  2792. }
  2793. return shader;
  2794. };
  2795. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  2796. var magFilter = gl.NEAREST;
  2797. var minFilter = gl.NEAREST;
  2798. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  2799. magFilter = gl.LINEAR;
  2800. if (generateMipMaps) {
  2801. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2802. } else {
  2803. minFilter = gl.LINEAR;
  2804. }
  2805. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  2806. magFilter = gl.LINEAR;
  2807. if (generateMipMaps) {
  2808. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2809. } else {
  2810. minFilter = gl.LINEAR;
  2811. }
  2812. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  2813. magFilter = gl.NEAREST;
  2814. if (generateMipMaps) {
  2815. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2816. } else {
  2817. minFilter = gl.NEAREST;
  2818. }
  2819. }
  2820. return {
  2821. min: minFilter,
  2822. mag: magFilter
  2823. };
  2824. };
  2825. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  2826. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  2827. var engine = scene.getEngine();
  2828. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  2829. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  2830. gl.bindTexture(gl.TEXTURE_2D, texture);
  2831. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2832. processFunction(potWidth, potHeight);
  2833. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  2834. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2835. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2836. if (!noMipmap && !isCompressed) {
  2837. gl.generateMipmap(gl.TEXTURE_2D);
  2838. }
  2839. gl.bindTexture(gl.TEXTURE_2D, null);
  2840. engine._activeTexturesCache = [];
  2841. texture._baseWidth = width;
  2842. texture._baseHeight = height;
  2843. texture._width = potWidth;
  2844. texture._height = potHeight;
  2845. texture.isReady = true;
  2846. scene._removePendingData(texture);
  2847. };
  2848. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  2849. var img;
  2850. var onload = function () {
  2851. loadedImages[index] = img;
  2852. loadedImages._internalCount++;
  2853. scene._removePendingData(img);
  2854. if (loadedImages._internalCount == 6) {
  2855. onfinish(loadedImages);
  2856. }
  2857. };
  2858. var onerror = function () {
  2859. scene._removePendingData(img);
  2860. };
  2861. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  2862. scene._addPendingData(img);
  2863. };
  2864. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  2865. var loadedImages = [];
  2866. loadedImages._internalCount = 0;
  2867. for (var index = 0; index < 6; index++) {
  2868. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  2869. }
  2870. };
  2871. var EngineCapabilities = (function () {
  2872. function EngineCapabilities() {
  2873. }
  2874. return EngineCapabilities;
  2875. })();
  2876. BABYLON.EngineCapabilities = EngineCapabilities;
  2877. var Engine = (function () {
  2878. function Engine(canvas, antialias, options) {
  2879. var _this = this;
  2880. this.isFullscreen = false;
  2881. this.isPointerLock = false;
  2882. this.forceWireframe = false;
  2883. this.cullBackFaces = true;
  2884. this.renderEvenInBackground = true;
  2885. this.scenes = new Array();
  2886. this._windowIsBackground = false;
  2887. this._runningLoop = false;
  2888. this._loadingDivBackgroundColor = "black";
  2889. this._depthCullingState = new _DepthCullingState();
  2890. this._alphaState = new _AlphaState();
  2891. this._loadedTexturesCache = new Array();
  2892. this._activeTexturesCache = new Array();
  2893. this._compiledEffects = {};
  2894. this._renderingCanvas = canvas;
  2895. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2896. options = options || {};
  2897. options.antialias = antialias;
  2898. try {
  2899. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  2900. } catch (e) {
  2901. throw new Error("WebGL not supported");
  2902. }
  2903. if (!this._gl) {
  2904. throw new Error("WebGL not supported");
  2905. }
  2906. this._onBlur = function () {
  2907. _this._windowIsBackground = true;
  2908. };
  2909. this._onFocus = function () {
  2910. _this._windowIsBackground = false;
  2911. };
  2912. window.addEventListener("blur", this._onBlur);
  2913. window.addEventListener("focus", this._onFocus);
  2914. this._workingCanvas = document.createElement("canvas");
  2915. this._workingContext = this._workingCanvas.getContext("2d");
  2916. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  2917. this.resize();
  2918. this._caps = new EngineCapabilities();
  2919. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  2920. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  2921. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  2922. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  2923. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  2924. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  2925. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  2926. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  2927. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  2928. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  2929. this.setDepthBuffer(true);
  2930. this.setDepthFunctionToLessOrEqual();
  2931. this.setDepthWrite(true);
  2932. this._onFullscreenChange = function () {
  2933. if (document.fullscreen !== undefined) {
  2934. _this.isFullscreen = document.fullscreen;
  2935. } else if (document.mozFullScreen !== undefined) {
  2936. _this.isFullscreen = document.mozFullScreen;
  2937. } else if (document.webkitIsFullScreen !== undefined) {
  2938. _this.isFullscreen = document.webkitIsFullScreen;
  2939. } else if (document.msIsFullScreen !== undefined) {
  2940. _this.isFullscreen = document.msIsFullScreen;
  2941. }
  2942. if (_this.isFullscreen && _this._pointerLockRequested) {
  2943. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  2944. if (canvas.requestPointerLock) {
  2945. canvas.requestPointerLock();
  2946. }
  2947. }
  2948. };
  2949. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  2950. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  2951. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  2952. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  2953. this._onPointerLockChange = function () {
  2954. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  2955. };
  2956. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  2957. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  2958. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  2959. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  2960. }
  2961. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  2962. get: function () {
  2963. return Engine._ALPHA_DISABLE;
  2964. },
  2965. enumerable: true,
  2966. configurable: true
  2967. });
  2968. Object.defineProperty(Engine, "ALPHA_ADD", {
  2969. get: function () {
  2970. return Engine._ALPHA_ADD;
  2971. },
  2972. enumerable: true,
  2973. configurable: true
  2974. });
  2975. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  2976. get: function () {
  2977. return Engine._ALPHA_COMBINE;
  2978. },
  2979. enumerable: true,
  2980. configurable: true
  2981. });
  2982. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  2983. get: function () {
  2984. return Engine._DELAYLOADSTATE_NONE;
  2985. },
  2986. enumerable: true,
  2987. configurable: true
  2988. });
  2989. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  2990. get: function () {
  2991. return Engine._DELAYLOADSTATE_LOADED;
  2992. },
  2993. enumerable: true,
  2994. configurable: true
  2995. });
  2996. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  2997. get: function () {
  2998. return Engine._DELAYLOADSTATE_LOADING;
  2999. },
  3000. enumerable: true,
  3001. configurable: true
  3002. });
  3003. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3004. get: function () {
  3005. return Engine._DELAYLOADSTATE_NOTLOADED;
  3006. },
  3007. enumerable: true,
  3008. configurable: true
  3009. });
  3010. Object.defineProperty(Engine, "Version", {
  3011. get: function () {
  3012. return "2.0.0";
  3013. },
  3014. enumerable: true,
  3015. configurable: true
  3016. });
  3017. Engine.prototype.getAspectRatio = function (camera) {
  3018. var viewport = camera.viewport;
  3019. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3020. };
  3021. Engine.prototype.getRenderWidth = function () {
  3022. if (this._currentRenderTarget) {
  3023. return this._currentRenderTarget._width;
  3024. }
  3025. return this._renderingCanvas.width;
  3026. };
  3027. Engine.prototype.getRenderHeight = function () {
  3028. if (this._currentRenderTarget) {
  3029. return this._currentRenderTarget._height;
  3030. }
  3031. return this._renderingCanvas.height;
  3032. };
  3033. Engine.prototype.getRenderingCanvas = function () {
  3034. return this._renderingCanvas;
  3035. };
  3036. Engine.prototype.getRenderingCanvasClientRect = function () {
  3037. return this._renderingCanvas.getBoundingClientRect();
  3038. };
  3039. Engine.prototype.setHardwareScalingLevel = function (level) {
  3040. this._hardwareScalingLevel = level;
  3041. this.resize();
  3042. };
  3043. Engine.prototype.getHardwareScalingLevel = function () {
  3044. return this._hardwareScalingLevel;
  3045. };
  3046. Engine.prototype.getLoadedTexturesCache = function () {
  3047. return this._loadedTexturesCache;
  3048. };
  3049. Engine.prototype.getCaps = function () {
  3050. return this._caps;
  3051. };
  3052. Engine.prototype.setDepthFunctionToGreater = function () {
  3053. this._depthCullingState.depthFunc = this._gl.GREATER;
  3054. };
  3055. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3056. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3057. };
  3058. Engine.prototype.setDepthFunctionToLess = function () {
  3059. this._depthCullingState.depthFunc = this._gl.LESS;
  3060. };
  3061. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3062. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3063. };
  3064. Engine.prototype.stopRenderLoop = function () {
  3065. this._renderFunction = null;
  3066. this._runningLoop = false;
  3067. };
  3068. Engine.prototype._renderLoop = function () {
  3069. var _this = this;
  3070. var shouldRender = true;
  3071. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3072. shouldRender = false;
  3073. }
  3074. if (shouldRender) {
  3075. this.beginFrame();
  3076. if (this._renderFunction) {
  3077. this._renderFunction();
  3078. }
  3079. this.endFrame();
  3080. }
  3081. if (this._runningLoop) {
  3082. BABYLON.Tools.QueueNewFrame(function () {
  3083. _this._renderLoop();
  3084. });
  3085. }
  3086. };
  3087. Engine.prototype.runRenderLoop = function (renderFunction) {
  3088. var _this = this;
  3089. this._runningLoop = true;
  3090. this._renderFunction = renderFunction;
  3091. BABYLON.Tools.QueueNewFrame(function () {
  3092. _this._renderLoop();
  3093. });
  3094. };
  3095. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3096. if (this.isFullscreen) {
  3097. BABYLON.Tools.ExitFullscreen();
  3098. } else {
  3099. this._pointerLockRequested = requestPointerLock;
  3100. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3101. }
  3102. };
  3103. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3104. this.applyStates();
  3105. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3106. if (this._depthCullingState.depthMask) {
  3107. this._gl.clearDepth(1.0);
  3108. }
  3109. var mode = 0;
  3110. if (backBuffer)
  3111. mode |= this._gl.COLOR_BUFFER_BIT;
  3112. if (depthStencil && this._depthCullingState.depthMask)
  3113. mode |= this._gl.DEPTH_BUFFER_BIT;
  3114. this._gl.clear(mode);
  3115. };
  3116. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3117. var width = requiredWidth || this._renderingCanvas.width;
  3118. var height = requiredHeight || this._renderingCanvas.height;
  3119. var x = viewport.x || 0;
  3120. var y = viewport.y || 0;
  3121. this._cachedViewport = viewport;
  3122. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3123. };
  3124. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3125. this._cachedViewport = null;
  3126. this._gl.viewport(x, y, width, height);
  3127. };
  3128. Engine.prototype.beginFrame = function () {
  3129. BABYLON.Tools._MeasureFps();
  3130. };
  3131. Engine.prototype.endFrame = function () {
  3132. this.flushFramebuffer();
  3133. };
  3134. Engine.prototype.resize = function () {
  3135. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3136. };
  3137. Engine.prototype.setSize = function (width, height) {
  3138. this._renderingCanvas.width = width;
  3139. this._renderingCanvas.height = height;
  3140. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3141. };
  3142. Engine.prototype.bindFramebuffer = function (texture) {
  3143. this._currentRenderTarget = texture;
  3144. var gl = this._gl;
  3145. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3146. this._gl.viewport(0, 0, texture._width, texture._height);
  3147. this.wipeCaches();
  3148. };
  3149. Engine.prototype.unBindFramebuffer = function (texture) {
  3150. this._currentRenderTarget = null;
  3151. if (texture.generateMipMaps) {
  3152. var gl = this._gl;
  3153. gl.bindTexture(gl.TEXTURE_2D, texture);
  3154. gl.generateMipmap(gl.TEXTURE_2D);
  3155. gl.bindTexture(gl.TEXTURE_2D, null);
  3156. }
  3157. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3158. };
  3159. Engine.prototype.flushFramebuffer = function () {
  3160. this._gl.flush();
  3161. };
  3162. Engine.prototype.restoreDefaultFramebuffer = function () {
  3163. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3164. this.setViewport(this._cachedViewport);
  3165. this.wipeCaches();
  3166. };
  3167. Engine.prototype._resetVertexBufferBinding = function () {
  3168. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3169. this._cachedVertexBuffers = null;
  3170. };
  3171. Engine.prototype.createVertexBuffer = function (vertices) {
  3172. var vbo = this._gl.createBuffer();
  3173. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3174. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3175. this._resetVertexBufferBinding();
  3176. vbo.references = 1;
  3177. return vbo;
  3178. };
  3179. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3180. var vbo = this._gl.createBuffer();
  3181. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3182. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3183. this._resetVertexBufferBinding();
  3184. vbo.references = 1;
  3185. return vbo;
  3186. };
  3187. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, length) {
  3188. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3189. if (vertices instanceof Float32Array) {
  3190. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  3191. } else {
  3192. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  3193. }
  3194. this._resetVertexBufferBinding();
  3195. };
  3196. Engine.prototype._resetIndexBufferBinding = function () {
  3197. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3198. this._cachedIndexBuffer = null;
  3199. };
  3200. Engine.prototype.createIndexBuffer = function (indices) {
  3201. var vbo = this._gl.createBuffer();
  3202. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3203. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  3204. this._resetIndexBufferBinding();
  3205. vbo.references = 1;
  3206. return vbo;
  3207. };
  3208. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3209. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3210. this._cachedVertexBuffers = vertexBuffer;
  3211. this._cachedEffectForVertexBuffers = effect;
  3212. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3213. var offset = 0;
  3214. for (var index = 0; index < vertexDeclaration.length; index++) {
  3215. var order = effect.getAttributeLocation(index);
  3216. if (order >= 0) {
  3217. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3218. }
  3219. offset += vertexDeclaration[index] * 4;
  3220. }
  3221. }
  3222. if (this._cachedIndexBuffer !== indexBuffer) {
  3223. this._cachedIndexBuffer = indexBuffer;
  3224. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3225. }
  3226. };
  3227. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3228. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3229. this._cachedVertexBuffers = vertexBuffers;
  3230. this._cachedEffectForVertexBuffers = effect;
  3231. var attributes = effect.getAttributesNames();
  3232. for (var index = 0; index < attributes.length; index++) {
  3233. var order = effect.getAttributeLocation(index);
  3234. if (order >= 0) {
  3235. var vertexBuffer = vertexBuffers[attributes[index]];
  3236. if (!vertexBuffer) {
  3237. continue;
  3238. }
  3239. var stride = vertexBuffer.getStrideSize();
  3240. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3241. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3242. }
  3243. }
  3244. }
  3245. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3246. this._cachedIndexBuffer = indexBuffer;
  3247. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3248. }
  3249. };
  3250. Engine.prototype._releaseBuffer = function (buffer) {
  3251. buffer.references--;
  3252. if (buffer.references === 0) {
  3253. this._gl.deleteBuffer(buffer);
  3254. return true;
  3255. }
  3256. return false;
  3257. };
  3258. Engine.prototype.createInstancesBuffer = function (capacity) {
  3259. var buffer = this._gl.createBuffer();
  3260. buffer.capacity = capacity;
  3261. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3262. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3263. return buffer;
  3264. };
  3265. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3266. this._gl.deleteBuffer(buffer);
  3267. };
  3268. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3269. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3270. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3271. for (var index = 0; index < 4; index++) {
  3272. var offsetLocation = offsetLocations[index];
  3273. this._gl.enableVertexAttribArray(offsetLocation);
  3274. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3275. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3276. }
  3277. };
  3278. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3279. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3280. for (var index = 0; index < 4; index++) {
  3281. var offsetLocation = offsetLocations[index];
  3282. this._gl.disableVertexAttribArray(offsetLocation);
  3283. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3284. }
  3285. };
  3286. Engine.prototype.applyStates = function () {
  3287. this._depthCullingState.apply(this._gl);
  3288. this._alphaState.apply(this._gl);
  3289. };
  3290. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  3291. this.applyStates();
  3292. if (instancesCount) {
  3293. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2, instancesCount);
  3294. return;
  3295. }
  3296. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  3297. };
  3298. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  3299. this.applyStates();
  3300. if (instancesCount) {
  3301. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  3302. return;
  3303. }
  3304. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  3305. };
  3306. Engine.prototype._releaseEffect = function (effect) {
  3307. if (this._compiledEffects[effect._key]) {
  3308. delete this._compiledEffects[effect._key];
  3309. if (effect.getProgram()) {
  3310. this._gl.deleteProgram(effect.getProgram());
  3311. }
  3312. }
  3313. };
  3314. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3315. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3316. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  3317. var name = vertex + "+" + fragment + "@" + defines;
  3318. if (this._compiledEffects[name]) {
  3319. return this._compiledEffects[name];
  3320. }
  3321. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  3322. effect._key = name;
  3323. this._compiledEffects[name] = effect;
  3324. return effect;
  3325. };
  3326. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3327. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  3328. if (typeof samplers === "undefined") { samplers = []; }
  3329. if (typeof defines === "undefined") { defines = ""; }
  3330. return this.createEffect({
  3331. vertex: "particles",
  3332. fragmentElement: fragmentName
  3333. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  3334. };
  3335. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  3336. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  3337. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  3338. var shaderProgram = this._gl.createProgram();
  3339. this._gl.attachShader(shaderProgram, vertexShader);
  3340. this._gl.attachShader(shaderProgram, fragmentShader);
  3341. this._gl.linkProgram(shaderProgram);
  3342. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  3343. if (!linked) {
  3344. var error = this._gl.getProgramInfoLog(shaderProgram);
  3345. if (error) {
  3346. throw new Error(error);
  3347. }
  3348. }
  3349. this._gl.deleteShader(vertexShader);
  3350. this._gl.deleteShader(fragmentShader);
  3351. return shaderProgram;
  3352. };
  3353. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3354. var results = [];
  3355. for (var index = 0; index < uniformsNames.length; index++) {
  3356. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3357. }
  3358. return results;
  3359. };
  3360. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3361. var results = [];
  3362. for (var index = 0; index < attributesNames.length; index++) {
  3363. try {
  3364. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3365. } catch (e) {
  3366. results.push(-1);
  3367. }
  3368. }
  3369. return results;
  3370. };
  3371. Engine.prototype.enableEffect = function (effect) {
  3372. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3373. return;
  3374. }
  3375. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3376. this._gl.useProgram(effect.getProgram());
  3377. for (var i in this._vertexAttribArrays) {
  3378. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3379. continue;
  3380. }
  3381. this._vertexAttribArrays[i] = false;
  3382. this._gl.disableVertexAttribArray(i);
  3383. }
  3384. var attributesCount = effect.getAttributesCount();
  3385. for (var index = 0; index < attributesCount; index++) {
  3386. var order = effect.getAttributeLocation(index);
  3387. if (order >= 0) {
  3388. this._vertexAttribArrays[order] = true;
  3389. this._gl.enableVertexAttribArray(order);
  3390. }
  3391. }
  3392. this._currentEffect = effect;
  3393. };
  3394. Engine.prototype.setArray = function (uniform, array) {
  3395. if (!uniform)
  3396. return;
  3397. this._gl.uniform1fv(uniform, array);
  3398. };
  3399. Engine.prototype.setMatrices = function (uniform, matrices) {
  3400. if (!uniform)
  3401. return;
  3402. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3403. };
  3404. Engine.prototype.setMatrix = function (uniform, matrix) {
  3405. if (!uniform)
  3406. return;
  3407. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3408. };
  3409. Engine.prototype.setFloat = function (uniform, value) {
  3410. if (!uniform)
  3411. return;
  3412. this._gl.uniform1f(uniform, value);
  3413. };
  3414. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3415. if (!uniform)
  3416. return;
  3417. this._gl.uniform2f(uniform, x, y);
  3418. };
  3419. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3420. if (!uniform)
  3421. return;
  3422. this._gl.uniform3f(uniform, x, y, z);
  3423. };
  3424. Engine.prototype.setBool = function (uniform, bool) {
  3425. if (!uniform)
  3426. return;
  3427. this._gl.uniform1i(uniform, bool);
  3428. };
  3429. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3430. if (!uniform)
  3431. return;
  3432. this._gl.uniform4f(uniform, x, y, z, w);
  3433. };
  3434. Engine.prototype.setColor3 = function (uniform, color3) {
  3435. if (!uniform)
  3436. return;
  3437. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3438. };
  3439. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3440. if (!uniform)
  3441. return;
  3442. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3443. };
  3444. Engine.prototype.setState = function (culling, force) {
  3445. if (this._depthCullingState.cull !== culling || force) {
  3446. if (culling) {
  3447. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3448. this._depthCullingState.cull = true;
  3449. } else {
  3450. this._depthCullingState.cull = false;
  3451. }
  3452. }
  3453. };
  3454. Engine.prototype.setDepthBuffer = function (enable) {
  3455. this._depthCullingState.depthTest = enable;
  3456. };
  3457. Engine.prototype.getDepthWrite = function () {
  3458. return this._depthCullingState.depthMask;
  3459. };
  3460. Engine.prototype.setDepthWrite = function (enable) {
  3461. this._depthCullingState.depthMask = enable;
  3462. };
  3463. Engine.prototype.setColorWrite = function (enable) {
  3464. this._gl.colorMask(enable, enable, enable, enable);
  3465. };
  3466. Engine.prototype.setAlphaMode = function (mode) {
  3467. switch (mode) {
  3468. case BABYLON.Engine.ALPHA_DISABLE:
  3469. this.setDepthWrite(true);
  3470. this._alphaState.alphaBlend = false;
  3471. break;
  3472. case BABYLON.Engine.ALPHA_COMBINE:
  3473. this.setDepthWrite(false);
  3474. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3475. this._alphaState.alphaBlend = true;
  3476. break;
  3477. case BABYLON.Engine.ALPHA_ADD:
  3478. this.setDepthWrite(false);
  3479. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3480. this._alphaState.alphaBlend = true;
  3481. break;
  3482. }
  3483. };
  3484. Engine.prototype.setAlphaTesting = function (enable) {
  3485. this._alphaTest = enable;
  3486. };
  3487. Engine.prototype.getAlphaTesting = function () {
  3488. return this._alphaTest;
  3489. };
  3490. Engine.prototype.wipeCaches = function () {
  3491. this._activeTexturesCache = [];
  3492. this._currentEffect = null;
  3493. this._depthCullingState.reset();
  3494. this._alphaState.reset();
  3495. this._cachedVertexBuffers = null;
  3496. this._cachedIndexBuffer = null;
  3497. this._cachedEffectForVertexBuffers = null;
  3498. };
  3499. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3500. var gl = this._gl;
  3501. gl.bindTexture(gl.TEXTURE_2D, texture);
  3502. var magFilter = gl.NEAREST;
  3503. var minFilter = gl.NEAREST;
  3504. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3505. magFilter = gl.LINEAR;
  3506. minFilter = gl.LINEAR;
  3507. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3508. magFilter = gl.LINEAR;
  3509. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3510. }
  3511. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3512. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3513. gl.bindTexture(gl.TEXTURE_2D, null);
  3514. };
  3515. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  3516. var _this = this;
  3517. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3518. if (typeof onLoad === "undefined") { onLoad = null; }
  3519. if (typeof onError === "undefined") { onError = null; }
  3520. if (typeof buffer === "undefined") { buffer = null; }
  3521. var texture = this._gl.createTexture();
  3522. var extension;
  3523. var fromData = false;
  3524. if (url.substr(0, 5) === "data:") {
  3525. fromData = true;
  3526. }
  3527. if (!fromData)
  3528. extension = url.substr(url.length - 4, 4).toLowerCase();
  3529. else {
  3530. var oldUrl = url;
  3531. fromData = oldUrl.split(':');
  3532. url = oldUrl;
  3533. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  3534. }
  3535. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3536. var isTGA = (extension === ".tga");
  3537. scene._addPendingData(texture);
  3538. texture.url = url;
  3539. texture.noMipmap = noMipmap;
  3540. texture.references = 1;
  3541. this._loadedTexturesCache.push(texture);
  3542. var onerror = function () {
  3543. scene._removePendingData(texture);
  3544. if (onError) {
  3545. onError();
  3546. }
  3547. };
  3548. if (isTGA) {
  3549. var callback = function (arrayBuffer) {
  3550. var data = new Uint8Array(arrayBuffer);
  3551. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3552. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3553. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3554. if (onLoad) {
  3555. onLoad();
  3556. }
  3557. }, samplingMode);
  3558. };
  3559. if (!(fromData instanceof Array))
  3560. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3561. callback(arrayBuffer);
  3562. }, onerror, scene.database, true);
  3563. else
  3564. callback(buffer);
  3565. } else if (isDDS) {
  3566. callback = function (data) {
  3567. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3568. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3569. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3570. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3571. if (onLoad) {
  3572. onLoad();
  3573. }
  3574. }, samplingMode);
  3575. };
  3576. if (!(fromData instanceof Array))
  3577. BABYLON.Tools.LoadFile(url, function (data) {
  3578. callback(data);
  3579. }, onerror, scene.database, true);
  3580. else
  3581. callback(buffer);
  3582. } else {
  3583. var onload = function (img) {
  3584. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3585. var isPot = (img.width == potWidth && img.height == potHeight);
  3586. if (!isPot) {
  3587. _this._workingCanvas.width = potWidth;
  3588. _this._workingCanvas.height = potHeight;
  3589. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3590. }
  3591. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3592. if (onLoad) {
  3593. onLoad();
  3594. }
  3595. }, samplingMode);
  3596. };
  3597. if (!(fromData instanceof Array))
  3598. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3599. else
  3600. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  3601. }
  3602. return texture;
  3603. };
  3604. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  3605. var texture = this._gl.createTexture();
  3606. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  3607. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  3608. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3609. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3610. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3611. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3612. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3613. this._activeTexturesCache = [];
  3614. texture._baseWidth = width;
  3615. texture._baseHeight = height;
  3616. texture._width = width;
  3617. texture._height = height;
  3618. texture.isReady = false;
  3619. texture.generateMipMaps = generateMipMaps;
  3620. texture.references = 1;
  3621. this._loadedTexturesCache.push(texture);
  3622. return texture;
  3623. };
  3624. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  3625. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3626. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3627. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  3628. if (texture.generateMipMaps) {
  3629. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3630. }
  3631. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3632. this._activeTexturesCache = [];
  3633. texture.isReady = true;
  3634. };
  3635. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  3636. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3637. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1);
  3638. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  3639. if (!texture._workingCanvas) {
  3640. texture._workingCanvas = document.createElement("canvas");
  3641. texture._workingContext = texture._workingCanvas.getContext("2d");
  3642. texture._workingCanvas.width = texture._width;
  3643. texture._workingCanvas.height = texture._height;
  3644. }
  3645. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  3646. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3647. } else {
  3648. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3649. }
  3650. if (texture.generateMipMaps) {
  3651. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3652. }
  3653. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3654. this._activeTexturesCache = [];
  3655. texture.isReady = true;
  3656. };
  3657. Engine.prototype.createRenderTargetTexture = function (size, options) {
  3658. var generateMipMaps = false;
  3659. var generateDepthBuffer = true;
  3660. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3661. if (options !== undefined) {
  3662. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  3663. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3664. if (options.samplingMode !== undefined) {
  3665. samplingMode = options.samplingMode;
  3666. }
  3667. }
  3668. var gl = this._gl;
  3669. var texture = gl.createTexture();
  3670. gl.bindTexture(gl.TEXTURE_2D, texture);
  3671. var width = size.width || size;
  3672. var height = size.height || size;
  3673. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3674. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3675. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3676. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3677. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3678. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  3679. var depthBuffer;
  3680. if (generateDepthBuffer) {
  3681. depthBuffer = gl.createRenderbuffer();
  3682. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  3683. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3684. }
  3685. var framebuffer = gl.createFramebuffer();
  3686. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  3687. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3688. if (generateDepthBuffer) {
  3689. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  3690. }
  3691. gl.bindTexture(gl.TEXTURE_2D, null);
  3692. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3693. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3694. texture._framebuffer = framebuffer;
  3695. if (generateDepthBuffer) {
  3696. texture._depthBuffer = depthBuffer;
  3697. }
  3698. texture._width = width;
  3699. texture._height = height;
  3700. texture.isReady = true;
  3701. texture.generateMipMaps = generateMipMaps;
  3702. texture.references = 1;
  3703. this._activeTexturesCache = [];
  3704. this._loadedTexturesCache.push(texture);
  3705. return texture;
  3706. };
  3707. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  3708. var _this = this;
  3709. var gl = this._gl;
  3710. var texture = gl.createTexture();
  3711. texture.isCube = true;
  3712. texture.url = rootUrl;
  3713. texture.references = 1;
  3714. this._loadedTexturesCache.push(texture);
  3715. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  3716. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3717. if (isDDS) {
  3718. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  3719. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3720. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3721. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3722. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3723. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  3724. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  3725. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3726. }
  3727. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3728. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3729. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3730. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3731. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3732. _this._activeTexturesCache = [];
  3733. texture._width = info.width;
  3734. texture._height = info.height;
  3735. texture.isReady = true;
  3736. }, null, null, true);
  3737. } else {
  3738. cascadeLoad(rootUrl, scene, function (imgs) {
  3739. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  3740. var height = width;
  3741. _this._workingCanvas.width = width;
  3742. _this._workingCanvas.height = height;
  3743. var faces = [
  3744. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3745. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3746. ];
  3747. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3748. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3749. for (var index = 0; index < faces.length; index++) {
  3750. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3751. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  3752. }
  3753. if (!noMipmap) {
  3754. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3755. }
  3756. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3757. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  3758. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3759. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3760. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3761. _this._activeTexturesCache = [];
  3762. texture._width = width;
  3763. texture._height = height;
  3764. texture.isReady = true;
  3765. }, extensions);
  3766. }
  3767. return texture;
  3768. };
  3769. Engine.prototype._releaseTexture = function (texture) {
  3770. var gl = this._gl;
  3771. if (texture._framebuffer) {
  3772. gl.deleteFramebuffer(texture._framebuffer);
  3773. }
  3774. if (texture._depthBuffer) {
  3775. gl.deleteRenderbuffer(texture._depthBuffer);
  3776. }
  3777. gl.deleteTexture(texture);
  3778. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3779. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3780. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3781. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3782. this._activeTexturesCache[channel] = null;
  3783. }
  3784. var index = this._loadedTexturesCache.indexOf(texture);
  3785. if (index !== -1) {
  3786. this._loadedTexturesCache.splice(index, 1);
  3787. }
  3788. };
  3789. Engine.prototype.bindSamplers = function (effect) {
  3790. this._gl.useProgram(effect.getProgram());
  3791. var samplers = effect.getSamplers();
  3792. for (var index = 0; index < samplers.length; index++) {
  3793. var uniform = effect.getUniform(samplers[index]);
  3794. this._gl.uniform1i(uniform, index);
  3795. }
  3796. this._currentEffect = null;
  3797. };
  3798. Engine.prototype._bindTexture = function (channel, texture) {
  3799. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3800. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3801. this._activeTexturesCache[channel] = null;
  3802. };
  3803. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  3804. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3805. };
  3806. Engine.prototype.setTexture = function (channel, texture) {
  3807. if (channel < 0) {
  3808. return;
  3809. }
  3810. if (!texture || !texture.isReady()) {
  3811. if (this._activeTexturesCache[channel] != null) {
  3812. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3813. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3814. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3815. this._activeTexturesCache[channel] = null;
  3816. }
  3817. return;
  3818. }
  3819. if (texture instanceof BABYLON.VideoTexture) {
  3820. if (texture.update()) {
  3821. this._activeTexturesCache[channel] = null;
  3822. }
  3823. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  3824. texture.delayLoad();
  3825. return;
  3826. }
  3827. if (this._activeTexturesCache[channel] == texture) {
  3828. return;
  3829. }
  3830. this._activeTexturesCache[channel] = texture;
  3831. var internalTexture = texture.getInternalTexture();
  3832. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3833. if (internalTexture.isCube) {
  3834. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3835. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3836. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3837. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3838. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3839. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3840. }
  3841. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3842. } else {
  3843. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  3844. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3845. internalTexture._cachedWrapU = texture.wrapU;
  3846. switch (texture.wrapU) {
  3847. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3848. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3849. break;
  3850. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3851. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3852. break;
  3853. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3854. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3855. break;
  3856. }
  3857. }
  3858. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3859. internalTexture._cachedWrapV = texture.wrapV;
  3860. switch (texture.wrapV) {
  3861. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3862. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3863. break;
  3864. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3865. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  3866. break;
  3867. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3868. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  3869. break;
  3870. }
  3871. }
  3872. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3873. }
  3874. };
  3875. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  3876. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3877. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  3878. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  3879. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  3880. }
  3881. };
  3882. Engine.prototype.readPixels = function (x, y, width, height) {
  3883. var data = new Uint8Array(height * width * 4);
  3884. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  3885. return data;
  3886. };
  3887. Engine.prototype.dispose = function () {
  3888. this.hideLoadingUI();
  3889. this.stopRenderLoop();
  3890. while (this.scenes.length) {
  3891. this.scenes[0].dispose();
  3892. }
  3893. for (var name in this._compiledEffects) {
  3894. this._gl.deleteProgram(this._compiledEffects[name]._program);
  3895. }
  3896. for (var i in this._vertexAttribArrays) {
  3897. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3898. continue;
  3899. }
  3900. this._gl.disableVertexAttribArray(i);
  3901. }
  3902. window.removeEventListener("blur", this._onBlur);
  3903. window.removeEventListener("focus", this._onFocus);
  3904. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  3905. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  3906. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  3907. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  3908. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  3909. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  3910. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  3911. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  3912. };
  3913. Engine.prototype.displayLoadingUI = function () {
  3914. var _this = this;
  3915. this._loadingDiv = document.createElement("div");
  3916. this._loadingDiv.style.opacity = "0";
  3917. this._loadingDiv.style.transition = "opacity 1.5s ease";
  3918. this._loadingTextDiv = document.createElement("div");
  3919. this._loadingTextDiv.style.position = "absolute";
  3920. this._loadingTextDiv.style.left = "0";
  3921. this._loadingTextDiv.style.top = "50%";
  3922. this._loadingTextDiv.style.marginTop = "80px";
  3923. this._loadingTextDiv.style.width = "100%";
  3924. this._loadingTextDiv.style.height = "20px";
  3925. this._loadingTextDiv.style.fontFamily = "Arial";
  3926. this._loadingTextDiv.style.fontSize = "14px";
  3927. this._loadingTextDiv.style.color = "white";
  3928. this._loadingTextDiv.style.textAlign = "center";
  3929. this._loadingTextDiv.innerHTML = "Loading";
  3930. this._loadingDiv.appendChild(this._loadingTextDiv);
  3931. var imgBack = new Image();
  3932. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAARbSURBVHhe7Z09aFNRFMc716kuLrq4FdyLq4Wi4CAoRQcR0UJBUBdRiuLSIYMo6CA4FF2sgw6CFAdFUOpSQYcWO4hD26UQCfXrIQrx/JJzw1OSWq3NPeL/B4Fy+0jg/HO+7j3vpUcI8b/Q39+/49ihfWdPHT94Yf/e3Se3bd263f8lus218TPn6vV6Ya8Wi/MzNRNmj18iusX9W1evmP1/EKNEIVG6CMbG6E3bt+fT++pHha8NoHdT72bLE8NDg7tGU64gLLndV4Wc4m8j/pS+vr4tGB/DT16v3Fyr8dvBe/jbit8BL0AES9LX1iPAz+BR/hFiLVCynj95dPzNy6fv3IZ/k4L3948Sq7FzYGBg4vLFGxitabuOFCbWNKGrMnbiUuo18KaV6tIHv6YtvL9/nOgE31jCktmrY7k6+/zhE4yP4Vf7hiNqh/BWWEl8mzDol4p22Lf7cIdvdUMEvv0Y2S9fE5S1hLzpqTsPkiep//gFGPnR3Yl7GL5p/xYFBrTwM+iXio3GqpwDGL5p/xYNIX7XG8Q6IJRgdIzf1KBBgafII7oMidhyQtVFaMA2Bt7il4huQRhaXphbcR2g4RXqBzKAGHiCCwGFVUAj/m/RTRDj29cvn10I0PZ3LghH5f4CL1EFlQmqqXK3jDDKFxmhQ3Yt6oQseUZGKmMnTpsOqc8o1F9kBOMjQlOLeqEeIyOc6JV6jYLJD/+XyIFvnzdgl9aXRQ5I2qZDK1SpospMqaoqON/wZZGDciLnMMiXRS7IF4hhqMTNTdk7CFu+LHLhR7BQqBvPDJUUQqCGvCMATHUgBmhWNgApmdOda9YpM+VwRYfuyyIXDK8hBlilNerLIheMZCKGwlUAyru6GlwOgPUbRxADdJ9FAChxXY864viyyEXqPxhc0M2TAfAbatSdRyHtXymhByEdRnE3ky+JnHAIhSA0h74kckETmHoQbSgGwJrCIRMEPSRIBCRIMAhZaYhaggQhJXUJEoRU9mofKwh+F22dLRRfEjlJM7w6KQwCoQpBOKTyJZETjmwRxKqtGV8SOSkNOGjKPQppBEgDDkFgpxdBVGkFgaYQQXRIFQSObk0P5ZFIpAZRHXsQ0r0hCluBWKkuvVbYCkQaCdL5ehBScudJP4yY+rLISdps1NBDEJKXMMmoSfggWC4ZQRR17oFYXph7hSiquIKQ+hJGTX1J5MYSPD/GVdNzsgLBwZVCVyAQAkF0ohiI/c1fS6tNXq9UfEnkhudmIQolsS+J3Hh/UtNDzQLhj42VKJFInqLwFYiUU5ToA+HdfI0JevUpQUAIn+vSz2lHIuUV/dJOIHhOY/IWVWGBIHQtzs88s9zyWBuTgcBLzGOmeNnfF/QslSDgMeQW85i3DOQxuipxAkCyZ8SIm4Omp+7MMlCB59j6sKZcMoM4iIEoeI2J9AKxrFobZx0v4vYInuHFS4J1GQRCAGaLEYQXfyMML5XSQgghhBBCCCH+cXp6vgNhKpSKX/XdOAAAAABJRU5ErkJggg==";
  3933. imgBack.style.position = "absolute";
  3934. imgBack.style.left = "50%";
  3935. imgBack.style.top = "50%";
  3936. imgBack.style.marginLeft = "-50px";
  3937. imgBack.style.marginTop = "-50px";
  3938. imgBack.style.transition = "transform 1.0s ease";
  3939. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  3940. var deg = 360;
  3941. var onTransitionEnd = function () {
  3942. deg += 360;
  3943. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  3944. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  3945. };
  3946. imgBack.addEventListener("transitionend", onTransitionEnd);
  3947. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  3948. this._loadingDiv.appendChild(imgBack);
  3949. var imgFront = new Image();
  3950. imgFront.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAAYJSURBVHhe7Zy/qx1FFMff/2Av2Nvbi4WFiiAEY/OQ2IgQsbCJQoqkCAgpFLXyoZURLfwBIiIpgqZJoYQYlWelNsIrNOxDJcrzfHe+G97dnTl75u7euzv7zgcWHrlnZmfOmXPmzI/NjuM4juM4juM4juM4juM4juM4juM4juM45fPic08/uHf5/CvffH7lnT8PfrtxdHS0n3p+/fHGl5+89/prr5599iEWd8bg0rkXHoFyqehKnlxQpjYSDHTm9JMPsGrHylOPPXofvICKXMcIGtXdf/76AYbm6xyNW9e/eAtKC7rbKLXnvHHx5Sf4auc4Ek7OQkFU1Dap/vv37k/wSjblZANFiFIGzw98hhizwqBgs04mCBdQRNCHidoAEtY+lLIvtSdoGFeyql2ZH57HBH4sE7O+o/r9l+8/ZXUni68+2jsHBQQ9qNRGeP/tSxdSYQX/roUcpL4/f3vtM9TD+jTq92n1LQ7jxF1hhGPtwWL3gGccy8JuS1r8sVWBGXNVdSKMYjBGPUJjCzooiGuSpnwlnnOGP2dhHRSLNgpHp2oMKIriK8TmG4Qh/rwW8D6pps9b9im+LDDipXOqMVJrAngBfg9i98gevWKA+/nnCod3Dr5GfaHaDgidVym6HKRjGIkpqthcAVKGxNqBImbEo66kjCih8AOpNmkUmbMuUrR8kEqiU6FvHZLGAPJ71JCYSyhiBqmwFE2GoD6jLGIfDHtG6EzoU4dK21PCqIRMEF0FGRjFzGDtIkXVAdATvsqfT9CJ0JcOFdYiFIsiMlqYy1YOFpQo2OddqBtyEaq9y+efoVh5oPHoROjLKn0j3JIE5Ka8UqZRtGrMnneX6yVofOhDh94MSbznTcpqmDOt1vyQzOgaJAF4F3JBfIXesrNEGWWmjIX7UBZ6jRJbBMLg/DmJiKUGVHleIpnVNTa+jakzkAviJqLhi4MC9XQGBrZeKJZESSrKy7ik0VGFWhQBRDTHIACKQ5l9nAjy75gya4a2w+Jhs0FJdc0xX/GwUbAqFBkZi7QpJ2w16WUbjFyK9MJF3KaoEM74KhVtLrQOrsmRxkbdHEqmSC/c+EuGnIFkjW7Ih2Kr4CCMIvNG2hrrgLpCjiFloooYCjyYrzCRyvhyBthkIPuQtsZGdnbMTezyDiU71KTC5zr7aVsHbsz2tllrEkS5UHwU1tq1HbtPW4UbeB0O7xx8R5EsMJql+BheUmHjkNVmIRP7LutoM3+D4O4tG7vCkNO9ESZ4lL3J6rKRMPx4qKbD/A0icf8CG7tC7kTahnMTwleuYSrsS7GatRAvfZh1tTm5BmmQCdZ8a0Sefe28xUrRBkmFLKy8KTIKUDRX0Y1xagPgwbaIdeFnQULmKak3xvwNMkVGgok/N5XNoehJvejRlCDl9escI28dJU0tZ++nBTJE9mEF647x5Ehbo4s5hDOKFIU0PdofeA5F5k1q63zIWmQqNI/P3ZubjFTqKxQ3jyjHAOX0RdlgVO9hzRFpczRcjZ3Gbxxpc7Qj6+5pTYF2OFXawNI+yDGf1k2NcvOlzBQeDQ/t7zD7DsEDpJ2xATXaNtDWUS4IzP4DS2ljajAVu57SUkYw245ptxZxA5JiZaJ0DswudGn3kYUy54426EjoT4dZfYbccxC2nI92cDkZHQr96jD4AGkMDKeSy/COBsRe6VTSKFN6irLeaCh3IteQjt1E5+oudsG/b/2DfZ5AqsYo8vMDK9LB1HzSsLWvlGThdxXvC6+NsqyPPWP0pMINtbdsajfVeC6f/GZ+cdAofQoB1d+Hf9waY98I7+RXWab3Lt4zYkjHtTnlOLXHYMsCh1zWeQYehu1zfNPOOiys/d91LAKEBSgh6MJMbSA82AaHofDgAIwbgvVvlLNS11nModMm4UZergLHZBZrodmBuA3lBB1thdorSjkOmATMDwg/UBQVtglqQyx6fbEJ+H3IWIapjYAjAfeIgeCMHldueJvFaqDaAHhwf8qNsEEQ1iQbOoUUGIbCLRc8+Bvfp4jyd2FEijuO4ziO4ziO4ziO4ziO4ziO4ziO4ziOUzw7O/8D0P7rcZ/GEboAAAAASUVORK5CYII=";
  3951. imgFront.style.position = "absolute";
  3952. imgFront.style.left = "50%";
  3953. imgFront.style.top = "50%";
  3954. imgFront.style.marginLeft = "-50px";
  3955. imgFront.style.marginTop = "-50px";
  3956. this._loadingDiv.appendChild(imgFront);
  3957. this._resizeLoadingUI = function () {
  3958. var canvasRect = _this.getRenderingCanvasClientRect();
  3959. _this._loadingDiv.style.position = "absolute";
  3960. _this._loadingDiv.style.left = canvasRect.left + "px";
  3961. _this._loadingDiv.style.top = canvasRect.top + "px";
  3962. _this._loadingDiv.style.width = canvasRect.width + "px";
  3963. _this._loadingDiv.style.height = canvasRect.height + "px";
  3964. };
  3965. this._resizeLoadingUI();
  3966. window.addEventListener("resize", this._resizeLoadingUI);
  3967. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3968. document.body.appendChild(this._loadingDiv);
  3969. setTimeout(function () {
  3970. _this._loadingDiv.style.opacity = "1";
  3971. imgBack.style.transform = "rotateZ(360deg)";
  3972. imgBack.style.webkitTransform = "rotateZ(360deg)";
  3973. }, 0);
  3974. };
  3975. Object.defineProperty(Engine.prototype, "loadingUIText", {
  3976. set: function (text) {
  3977. if (!this._loadingDiv) {
  3978. return;
  3979. }
  3980. this._loadingTextDiv.innerHTML = text;
  3981. },
  3982. enumerable: true,
  3983. configurable: true
  3984. });
  3985. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  3986. get: function () {
  3987. return this._loadingDivBackgroundColor;
  3988. },
  3989. set: function (color) {
  3990. this._loadingDivBackgroundColor = color;
  3991. if (!this._loadingDiv) {
  3992. return;
  3993. }
  3994. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3995. },
  3996. enumerable: true,
  3997. configurable: true
  3998. });
  3999. Engine.prototype.hideLoadingUI = function () {
  4000. var _this = this;
  4001. if (!this._loadingDiv) {
  4002. return;
  4003. }
  4004. var onTransitionEnd = function () {
  4005. if (!_this._loadingDiv) {
  4006. return;
  4007. }
  4008. document.body.removeChild(_this._loadingDiv);
  4009. window.removeEventListener("resize", _this._resizeLoadingUI);
  4010. _this._loadingDiv = null;
  4011. };
  4012. this._loadingDiv.style.opacity = "0";
  4013. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4014. };
  4015. Engine.isSupported = function () {
  4016. try {
  4017. if (navigator.isCocoonJS) {
  4018. return true;
  4019. }
  4020. var tempcanvas = document.createElement("canvas");
  4021. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4022. return gl != null && !!window.WebGLRenderingContext;
  4023. } catch (e) {
  4024. return false;
  4025. }
  4026. };
  4027. Engine._ALPHA_DISABLE = 0;
  4028. Engine._ALPHA_ADD = 1;
  4029. Engine._ALPHA_COMBINE = 2;
  4030. Engine._DELAYLOADSTATE_NONE = 0;
  4031. Engine._DELAYLOADSTATE_LOADED = 1;
  4032. Engine._DELAYLOADSTATE_LOADING = 2;
  4033. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4034. Engine.Epsilon = 0.001;
  4035. Engine.CollisionsEpsilon = 0.001;
  4036. Engine.ShadersRepository = "Babylon/Shaders/";
  4037. return Engine;
  4038. })();
  4039. BABYLON.Engine = Engine;
  4040. })(BABYLON || (BABYLON = {}));
  4041. var BABYLON;
  4042. (function (BABYLON) {
  4043. var Node = (function () {
  4044. function Node(name, scene) {
  4045. this.state = "";
  4046. this.animations = new Array();
  4047. this._childrenFlag = -1;
  4048. this._isEnabled = true;
  4049. this._isReady = true;
  4050. this._currentRenderId = -1;
  4051. this.name = name;
  4052. this.id = name;
  4053. this._scene = scene;
  4054. this._initCache();
  4055. }
  4056. Node.prototype.getScene = function () {
  4057. return this._scene;
  4058. };
  4059. Node.prototype.getEngine = function () {
  4060. return this._scene.getEngine();
  4061. };
  4062. Node.prototype.getWorldMatrix = function () {
  4063. return BABYLON.Matrix.Identity();
  4064. };
  4065. Node.prototype._initCache = function () {
  4066. this._cache = {};
  4067. this._cache.parent = undefined;
  4068. };
  4069. Node.prototype.updateCache = function (force) {
  4070. if (!force && this.isSynchronized())
  4071. return;
  4072. this._cache.parent = this.parent;
  4073. this._updateCache();
  4074. };
  4075. Node.prototype._updateCache = function (ignoreParentClass) {
  4076. };
  4077. Node.prototype._isSynchronized = function () {
  4078. return true;
  4079. };
  4080. Node.prototype.isSynchronizedWithParent = function () {
  4081. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4082. };
  4083. Node.prototype.isSynchronized = function (updateCache) {
  4084. var check = this.hasNewParent();
  4085. check = check || !this.isSynchronizedWithParent();
  4086. check = check || !this._isSynchronized();
  4087. if (updateCache)
  4088. this.updateCache(true);
  4089. return !check;
  4090. };
  4091. Node.prototype.hasNewParent = function (update) {
  4092. if (this._cache.parent === this.parent)
  4093. return false;
  4094. if (update)
  4095. this._cache.parent = this.parent;
  4096. return true;
  4097. };
  4098. Node.prototype.isReady = function () {
  4099. return this._isReady;
  4100. };
  4101. Node.prototype.isEnabled = function () {
  4102. if (!this._isEnabled) {
  4103. return false;
  4104. }
  4105. if (this.parent) {
  4106. return this.parent.isEnabled();
  4107. }
  4108. return true;
  4109. };
  4110. Node.prototype.setEnabled = function (value) {
  4111. this._isEnabled = value;
  4112. };
  4113. Node.prototype.isDescendantOf = function (ancestor) {
  4114. if (this.parent) {
  4115. if (this.parent === ancestor) {
  4116. return true;
  4117. }
  4118. return this.parent.isDescendantOf(ancestor);
  4119. }
  4120. return false;
  4121. };
  4122. Node.prototype._getDescendants = function (list, results) {
  4123. for (var index = 0; index < list.length; index++) {
  4124. var item = list[index];
  4125. if (item.isDescendantOf(this)) {
  4126. results.push(item);
  4127. }
  4128. }
  4129. };
  4130. Node.prototype.getDescendants = function () {
  4131. var results = [];
  4132. this._getDescendants(this._scene.meshes, results);
  4133. this._getDescendants(this._scene.lights, results);
  4134. this._getDescendants(this._scene.cameras, results);
  4135. return results;
  4136. };
  4137. Node.prototype._setReady = function (state) {
  4138. if (state == this._isReady) {
  4139. return;
  4140. }
  4141. if (!state) {
  4142. this._isReady = false;
  4143. return;
  4144. }
  4145. this._isReady = true;
  4146. if (this.onReady) {
  4147. this.onReady(this);
  4148. }
  4149. };
  4150. return Node;
  4151. })();
  4152. BABYLON.Node = Node;
  4153. })(BABYLON || (BABYLON = {}));
  4154. var BABYLON;
  4155. (function (BABYLON) {
  4156. var BoundingSphere = (function () {
  4157. function BoundingSphere(minimum, maximum) {
  4158. this.minimum = minimum;
  4159. this.maximum = maximum;
  4160. this._tempRadiusVector = BABYLON.Vector3.Zero();
  4161. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  4162. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  4163. this.radius = distance * 0.5;
  4164. this.centerWorld = BABYLON.Vector3.Zero();
  4165. this._update(BABYLON.Matrix.Identity());
  4166. }
  4167. BoundingSphere.prototype._update = function (world) {
  4168. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  4169. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  4170. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  4171. };
  4172. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  4173. for (var i = 0; i < 6; i++) {
  4174. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  4175. return false;
  4176. }
  4177. return true;
  4178. };
  4179. BoundingSphere.prototype.intersectsPoint = function (point) {
  4180. var x = this.centerWorld.x - point.x;
  4181. var y = this.centerWorld.y - point.y;
  4182. var z = this.centerWorld.z - point.z;
  4183. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4184. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  4185. return false;
  4186. return true;
  4187. };
  4188. BoundingSphere.Intersects = function (sphere0, sphere1) {
  4189. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  4190. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  4191. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  4192. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4193. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  4194. return false;
  4195. return true;
  4196. };
  4197. return BoundingSphere;
  4198. })();
  4199. BABYLON.BoundingSphere = BoundingSphere;
  4200. })(BABYLON || (BABYLON = {}));
  4201. var BABYLON;
  4202. (function (BABYLON) {
  4203. var BoundingBox = (function () {
  4204. function BoundingBox(minimum, maximum) {
  4205. this.minimum = minimum;
  4206. this.maximum = maximum;
  4207. this.vectors = new Array();
  4208. this.vectorsWorld = new Array();
  4209. this.vectors.push(this.minimum.clone());
  4210. this.vectors.push(this.maximum.clone());
  4211. this.vectors.push(this.minimum.clone());
  4212. this.vectors[2].x = this.maximum.x;
  4213. this.vectors.push(this.minimum.clone());
  4214. this.vectors[3].y = this.maximum.y;
  4215. this.vectors.push(this.minimum.clone());
  4216. this.vectors[4].z = this.maximum.z;
  4217. this.vectors.push(this.maximum.clone());
  4218. this.vectors[5].z = this.minimum.z;
  4219. this.vectors.push(this.maximum.clone());
  4220. this.vectors[6].x = this.minimum.x;
  4221. this.vectors.push(this.maximum.clone());
  4222. this.vectors[7].y = this.minimum.y;
  4223. this.center = this.maximum.add(this.minimum).scale(0.5);
  4224. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  4225. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  4226. for (var index = 0; index < this.vectors.length; index++) {
  4227. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  4228. }
  4229. this.minimumWorld = BABYLON.Vector3.Zero();
  4230. this.maximumWorld = BABYLON.Vector3.Zero();
  4231. this._update(BABYLON.Matrix.Identity());
  4232. }
  4233. BoundingBox.prototype.getWorldMatrix = function () {
  4234. return this._worldMatrix;
  4235. };
  4236. BoundingBox.prototype._update = function (world) {
  4237. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  4238. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  4239. for (var index = 0; index < this.vectors.length; index++) {
  4240. var v = this.vectorsWorld[index];
  4241. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  4242. if (v.x < this.minimumWorld.x)
  4243. this.minimumWorld.x = v.x;
  4244. if (v.y < this.minimumWorld.y)
  4245. this.minimumWorld.y = v.y;
  4246. if (v.z < this.minimumWorld.z)
  4247. this.minimumWorld.z = v.z;
  4248. if (v.x > this.maximumWorld.x)
  4249. this.maximumWorld.x = v.x;
  4250. if (v.y > this.maximumWorld.y)
  4251. this.maximumWorld.y = v.y;
  4252. if (v.z > this.maximumWorld.z)
  4253. this.maximumWorld.z = v.z;
  4254. }
  4255. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  4256. this.center.scaleInPlace(0.5);
  4257. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  4258. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  4259. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  4260. this._worldMatrix = world;
  4261. };
  4262. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  4263. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  4264. };
  4265. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4266. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  4267. };
  4268. BoundingBox.prototype.intersectsPoint = function (point) {
  4269. var delta = BABYLON.Engine.Epsilon;
  4270. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  4271. return false;
  4272. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  4273. return false;
  4274. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  4275. return false;
  4276. return true;
  4277. };
  4278. BoundingBox.prototype.intersectsSphere = function (sphere) {
  4279. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  4280. };
  4281. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  4282. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  4283. return false;
  4284. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  4285. return false;
  4286. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  4287. return false;
  4288. return true;
  4289. };
  4290. BoundingBox.Intersects = function (box0, box1) {
  4291. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  4292. return false;
  4293. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  4294. return false;
  4295. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  4296. return false;
  4297. return true;
  4298. };
  4299. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  4300. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  4301. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  4302. return (num <= (sphereRadius * sphereRadius));
  4303. };
  4304. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  4305. for (var p = 0; p < 6; p++) {
  4306. for (var i = 0; i < 8; i++) {
  4307. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4308. return false;
  4309. }
  4310. }
  4311. }
  4312. return true;
  4313. };
  4314. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  4315. for (var p = 0; p < 6; p++) {
  4316. var inCount = 8;
  4317. for (var i = 0; i < 8; i++) {
  4318. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4319. --inCount;
  4320. } else {
  4321. break;
  4322. }
  4323. }
  4324. if (inCount == 0)
  4325. return false;
  4326. }
  4327. return true;
  4328. };
  4329. return BoundingBox;
  4330. })();
  4331. BABYLON.BoundingBox = BoundingBox;
  4332. })(BABYLON || (BABYLON = {}));
  4333. var BABYLON;
  4334. (function (BABYLON) {
  4335. var computeBoxExtents = function (axis, box) {
  4336. var p = BABYLON.Vector3.Dot(box.center, axis);
  4337. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  4338. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  4339. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  4340. var r = r0 + r1 + r2;
  4341. return {
  4342. min: p - r,
  4343. max: p + r
  4344. };
  4345. };
  4346. var extentsOverlap = function (min0, max0, min1, max1) {
  4347. return !(min0 > max1 || min1 > max0);
  4348. };
  4349. var axisOverlap = function (axis, box0, box1) {
  4350. var result0 = computeBoxExtents(axis, box0);
  4351. var result1 = computeBoxExtents(axis, box1);
  4352. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  4353. };
  4354. var BoundingInfo = (function () {
  4355. function BoundingInfo(minimum, maximum) {
  4356. this.minimum = minimum;
  4357. this.maximum = maximum;
  4358. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  4359. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  4360. }
  4361. BoundingInfo.prototype._update = function (world) {
  4362. this.boundingBox._update(world);
  4363. this.boundingSphere._update(world);
  4364. };
  4365. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  4366. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  4367. return false;
  4368. return this.boundingBox.isInFrustum(frustumPlanes);
  4369. };
  4370. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4371. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  4372. };
  4373. BoundingInfo.prototype._checkCollision = function (collider) {
  4374. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  4375. };
  4376. BoundingInfo.prototype.intersectsPoint = function (point) {
  4377. if (!this.boundingSphere.centerWorld) {
  4378. return false;
  4379. }
  4380. if (!this.boundingSphere.intersectsPoint(point)) {
  4381. return false;
  4382. }
  4383. if (!this.boundingBox.intersectsPoint(point)) {
  4384. return false;
  4385. }
  4386. return true;
  4387. };
  4388. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  4389. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  4390. return false;
  4391. }
  4392. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  4393. return false;
  4394. }
  4395. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  4396. return false;
  4397. }
  4398. if (!precise) {
  4399. return true;
  4400. }
  4401. var box0 = this.boundingBox;
  4402. var box1 = boundingInfo.boundingBox;
  4403. if (!axisOverlap(box0.directions[0], box0, box1))
  4404. return false;
  4405. if (!axisOverlap(box0.directions[1], box0, box1))
  4406. return false;
  4407. if (!axisOverlap(box0.directions[2], box0, box1))
  4408. return false;
  4409. if (!axisOverlap(box1.directions[0], box0, box1))
  4410. return false;
  4411. if (!axisOverlap(box1.directions[1], box0, box1))
  4412. return false;
  4413. if (!axisOverlap(box1.directions[2], box0, box1))
  4414. return false;
  4415. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  4416. return false;
  4417. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  4418. return false;
  4419. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  4420. return false;
  4421. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  4422. return false;
  4423. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  4424. return false;
  4425. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  4426. return false;
  4427. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  4428. return false;
  4429. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  4430. return false;
  4431. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  4432. return false;
  4433. return true;
  4434. };
  4435. return BoundingInfo;
  4436. })();
  4437. BABYLON.BoundingInfo = BoundingInfo;
  4438. })(BABYLON || (BABYLON = {}));
  4439. var __extends = this.__extends || function (d, b) {
  4440. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4441. function __() { this.constructor = d; }
  4442. __.prototype = b.prototype;
  4443. d.prototype = new __();
  4444. };
  4445. var BABYLON;
  4446. (function (BABYLON) {
  4447. var Light = (function (_super) {
  4448. __extends(Light, _super);
  4449. function Light(name, scene) {
  4450. _super.call(this, name, scene);
  4451. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  4452. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  4453. this.intensity = 1.0;
  4454. this.range = Number.MAX_VALUE;
  4455. this.includedOnlyMeshes = new Array();
  4456. this.excludedMeshes = new Array();
  4457. this._excludedMeshesIds = new Array();
  4458. this._includedOnlyMeshesIds = new Array();
  4459. scene.lights.push(this);
  4460. }
  4461. Light.prototype.getShadowGenerator = function () {
  4462. return this._shadowGenerator;
  4463. };
  4464. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4465. };
  4466. Light.prototype._getWorldMatrix = function () {
  4467. return BABYLON.Matrix.Identity();
  4468. };
  4469. Light.prototype.canAffectMesh = function (mesh) {
  4470. if (!mesh) {
  4471. return true;
  4472. }
  4473. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4474. return false;
  4475. }
  4476. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4477. return false;
  4478. }
  4479. return true;
  4480. };
  4481. Light.prototype.getWorldMatrix = function () {
  4482. this._currentRenderId = this.getScene().getRenderId();
  4483. var worldMatrix = this._getWorldMatrix();
  4484. if (this.parent && this.parent.getWorldMatrix) {
  4485. if (!this._parentedWorldMatrix) {
  4486. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4487. }
  4488. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4489. return this._parentedWorldMatrix;
  4490. }
  4491. return worldMatrix;
  4492. };
  4493. Light.prototype.dispose = function () {
  4494. if (this._shadowGenerator) {
  4495. this._shadowGenerator.dispose();
  4496. this._shadowGenerator = null;
  4497. }
  4498. var index = this.getScene().lights.indexOf(this);
  4499. this.getScene().lights.splice(index, 1);
  4500. };
  4501. return Light;
  4502. })(BABYLON.Node);
  4503. BABYLON.Light = Light;
  4504. })(BABYLON || (BABYLON = {}));
  4505. var __extends = this.__extends || function (d, b) {
  4506. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4507. function __() { this.constructor = d; }
  4508. __.prototype = b.prototype;
  4509. d.prototype = new __();
  4510. };
  4511. var BABYLON;
  4512. (function (BABYLON) {
  4513. var PointLight = (function (_super) {
  4514. __extends(PointLight, _super);
  4515. function PointLight(name, position, scene) {
  4516. _super.call(this, name, scene);
  4517. this.position = position;
  4518. }
  4519. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  4520. if (this.parent && this.parent.getWorldMatrix) {
  4521. if (!this._transformedPosition) {
  4522. this._transformedPosition = BABYLON.Vector3.Zero();
  4523. }
  4524. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4525. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  4526. return;
  4527. }
  4528. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  4529. };
  4530. PointLight.prototype.getShadowGenerator = function () {
  4531. return null;
  4532. };
  4533. PointLight.prototype._getWorldMatrix = function () {
  4534. if (!this._worldMatrix) {
  4535. this._worldMatrix = BABYLON.Matrix.Identity();
  4536. }
  4537. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4538. return this._worldMatrix;
  4539. };
  4540. return PointLight;
  4541. })(BABYLON.Light);
  4542. BABYLON.PointLight = PointLight;
  4543. })(BABYLON || (BABYLON = {}));
  4544. var __extends = this.__extends || function (d, b) {
  4545. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4546. function __() { this.constructor = d; }
  4547. __.prototype = b.prototype;
  4548. d.prototype = new __();
  4549. };
  4550. var BABYLON;
  4551. (function (BABYLON) {
  4552. var SpotLight = (function (_super) {
  4553. __extends(SpotLight, _super);
  4554. function SpotLight(name, position, direction, angle, exponent, scene) {
  4555. _super.call(this, name, scene);
  4556. this.position = position;
  4557. this.direction = direction;
  4558. this.angle = angle;
  4559. this.exponent = exponent;
  4560. }
  4561. SpotLight.prototype.setDirectionToTarget = function (target) {
  4562. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4563. return this.direction;
  4564. };
  4565. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  4566. var normalizeDirection;
  4567. if (this.parent && this.parent.getWorldMatrix) {
  4568. if (!this._transformedDirection) {
  4569. this._transformedDirection = BABYLON.Vector3.Zero();
  4570. }
  4571. if (!this._transformedPosition) {
  4572. this._transformedPosition = BABYLON.Vector3.Zero();
  4573. }
  4574. var parentWorldMatrix = this.parent.getWorldMatrix();
  4575. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  4576. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  4577. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  4578. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  4579. } else {
  4580. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  4581. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4582. }
  4583. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  4584. };
  4585. SpotLight.prototype._getWorldMatrix = function () {
  4586. if (!this._worldMatrix) {
  4587. this._worldMatrix = BABYLON.Matrix.Identity();
  4588. }
  4589. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4590. return this._worldMatrix;
  4591. };
  4592. return SpotLight;
  4593. })(BABYLON.Light);
  4594. BABYLON.SpotLight = SpotLight;
  4595. })(BABYLON || (BABYLON = {}));
  4596. var __extends = this.__extends || function (d, b) {
  4597. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4598. function __() { this.constructor = d; }
  4599. __.prototype = b.prototype;
  4600. d.prototype = new __();
  4601. };
  4602. var BABYLON;
  4603. (function (BABYLON) {
  4604. var DirectionalLight = (function (_super) {
  4605. __extends(DirectionalLight, _super);
  4606. function DirectionalLight(name, direction, scene) {
  4607. _super.call(this, name, scene);
  4608. this.direction = direction;
  4609. this.position = direction.scale(-1);
  4610. }
  4611. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  4612. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4613. return this.direction;
  4614. };
  4615. DirectionalLight.prototype._computeTransformedPosition = function () {
  4616. if (this.parent && this.parent.getWorldMatrix) {
  4617. if (!this._transformedPosition) {
  4618. this._transformedPosition = BABYLON.Vector3.Zero();
  4619. }
  4620. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4621. return true;
  4622. }
  4623. return false;
  4624. };
  4625. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  4626. if (this.parent && this.parent.getWorldMatrix) {
  4627. if (!this._transformedDirection) {
  4628. this._transformedDirection = BABYLON.Vector3.Zero();
  4629. }
  4630. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  4631. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  4632. return;
  4633. }
  4634. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  4635. };
  4636. DirectionalLight.prototype._getWorldMatrix = function () {
  4637. if (!this._worldMatrix) {
  4638. this._worldMatrix = BABYLON.Matrix.Identity();
  4639. }
  4640. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4641. return this._worldMatrix;
  4642. };
  4643. return DirectionalLight;
  4644. })(BABYLON.Light);
  4645. BABYLON.DirectionalLight = DirectionalLight;
  4646. })(BABYLON || (BABYLON = {}));
  4647. var BABYLON;
  4648. (function (BABYLON) {
  4649. var ShadowGenerator = (function () {
  4650. function ShadowGenerator(mapSize, light) {
  4651. var _this = this;
  4652. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4653. this._darkness = 0;
  4654. this._transparencyShadow = false;
  4655. this._viewMatrix = BABYLON.Matrix.Zero();
  4656. this._projectionMatrix = BABYLON.Matrix.Zero();
  4657. this._transformMatrix = BABYLON.Matrix.Zero();
  4658. this._worldViewProjection = BABYLON.Matrix.Zero();
  4659. this._light = light;
  4660. this._scene = light.getScene();
  4661. light._shadowGenerator = this;
  4662. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  4663. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4664. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4665. this._shadowMap.renderParticles = false;
  4666. var renderSubMesh = function (subMesh) {
  4667. var mesh = subMesh.getRenderingMesh();
  4668. var scene = _this._scene;
  4669. var engine = scene.getEngine();
  4670. engine.setState(subMesh.getMaterial().backFaceCulling);
  4671. var batch = mesh._getInstancesRenderList(subMesh._id);
  4672. if (batch.mustReturn) {
  4673. return;
  4674. }
  4675. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  4676. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  4677. engine.enableEffect(_this._effect);
  4678. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  4679. var material = subMesh.getMaterial();
  4680. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  4681. if (material && material.needAlphaTesting()) {
  4682. var alphaTexture = material.getAlphaTestTexture();
  4683. _this._effect.setTexture("diffuseSampler", alphaTexture);
  4684. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  4685. }
  4686. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  4687. if (useBones) {
  4688. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  4689. }
  4690. if (hardwareInstancedRendering) {
  4691. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  4692. } else {
  4693. if (batch.renderSelf[subMesh._id]) {
  4694. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  4695. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  4696. }
  4697. if (batch.visibleInstances[subMesh._id]) {
  4698. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  4699. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  4700. _this._effect.setMatrix("world", instance.getWorldMatrix());
  4701. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  4702. }
  4703. }
  4704. }
  4705. } else {
  4706. _this._shadowMap.resetRefreshCounter();
  4707. }
  4708. };
  4709. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  4710. var index;
  4711. for (index = 0; index < opaqueSubMeshes.length; index++) {
  4712. renderSubMesh(opaqueSubMeshes.data[index]);
  4713. }
  4714. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  4715. renderSubMesh(alphaTestSubMeshes.data[index]);
  4716. }
  4717. if (_this._transparencyShadow) {
  4718. for (index = 0; index < transparentSubMeshes.length; index++) {
  4719. renderSubMesh(transparentSubMeshes.data[index]);
  4720. }
  4721. }
  4722. };
  4723. }
  4724. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  4725. get: function () {
  4726. return ShadowGenerator._FILTER_NONE;
  4727. },
  4728. enumerable: true,
  4729. configurable: true
  4730. });
  4731. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  4732. get: function () {
  4733. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  4734. },
  4735. enumerable: true,
  4736. configurable: true
  4737. });
  4738. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  4739. get: function () {
  4740. return ShadowGenerator._FILTER_POISSONSAMPLING;
  4741. },
  4742. enumerable: true,
  4743. configurable: true
  4744. });
  4745. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  4746. get: function () {
  4747. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4748. },
  4749. set: function (value) {
  4750. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  4751. },
  4752. enumerable: true,
  4753. configurable: true
  4754. });
  4755. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  4756. get: function () {
  4757. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  4758. },
  4759. set: function (value) {
  4760. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  4761. },
  4762. enumerable: true,
  4763. configurable: true
  4764. });
  4765. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  4766. var defines = [];
  4767. if (this.useVarianceShadowMap) {
  4768. defines.push("#define VSM");
  4769. }
  4770. var attribs = [BABYLON.VertexBuffer.PositionKind];
  4771. var mesh = subMesh.getMesh();
  4772. var material = subMesh.getMaterial();
  4773. if (material && material.needAlphaTesting()) {
  4774. defines.push("#define ALPHATEST");
  4775. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  4776. attribs.push(BABYLON.VertexBuffer.UVKind);
  4777. defines.push("#define UV1");
  4778. }
  4779. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  4780. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  4781. defines.push("#define UV2");
  4782. }
  4783. }
  4784. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  4785. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  4786. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  4787. defines.push("#define BONES");
  4788. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  4789. }
  4790. if (useInstances) {
  4791. defines.push("#define INSTANCES");
  4792. attribs.push("world0");
  4793. attribs.push("world1");
  4794. attribs.push("world2");
  4795. attribs.push("world3");
  4796. }
  4797. var join = defines.join("\n");
  4798. if (this._cachedDefines != join) {
  4799. this._cachedDefines = join;
  4800. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  4801. }
  4802. return this._effect.isReady();
  4803. };
  4804. ShadowGenerator.prototype.getShadowMap = function () {
  4805. return this._shadowMap;
  4806. };
  4807. ShadowGenerator.prototype.getLight = function () {
  4808. return this._light;
  4809. };
  4810. ShadowGenerator.prototype.getTransformMatrix = function () {
  4811. var lightPosition = this._light.position;
  4812. var lightDirection = this._light.direction;
  4813. if (this._light._computeTransformedPosition()) {
  4814. lightPosition = this._light._transformedPosition;
  4815. }
  4816. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  4817. this._cachedPosition = lightPosition.clone();
  4818. this._cachedDirection = lightDirection.clone();
  4819. var activeCamera = this._scene.activeCamera;
  4820. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  4821. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  4822. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  4823. }
  4824. return this._transformMatrix;
  4825. };
  4826. ShadowGenerator.prototype.getDarkness = function () {
  4827. return this._darkness;
  4828. };
  4829. ShadowGenerator.prototype.setDarkness = function (darkness) {
  4830. if (darkness >= 1.0)
  4831. this._darkness = 1.0;
  4832. else if (darkness <= 0.0)
  4833. this._darkness = 0.0;
  4834. else
  4835. this._darkness = darkness;
  4836. };
  4837. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  4838. this._transparencyShadow = hasShadow;
  4839. };
  4840. ShadowGenerator.prototype.dispose = function () {
  4841. this._shadowMap.dispose();
  4842. };
  4843. ShadowGenerator._FILTER_NONE = 0;
  4844. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  4845. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  4846. return ShadowGenerator;
  4847. })();
  4848. BABYLON.ShadowGenerator = ShadowGenerator;
  4849. })(BABYLON || (BABYLON = {}));
  4850. var __extends = this.__extends || function (d, b) {
  4851. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4852. function __() { this.constructor = d; }
  4853. __.prototype = b.prototype;
  4854. d.prototype = new __();
  4855. };
  4856. var BABYLON;
  4857. (function (BABYLON) {
  4858. var HemisphericLight = (function (_super) {
  4859. __extends(HemisphericLight, _super);
  4860. function HemisphericLight(name, direction, scene) {
  4861. _super.call(this, name, scene);
  4862. this.direction = direction;
  4863. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  4864. }
  4865. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  4866. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  4867. return this.direction;
  4868. };
  4869. HemisphericLight.prototype.getShadowGenerator = function () {
  4870. return null;
  4871. };
  4872. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  4873. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4874. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  4875. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  4876. };
  4877. HemisphericLight.prototype._getWorldMatrix = function () {
  4878. if (!this._worldMatrix) {
  4879. this._worldMatrix = BABYLON.Matrix.Identity();
  4880. }
  4881. return this._worldMatrix;
  4882. };
  4883. return HemisphericLight;
  4884. })(BABYLON.Light);
  4885. BABYLON.HemisphericLight = HemisphericLight;
  4886. })(BABYLON || (BABYLON = {}));
  4887. var BABYLON;
  4888. (function (BABYLON) {
  4889. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  4890. if (boxMin.x > sphereCenter.x + sphereRadius)
  4891. return false;
  4892. if (sphereCenter.x - sphereRadius > boxMax.x)
  4893. return false;
  4894. if (boxMin.y > sphereCenter.y + sphereRadius)
  4895. return false;
  4896. if (sphereCenter.y - sphereRadius > boxMax.y)
  4897. return false;
  4898. if (boxMin.z > sphereCenter.z + sphereRadius)
  4899. return false;
  4900. if (sphereCenter.z - sphereRadius > boxMax.z)
  4901. return false;
  4902. return true;
  4903. };
  4904. var getLowestRoot = function (a, b, c, maxR) {
  4905. var determinant = b * b - 4.0 * a * c;
  4906. var result = { root: 0, found: false };
  4907. if (determinant < 0)
  4908. return result;
  4909. var sqrtD = Math.sqrt(determinant);
  4910. var r1 = (-b - sqrtD) / (2.0 * a);
  4911. var r2 = (-b + sqrtD) / (2.0 * a);
  4912. if (r1 > r2) {
  4913. var temp = r2;
  4914. r2 = r1;
  4915. r1 = temp;
  4916. }
  4917. if (r1 > 0 && r1 < maxR) {
  4918. result.root = r1;
  4919. result.found = true;
  4920. return result;
  4921. }
  4922. if (r2 > 0 && r2 < maxR) {
  4923. result.root = r2;
  4924. result.found = true;
  4925. return result;
  4926. }
  4927. return result;
  4928. };
  4929. var Collider = (function () {
  4930. function Collider() {
  4931. this.radius = new BABYLON.Vector3(1, 1, 1);
  4932. this.retry = 0;
  4933. this.basePointWorld = BABYLON.Vector3.Zero();
  4934. this.velocityWorld = BABYLON.Vector3.Zero();
  4935. this.normalizedVelocity = BABYLON.Vector3.Zero();
  4936. this._collisionPoint = BABYLON.Vector3.Zero();
  4937. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  4938. this._tempVector = BABYLON.Vector3.Zero();
  4939. this._tempVector2 = BABYLON.Vector3.Zero();
  4940. this._tempVector3 = BABYLON.Vector3.Zero();
  4941. this._tempVector4 = BABYLON.Vector3.Zero();
  4942. this._edge = BABYLON.Vector3.Zero();
  4943. this._baseToVertex = BABYLON.Vector3.Zero();
  4944. this._destinationPoint = BABYLON.Vector3.Zero();
  4945. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  4946. this._displacementVector = BABYLON.Vector3.Zero();
  4947. }
  4948. Collider.prototype._initialize = function (source, dir, e) {
  4949. this.velocity = dir;
  4950. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  4951. this.basePoint = source;
  4952. source.multiplyToRef(this.radius, this.basePointWorld);
  4953. dir.multiplyToRef(this.radius, this.velocityWorld);
  4954. this.velocityWorldLength = this.velocityWorld.length();
  4955. this.epsilon = e;
  4956. this.collisionFound = false;
  4957. };
  4958. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  4959. pa.subtractToRef(point, this._tempVector);
  4960. pb.subtractToRef(point, this._tempVector2);
  4961. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  4962. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4963. if (d < 0)
  4964. return false;
  4965. pc.subtractToRef(point, this._tempVector3);
  4966. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  4967. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4968. if (d < 0)
  4969. return false;
  4970. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  4971. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4972. return d >= 0;
  4973. };
  4974. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  4975. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  4976. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  4977. if (distance > this.velocityWorldLength + max + sphereRadius) {
  4978. return false;
  4979. }
  4980. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  4981. return false;
  4982. return true;
  4983. };
  4984. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  4985. var t0;
  4986. var embeddedInPlane = false;
  4987. if (!subMesh._trianglePlanes) {
  4988. subMesh._trianglePlanes = [];
  4989. }
  4990. if (!subMesh._trianglePlanes[faceIndex]) {
  4991. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  4992. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  4993. }
  4994. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  4995. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  4996. return;
  4997. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  4998. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  4999. if (normalDotVelocity == 0) {
  5000. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5001. return;
  5002. embeddedInPlane = true;
  5003. t0 = 0;
  5004. } else {
  5005. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5006. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5007. if (t0 > t1) {
  5008. var temp = t1;
  5009. t1 = t0;
  5010. t0 = temp;
  5011. }
  5012. if (t0 > 1.0 || t1 < 0.0)
  5013. return;
  5014. if (t0 < 0)
  5015. t0 = 0;
  5016. if (t0 > 1.0)
  5017. t0 = 1.0;
  5018. }
  5019. this._collisionPoint.copyFromFloats(0, 0, 0);
  5020. var found = false;
  5021. var t = 1.0;
  5022. if (!embeddedInPlane) {
  5023. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5024. this.velocity.scaleToRef(t0, this._tempVector);
  5025. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5026. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5027. found = true;
  5028. t = t0;
  5029. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5030. }
  5031. }
  5032. if (!found) {
  5033. var velocitySquaredLength = this.velocity.lengthSquared();
  5034. var a = velocitySquaredLength;
  5035. this.basePoint.subtractToRef(p1, this._tempVector);
  5036. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5037. var c = this._tempVector.lengthSquared() - 1.0;
  5038. var lowestRoot = getLowestRoot(a, b, c, t);
  5039. if (lowestRoot.found) {
  5040. t = lowestRoot.root;
  5041. found = true;
  5042. this._collisionPoint.copyFrom(p1);
  5043. }
  5044. this.basePoint.subtractToRef(p2, this._tempVector);
  5045. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5046. c = this._tempVector.lengthSquared() - 1.0;
  5047. lowestRoot = getLowestRoot(a, b, c, t);
  5048. if (lowestRoot.found) {
  5049. t = lowestRoot.root;
  5050. found = true;
  5051. this._collisionPoint.copyFrom(p2);
  5052. }
  5053. this.basePoint.subtractToRef(p3, this._tempVector);
  5054. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5055. c = this._tempVector.lengthSquared() - 1.0;
  5056. lowestRoot = getLowestRoot(a, b, c, t);
  5057. if (lowestRoot.found) {
  5058. t = lowestRoot.root;
  5059. found = true;
  5060. this._collisionPoint.copyFrom(p3);
  5061. }
  5062. p2.subtractToRef(p1, this._edge);
  5063. p1.subtractToRef(this.basePoint, this._baseToVertex);
  5064. var edgeSquaredLength = this._edge.lengthSquared();
  5065. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5066. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5067. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5068. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5069. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5070. lowestRoot = getLowestRoot(a, b, c, t);
  5071. if (lowestRoot.found) {
  5072. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5073. if (f >= 0.0 && f <= 1.0) {
  5074. t = lowestRoot.root;
  5075. found = true;
  5076. this._edge.scaleInPlace(f);
  5077. p1.addToRef(this._edge, this._collisionPoint);
  5078. }
  5079. }
  5080. p3.subtractToRef(p2, this._edge);
  5081. p2.subtractToRef(this.basePoint, this._baseToVertex);
  5082. edgeSquaredLength = this._edge.lengthSquared();
  5083. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5084. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5085. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5086. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5087. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5088. lowestRoot = getLowestRoot(a, b, c, t);
  5089. if (lowestRoot.found) {
  5090. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5091. if (f >= 0.0 && f <= 1.0) {
  5092. t = lowestRoot.root;
  5093. found = true;
  5094. this._edge.scaleInPlace(f);
  5095. p2.addToRef(this._edge, this._collisionPoint);
  5096. }
  5097. }
  5098. p1.subtractToRef(p3, this._edge);
  5099. p3.subtractToRef(this.basePoint, this._baseToVertex);
  5100. edgeSquaredLength = this._edge.lengthSquared();
  5101. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5102. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5103. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5104. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5105. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5106. lowestRoot = getLowestRoot(a, b, c, t);
  5107. if (lowestRoot.found) {
  5108. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5109. if (f >= 0.0 && f <= 1.0) {
  5110. t = lowestRoot.root;
  5111. found = true;
  5112. this._edge.scaleInPlace(f);
  5113. p3.addToRef(this._edge, this._collisionPoint);
  5114. }
  5115. }
  5116. }
  5117. if (found) {
  5118. var distToCollision = t * this.velocity.length();
  5119. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  5120. if (!this.intersectionPoint) {
  5121. this.intersectionPoint = this._collisionPoint.clone();
  5122. } else {
  5123. this.intersectionPoint.copyFrom(this._collisionPoint);
  5124. }
  5125. this.nearestDistance = distToCollision;
  5126. this.collisionFound = true;
  5127. this.collidedMesh = subMesh.getMesh();
  5128. }
  5129. }
  5130. };
  5131. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  5132. for (var i = indexStart; i < indexEnd; i += 3) {
  5133. var p1 = pts[indices[i] - decal];
  5134. var p2 = pts[indices[i + 1] - decal];
  5135. var p3 = pts[indices[i + 2] - decal];
  5136. this._testTriangle(i, subMesh, p3, p2, p1);
  5137. }
  5138. };
  5139. Collider.prototype._getResponse = function (pos, vel) {
  5140. pos.addToRef(vel, this._destinationPoint);
  5141. vel.scaleInPlace((this.nearestDistance / vel.length()));
  5142. this.basePoint.addToRef(vel, pos);
  5143. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  5144. this._slidePlaneNormal.normalize();
  5145. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  5146. pos.addInPlace(this._displacementVector);
  5147. this.intersectionPoint.addInPlace(this._displacementVector);
  5148. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  5149. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  5150. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  5151. };
  5152. return Collider;
  5153. })();
  5154. BABYLON.Collider = Collider;
  5155. })(BABYLON || (BABYLON = {}));
  5156. var __extends = this.__extends || function (d, b) {
  5157. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5158. function __() { this.constructor = d; }
  5159. __.prototype = b.prototype;
  5160. d.prototype = new __();
  5161. };
  5162. var BABYLON;
  5163. (function (BABYLON) {
  5164. var Camera = (function (_super) {
  5165. __extends(Camera, _super);
  5166. function Camera(name, position, scene) {
  5167. _super.call(this, name, scene);
  5168. this.position = position;
  5169. this.upVector = BABYLON.Vector3.Up();
  5170. this.orthoLeft = null;
  5171. this.orthoRight = null;
  5172. this.orthoBottom = null;
  5173. this.orthoTop = null;
  5174. this.fov = 0.8;
  5175. this.minZ = 1.0;
  5176. this.maxZ = 10000.0;
  5177. this.inertia = 0.9;
  5178. this.mode = Camera.PERSPECTIVE_CAMERA;
  5179. this.isIntermediate = false;
  5180. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  5181. this.subCameras = [];
  5182. this.layerMask = 0xFFFFFFFF;
  5183. this._computedViewMatrix = BABYLON.Matrix.Identity();
  5184. this._projectionMatrix = new BABYLON.Matrix();
  5185. this._postProcesses = new Array();
  5186. this._postProcessesTakenIndices = [];
  5187. scene.cameras.push(this);
  5188. if (!scene.activeCamera) {
  5189. scene.activeCamera = this;
  5190. }
  5191. }
  5192. Camera.prototype._initCache = function () {
  5193. _super.prototype._initCache.call(this);
  5194. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5195. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5196. this._cache.mode = undefined;
  5197. this._cache.minZ = undefined;
  5198. this._cache.maxZ = undefined;
  5199. this._cache.fov = undefined;
  5200. this._cache.aspectRatio = undefined;
  5201. this._cache.orthoLeft = undefined;
  5202. this._cache.orthoRight = undefined;
  5203. this._cache.orthoBottom = undefined;
  5204. this._cache.orthoTop = undefined;
  5205. this._cache.renderWidth = undefined;
  5206. this._cache.renderHeight = undefined;
  5207. };
  5208. Camera.prototype._updateCache = function (ignoreParentClass) {
  5209. if (!ignoreParentClass) {
  5210. _super.prototype._updateCache.call(this);
  5211. }
  5212. var engine = this.getEngine();
  5213. this._cache.position.copyFrom(this.position);
  5214. this._cache.upVector.copyFrom(this.upVector);
  5215. this._cache.mode = this.mode;
  5216. this._cache.minZ = this.minZ;
  5217. this._cache.maxZ = this.maxZ;
  5218. this._cache.fov = this.fov;
  5219. this._cache.aspectRatio = engine.getAspectRatio(this);
  5220. this._cache.orthoLeft = this.orthoLeft;
  5221. this._cache.orthoRight = this.orthoRight;
  5222. this._cache.orthoBottom = this.orthoBottom;
  5223. this._cache.orthoTop = this.orthoTop;
  5224. this._cache.renderWidth = engine.getRenderWidth();
  5225. this._cache.renderHeight = engine.getRenderHeight();
  5226. };
  5227. Camera.prototype._updateFromScene = function () {
  5228. this.updateCache();
  5229. this._update();
  5230. };
  5231. Camera.prototype._isSynchronized = function () {
  5232. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  5233. };
  5234. Camera.prototype._isSynchronizedViewMatrix = function () {
  5235. if (!_super.prototype._isSynchronized.call(this))
  5236. return false;
  5237. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  5238. };
  5239. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  5240. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  5241. if (!check) {
  5242. return false;
  5243. }
  5244. var engine = this.getEngine();
  5245. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5246. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  5247. } else {
  5248. check = this._cache.orthoLeft === this.orthoLeft && this._cache.orthoRight === this.orthoRight && this._cache.orthoBottom === this.orthoBottom && this._cache.orthoTop === this.orthoTop && this._cache.renderWidth === engine.getRenderWidth() && this._cache.renderHeight === engine.getRenderHeight();
  5249. }
  5250. return check;
  5251. };
  5252. Camera.prototype.attachControl = function (element) {
  5253. };
  5254. Camera.prototype.detachControl = function (element) {
  5255. };
  5256. Camera.prototype._update = function () {
  5257. };
  5258. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  5259. if (typeof insertAt === "undefined") { insertAt = null; }
  5260. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  5261. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  5262. return 0;
  5263. }
  5264. if (insertAt == null || insertAt < 0) {
  5265. this._postProcesses.push(postProcess);
  5266. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  5267. return this._postProcesses.length - 1;
  5268. }
  5269. var add = 0;
  5270. if (this._postProcesses[insertAt]) {
  5271. var start = this._postProcesses.length - 1;
  5272. for (var i = start; i >= insertAt + 1; --i) {
  5273. this._postProcesses[i + 1] = this._postProcesses[i];
  5274. }
  5275. add = 1;
  5276. }
  5277. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5278. if (this._postProcessesTakenIndices[i] < insertAt) {
  5279. continue;
  5280. }
  5281. start = this._postProcessesTakenIndices.length - 1;
  5282. for (var j = start; j >= i; --j) {
  5283. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  5284. }
  5285. this._postProcessesTakenIndices[i] = insertAt;
  5286. break;
  5287. }
  5288. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  5289. this._postProcessesTakenIndices.push(insertAt);
  5290. }
  5291. var result = insertAt + add;
  5292. this._postProcesses[result] = postProcess;
  5293. return result;
  5294. };
  5295. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  5296. if (typeof atIndices === "undefined") { atIndices = null; }
  5297. var result = [];
  5298. if (!atIndices) {
  5299. var length = this._postProcesses.length;
  5300. for (var i = 0; i < length; i++) {
  5301. if (this._postProcesses[i] !== postProcess) {
  5302. continue;
  5303. }
  5304. delete this._postProcesses[i];
  5305. var index = this._postProcessesTakenIndices.indexOf(i);
  5306. this._postProcessesTakenIndices.splice(index, 1);
  5307. }
  5308. } else {
  5309. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  5310. for (i = 0; i < atIndices.length; i++) {
  5311. var foundPostProcess = this._postProcesses[atIndices[i]];
  5312. if (foundPostProcess !== postProcess) {
  5313. result.push(i);
  5314. continue;
  5315. }
  5316. delete this._postProcesses[atIndices[i]];
  5317. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  5318. this._postProcessesTakenIndices.splice(index, 1);
  5319. }
  5320. }
  5321. return result;
  5322. };
  5323. Camera.prototype.getWorldMatrix = function () {
  5324. if (!this._worldMatrix) {
  5325. this._worldMatrix = BABYLON.Matrix.Identity();
  5326. }
  5327. var viewMatrix = this.getViewMatrix();
  5328. viewMatrix.invertToRef(this._worldMatrix);
  5329. return this._worldMatrix;
  5330. };
  5331. Camera.prototype._getViewMatrix = function () {
  5332. return BABYLON.Matrix.Identity();
  5333. };
  5334. Camera.prototype.getViewMatrix = function () {
  5335. this._computedViewMatrix = this._computeViewMatrix();
  5336. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  5337. return this._computedViewMatrix;
  5338. }
  5339. if (!this._worldMatrix) {
  5340. this._worldMatrix = BABYLON.Matrix.Identity();
  5341. }
  5342. this._computedViewMatrix.invertToRef(this._worldMatrix);
  5343. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  5344. this._computedViewMatrix.invert();
  5345. this._currentRenderId = this.getScene().getRenderId();
  5346. return this._computedViewMatrix;
  5347. };
  5348. Camera.prototype._computeViewMatrix = function (force) {
  5349. if (!force && this._isSynchronizedViewMatrix()) {
  5350. return this._computedViewMatrix;
  5351. }
  5352. this._computedViewMatrix = this._getViewMatrix();
  5353. if (!this.parent || !this.parent.getWorldMatrix) {
  5354. this._currentRenderId = this.getScene().getRenderId();
  5355. }
  5356. return this._computedViewMatrix;
  5357. };
  5358. Camera.prototype.getProjectionMatrix = function (force) {
  5359. if (!force && this._isSynchronizedProjectionMatrix()) {
  5360. return this._projectionMatrix;
  5361. }
  5362. var engine = this.getEngine();
  5363. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5364. if (this.minZ <= 0) {
  5365. this.minZ = 0.1;
  5366. }
  5367. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  5368. return this._projectionMatrix;
  5369. }
  5370. var halfWidth = engine.getRenderWidth() / 2.0;
  5371. var halfHeight = engine.getRenderHeight() / 2.0;
  5372. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  5373. return this._projectionMatrix;
  5374. };
  5375. Camera.prototype.dispose = function () {
  5376. var index = this.getScene().cameras.indexOf(this);
  5377. this.getScene().cameras.splice(index, 1);
  5378. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5379. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  5380. }
  5381. };
  5382. Camera.PERSPECTIVE_CAMERA = 0;
  5383. Camera.ORTHOGRAPHIC_CAMERA = 1;
  5384. return Camera;
  5385. })(BABYLON.Node);
  5386. BABYLON.Camera = Camera;
  5387. })(BABYLON || (BABYLON = {}));
  5388. var __extends = this.__extends || function (d, b) {
  5389. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5390. function __() { this.constructor = d; }
  5391. __.prototype = b.prototype;
  5392. d.prototype = new __();
  5393. };
  5394. var BABYLON;
  5395. (function (BABYLON) {
  5396. var TargetCamera = (function (_super) {
  5397. __extends(TargetCamera, _super);
  5398. function TargetCamera(name, position, scene) {
  5399. _super.call(this, name, position, scene);
  5400. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5401. this.cameraRotation = new BABYLON.Vector2(0, 0);
  5402. this.rotation = new BABYLON.Vector3(0, 0, 0);
  5403. this.speed = 2.0;
  5404. this.noRotationConstraint = false;
  5405. this.lockedTarget = null;
  5406. this._currentTarget = BABYLON.Vector3.Zero();
  5407. this._viewMatrix = BABYLON.Matrix.Zero();
  5408. this._camMatrix = BABYLON.Matrix.Zero();
  5409. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  5410. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  5411. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  5412. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  5413. this._lookAtTemp = BABYLON.Matrix.Zero();
  5414. this._tempMatrix = BABYLON.Matrix.Zero();
  5415. }
  5416. TargetCamera.prototype._getLockedTargetPosition = function () {
  5417. if (!this.lockedTarget) {
  5418. return null;
  5419. }
  5420. return this.lockedTarget.position || this.lockedTarget;
  5421. };
  5422. TargetCamera.prototype._initCache = function () {
  5423. _super.prototype._initCache.call(this);
  5424. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5425. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5426. };
  5427. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  5428. if (!ignoreParentClass) {
  5429. _super.prototype._updateCache.call(this);
  5430. }
  5431. var lockedTargetPosition = this._getLockedTargetPosition();
  5432. if (!lockedTargetPosition) {
  5433. this._cache.lockedTarget = null;
  5434. } else {
  5435. if (!this._cache.lockedTarget) {
  5436. this._cache.lockedTarget = lockedTargetPosition.clone();
  5437. } else {
  5438. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  5439. }
  5440. }
  5441. this._cache.rotation.copyFrom(this.rotation);
  5442. };
  5443. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  5444. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  5445. return false;
  5446. }
  5447. var lockedTargetPosition = this._getLockedTargetPosition();
  5448. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  5449. };
  5450. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  5451. return this.speed * ((BABYLON.Tools.GetDeltaTime() / (BABYLON.Tools.GetFps() * 10.0)));
  5452. };
  5453. TargetCamera.prototype.setTarget = function (target) {
  5454. this.upVector.normalize();
  5455. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  5456. this._camMatrix.invert();
  5457. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  5458. var vDir = target.subtract(this.position);
  5459. if (vDir.x >= 0.0) {
  5460. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5461. } else {
  5462. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5463. }
  5464. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5465. if (isNaN(this.rotation.x)) {
  5466. this.rotation.x = 0;
  5467. }
  5468. if (isNaN(this.rotation.y)) {
  5469. this.rotation.y = 0;
  5470. }
  5471. if (isNaN(this.rotation.z)) {
  5472. this.rotation.z = 0;
  5473. }
  5474. };
  5475. TargetCamera.prototype.getTarget = function () {
  5476. return this._currentTarget;
  5477. };
  5478. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5479. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5480. };
  5481. TargetCamera.prototype._updatePosition = function () {
  5482. this.position.addInPlace(this.cameraDirection);
  5483. };
  5484. TargetCamera.prototype._update = function () {
  5485. var needToMove = this._decideIfNeedsToMove();
  5486. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5487. if (needToMove) {
  5488. this._updatePosition();
  5489. }
  5490. if (needToRotate) {
  5491. this.rotation.x += this.cameraRotation.x;
  5492. this.rotation.y += this.cameraRotation.y;
  5493. if (!this.noRotationConstraint) {
  5494. var limit = (Math.PI / 2) * 0.95;
  5495. if (this.rotation.x > limit)
  5496. this.rotation.x = limit;
  5497. if (this.rotation.x < -limit)
  5498. this.rotation.x = -limit;
  5499. }
  5500. }
  5501. if (needToMove) {
  5502. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  5503. this.cameraDirection.x = 0;
  5504. }
  5505. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  5506. this.cameraDirection.y = 0;
  5507. }
  5508. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  5509. this.cameraDirection.z = 0;
  5510. }
  5511. this.cameraDirection.scaleInPlace(this.inertia);
  5512. }
  5513. if (needToRotate) {
  5514. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  5515. this.cameraRotation.x = 0;
  5516. }
  5517. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  5518. this.cameraRotation.y = 0;
  5519. }
  5520. this.cameraRotation.scaleInPlace(this.inertia);
  5521. }
  5522. };
  5523. TargetCamera.prototype._getViewMatrix = function () {
  5524. if (!this.lockedTarget) {
  5525. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  5526. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  5527. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5528. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  5529. this._lookAtTemp.invert();
  5530. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  5531. } else {
  5532. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5533. }
  5534. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  5535. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  5536. } else {
  5537. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  5538. }
  5539. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  5540. return this._viewMatrix;
  5541. };
  5542. return TargetCamera;
  5543. })(BABYLON.Camera);
  5544. BABYLON.TargetCamera = TargetCamera;
  5545. })(BABYLON || (BABYLON = {}));
  5546. var __extends = this.__extends || function (d, b) {
  5547. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5548. function __() { this.constructor = d; }
  5549. __.prototype = b.prototype;
  5550. d.prototype = new __();
  5551. };
  5552. var BABYLON;
  5553. (function (BABYLON) {
  5554. var FollowCamera = (function (_super) {
  5555. __extends(FollowCamera, _super);
  5556. function FollowCamera(name, position, scene) {
  5557. _super.call(this, name, position, scene);
  5558. this.radius = 12;
  5559. this.rotationOffset = 0;
  5560. this.heightOffset = 4;
  5561. this.cameraAcceleration = 0.05;
  5562. this.maxCameraSpeed = 20;
  5563. }
  5564. FollowCamera.prototype.getRadians = function (degrees) {
  5565. return degrees * Math.PI / 180;
  5566. };
  5567. FollowCamera.prototype.follow = function (cameraTarget) {
  5568. if (!cameraTarget)
  5569. return;
  5570. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  5571. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  5572. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  5573. var dx = targetX - this.position.x;
  5574. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  5575. var dz = (targetZ) - this.position.z;
  5576. var vx = dx * this.cameraAcceleration * 2;
  5577. var vy = dy * this.cameraAcceleration;
  5578. var vz = dz * this.cameraAcceleration * 2;
  5579. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  5580. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5581. }
  5582. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  5583. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5584. }
  5585. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  5586. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5587. }
  5588. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  5589. this.setTarget(cameraTarget.position);
  5590. };
  5591. FollowCamera.prototype._update = function () {
  5592. _super.prototype._update.call(this);
  5593. this.follow(this.target);
  5594. };
  5595. return FollowCamera;
  5596. })(BABYLON.TargetCamera);
  5597. BABYLON.FollowCamera = FollowCamera;
  5598. })(BABYLON || (BABYLON = {}));
  5599. var __extends = this.__extends || function (d, b) {
  5600. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5601. function __() { this.constructor = d; }
  5602. __.prototype = b.prototype;
  5603. d.prototype = new __();
  5604. };
  5605. var BABYLON;
  5606. (function (BABYLON) {
  5607. var FreeCamera = (function (_super) {
  5608. __extends(FreeCamera, _super);
  5609. function FreeCamera(name, position, scene) {
  5610. _super.call(this, name, position, scene);
  5611. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  5612. this.keysUp = [38];
  5613. this.keysDown = [40];
  5614. this.keysLeft = [37];
  5615. this.keysRight = [39];
  5616. this.checkCollisions = false;
  5617. this.applyGravity = false;
  5618. this.angularSensibility = 2000.0;
  5619. this._keys = [];
  5620. this._collider = new BABYLON.Collider();
  5621. this._needMoveForGravity = true;
  5622. this._oldPosition = BABYLON.Vector3.Zero();
  5623. this._diffPosition = BABYLON.Vector3.Zero();
  5624. this._newPosition = BABYLON.Vector3.Zero();
  5625. }
  5626. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  5627. var _this = this;
  5628. var previousPosition;
  5629. var engine = this.getEngine();
  5630. if (this._attachedElement) {
  5631. return;
  5632. }
  5633. this._attachedElement = element;
  5634. if (this._onMouseDown === undefined) {
  5635. this._onMouseDown = function (evt) {
  5636. previousPosition = {
  5637. x: evt.clientX,
  5638. y: evt.clientY
  5639. };
  5640. if (!noPreventDefault) {
  5641. evt.preventDefault();
  5642. }
  5643. };
  5644. this._onMouseUp = function (evt) {
  5645. previousPosition = null;
  5646. if (!noPreventDefault) {
  5647. evt.preventDefault();
  5648. }
  5649. };
  5650. this._onMouseOut = function (evt) {
  5651. previousPosition = null;
  5652. _this._keys = [];
  5653. if (!noPreventDefault) {
  5654. evt.preventDefault();
  5655. }
  5656. };
  5657. this._onMouseMove = function (evt) {
  5658. if (!previousPosition && !engine.isPointerLock) {
  5659. return;
  5660. }
  5661. var offsetX;
  5662. var offsetY;
  5663. if (!engine.isPointerLock) {
  5664. offsetX = evt.clientX - previousPosition.x;
  5665. offsetY = evt.clientY - previousPosition.y;
  5666. } else {
  5667. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5668. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5669. }
  5670. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  5671. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  5672. previousPosition = {
  5673. x: evt.clientX,
  5674. y: evt.clientY
  5675. };
  5676. if (!noPreventDefault) {
  5677. evt.preventDefault();
  5678. }
  5679. };
  5680. this._onKeyDown = function (evt) {
  5681. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  5682. var index = _this._keys.indexOf(evt.keyCode);
  5683. if (index === -1) {
  5684. _this._keys.push(evt.keyCode);
  5685. }
  5686. if (!noPreventDefault) {
  5687. evt.preventDefault();
  5688. }
  5689. }
  5690. };
  5691. this._onKeyUp = function (evt) {
  5692. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  5693. var index = _this._keys.indexOf(evt.keyCode);
  5694. if (index >= 0) {
  5695. _this._keys.splice(index, 1);
  5696. }
  5697. if (!noPreventDefault) {
  5698. evt.preventDefault();
  5699. }
  5700. }
  5701. };
  5702. this._onLostFocus = function () {
  5703. _this._keys = [];
  5704. };
  5705. this._reset = function () {
  5706. _this._keys = [];
  5707. previousPosition = null;
  5708. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5709. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  5710. };
  5711. }
  5712. element.addEventListener("mousedown", this._onMouseDown, false);
  5713. element.addEventListener("mouseup", this._onMouseUp, false);
  5714. element.addEventListener("mouseout", this._onMouseOut, false);
  5715. element.addEventListener("mousemove", this._onMouseMove, false);
  5716. BABYLON.Tools.RegisterTopRootEvents([
  5717. { name: "keydown", handler: this._onKeyDown },
  5718. { name: "keyup", handler: this._onKeyUp },
  5719. { name: "blur", handler: this._onLostFocus }
  5720. ]);
  5721. };
  5722. FreeCamera.prototype.detachControl = function (element) {
  5723. if (this._attachedElement != element) {
  5724. return;
  5725. }
  5726. element.removeEventListener("mousedown", this._onMouseDown);
  5727. element.removeEventListener("mouseup", this._onMouseUp);
  5728. element.removeEventListener("mouseout", this._onMouseOut);
  5729. element.removeEventListener("mousemove", this._onMouseMove);
  5730. BABYLON.Tools.UnregisterTopRootEvents([
  5731. { name: "keydown", handler: this._onKeyDown },
  5732. { name: "keyup", handler: this._onKeyUp },
  5733. { name: "blur", handler: this._onLostFocus }
  5734. ]);
  5735. this._attachedElement = null;
  5736. if (this._reset) {
  5737. this._reset();
  5738. }
  5739. };
  5740. FreeCamera.prototype._collideWithWorld = function (velocity) {
  5741. var globalPosition;
  5742. if (this.parent) {
  5743. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  5744. } else {
  5745. globalPosition = this.position;
  5746. }
  5747. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  5748. this._collider.radius = this.ellipsoid;
  5749. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  5750. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  5751. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  5752. this.position.addInPlace(this._diffPosition);
  5753. if (this.onCollide) {
  5754. this.onCollide(this._collider.collidedMesh);
  5755. }
  5756. }
  5757. };
  5758. FreeCamera.prototype._checkInputs = function () {
  5759. if (!this._localDirection) {
  5760. this._localDirection = BABYLON.Vector3.Zero();
  5761. this._transformedDirection = BABYLON.Vector3.Zero();
  5762. }
  5763. for (var index = 0; index < this._keys.length; index++) {
  5764. var keyCode = this._keys[index];
  5765. var speed = this._computeLocalCameraSpeed();
  5766. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5767. this._localDirection.copyFromFloats(-speed, 0, 0);
  5768. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5769. this._localDirection.copyFromFloats(0, 0, speed);
  5770. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5771. this._localDirection.copyFromFloats(speed, 0, 0);
  5772. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5773. this._localDirection.copyFromFloats(0, 0, -speed);
  5774. }
  5775. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  5776. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  5777. this.cameraDirection.addInPlace(this._transformedDirection);
  5778. }
  5779. };
  5780. FreeCamera.prototype._decideIfNeedsToMove = function () {
  5781. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5782. };
  5783. FreeCamera.prototype._updatePosition = function () {
  5784. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  5785. this._collideWithWorld(this.cameraDirection);
  5786. if (this.applyGravity) {
  5787. var oldPosition = this.position;
  5788. this._collideWithWorld(this.getScene().gravity);
  5789. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  5790. }
  5791. } else {
  5792. this.position.addInPlace(this.cameraDirection);
  5793. }
  5794. };
  5795. FreeCamera.prototype._update = function () {
  5796. this._checkInputs();
  5797. _super.prototype._update.call(this);
  5798. };
  5799. return FreeCamera;
  5800. })(BABYLON.TargetCamera);
  5801. BABYLON.FreeCamera = FreeCamera;
  5802. })(BABYLON || (BABYLON = {}));
  5803. var __extends = this.__extends || function (d, b) {
  5804. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5805. function __() { this.constructor = d; }
  5806. __.prototype = b.prototype;
  5807. d.prototype = new __();
  5808. };
  5809. var BABYLON;
  5810. (function (BABYLON) {
  5811. var TouchCamera = (function (_super) {
  5812. __extends(TouchCamera, _super);
  5813. function TouchCamera(name, position, scene) {
  5814. _super.call(this, name, position, scene);
  5815. this._offsetX = null;
  5816. this._offsetY = null;
  5817. this._pointerCount = 0;
  5818. this._pointerPressed = [];
  5819. this.angularSensibility = 200000.0;
  5820. this.moveSensibility = 500.0;
  5821. }
  5822. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5823. var _this = this;
  5824. var previousPosition;
  5825. if (this._attachedCanvas) {
  5826. return;
  5827. }
  5828. this._attachedCanvas = canvas;
  5829. if (this._onPointerDown === undefined) {
  5830. this._onPointerDown = function (evt) {
  5831. if (!noPreventDefault) {
  5832. evt.preventDefault();
  5833. }
  5834. _this._pointerPressed.push(evt.pointerId);
  5835. if (_this._pointerPressed.length !== 1) {
  5836. return;
  5837. }
  5838. previousPosition = {
  5839. x: evt.clientX,
  5840. y: evt.clientY
  5841. };
  5842. };
  5843. this._onPointerUp = function (evt) {
  5844. if (!noPreventDefault) {
  5845. evt.preventDefault();
  5846. }
  5847. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5848. if (index === -1) {
  5849. return;
  5850. }
  5851. _this._pointerPressed.splice(index, 1);
  5852. if (index != 0) {
  5853. return;
  5854. }
  5855. previousPosition = null;
  5856. _this._offsetX = null;
  5857. _this._offsetY = null;
  5858. };
  5859. this._onPointerMove = function (evt) {
  5860. if (!noPreventDefault) {
  5861. evt.preventDefault();
  5862. }
  5863. if (!previousPosition) {
  5864. return;
  5865. }
  5866. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5867. if (index != 0) {
  5868. return;
  5869. }
  5870. _this._offsetX = evt.clientX - previousPosition.x;
  5871. _this._offsetY = -(evt.clientY - previousPosition.y);
  5872. };
  5873. this._onLostFocus = function () {
  5874. _this._offsetX = null;
  5875. _this._offsetY = null;
  5876. };
  5877. }
  5878. canvas.addEventListener("pointerdown", this._onPointerDown);
  5879. canvas.addEventListener("pointerup", this._onPointerUp);
  5880. canvas.addEventListener("pointerout", this._onPointerUp);
  5881. canvas.addEventListener("pointermove", this._onPointerMove);
  5882. BABYLON.Tools.RegisterTopRootEvents([
  5883. { name: "blur", handler: this._onLostFocus }
  5884. ]);
  5885. };
  5886. TouchCamera.prototype.detachControl = function (canvas) {
  5887. if (this._attachedCanvas != canvas) {
  5888. return;
  5889. }
  5890. canvas.removeEventListener("pointerdown", this._onPointerDown);
  5891. canvas.removeEventListener("pointerup", this._onPointerUp);
  5892. canvas.removeEventListener("pointerout", this._onPointerUp);
  5893. canvas.removeEventListener("pointermove", this._onPointerMove);
  5894. BABYLON.Tools.UnregisterTopRootEvents([
  5895. { name: "blur", handler: this._onLostFocus }
  5896. ]);
  5897. this._attachedCanvas = null;
  5898. };
  5899. TouchCamera.prototype._checkInputs = function () {
  5900. if (!this._offsetX) {
  5901. return;
  5902. }
  5903. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  5904. if (this._pointerPressed.length > 1) {
  5905. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  5906. } else {
  5907. var speed = this._computeLocalCameraSpeed();
  5908. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5909. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5910. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5911. }
  5912. };
  5913. return TouchCamera;
  5914. })(BABYLON.FreeCamera);
  5915. BABYLON.TouchCamera = TouchCamera;
  5916. })(BABYLON || (BABYLON = {}));
  5917. var __extends = this.__extends || function (d, b) {
  5918. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5919. function __() { this.constructor = d; }
  5920. __.prototype = b.prototype;
  5921. d.prototype = new __();
  5922. };
  5923. var BABYLON;
  5924. (function (BABYLON) {
  5925. var DeviceOrientationCamera = (function (_super) {
  5926. __extends(DeviceOrientationCamera, _super);
  5927. function DeviceOrientationCamera(name, position, scene) {
  5928. var _this = this;
  5929. _super.call(this, name, position, scene);
  5930. this._offsetX = null;
  5931. this._offsetY = null;
  5932. this._orientationGamma = 0;
  5933. this._orientationBeta = 0;
  5934. this._initialOrientationGamma = 0;
  5935. this._initialOrientationBeta = 0;
  5936. this.angularSensibility = 10000.0;
  5937. this.moveSensibility = 50.0;
  5938. window.addEventListener("resize", function () {
  5939. _this._initialOrientationGamma = null;
  5940. }, false);
  5941. }
  5942. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5943. var _this = this;
  5944. if (this._attachedCanvas) {
  5945. return;
  5946. }
  5947. this._attachedCanvas = canvas;
  5948. if (!this._orientationChanged) {
  5949. this._orientationChanged = function (evt) {
  5950. if (!_this._initialOrientationGamma) {
  5951. _this._initialOrientationGamma = evt.gamma;
  5952. _this._initialOrientationBeta = evt.beta;
  5953. }
  5954. _this._orientationGamma = evt.gamma;
  5955. _this._orientationBeta = evt.beta;
  5956. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  5957. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  5958. };
  5959. }
  5960. window.addEventListener("deviceorientation", this._orientationChanged);
  5961. };
  5962. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  5963. if (this._attachedCanvas != canvas) {
  5964. return;
  5965. }
  5966. window.removeEventListener("deviceorientation", this._orientationChanged);
  5967. this._attachedCanvas = null;
  5968. this._orientationGamma = 0;
  5969. this._orientationBeta = 0;
  5970. this._initialOrientationGamma = 0;
  5971. this._initialOrientationBeta = 0;
  5972. };
  5973. DeviceOrientationCamera.prototype._checkInputs = function () {
  5974. if (!this._offsetX) {
  5975. return;
  5976. }
  5977. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  5978. var speed = this._computeLocalCameraSpeed();
  5979. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5980. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5981. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5982. };
  5983. return DeviceOrientationCamera;
  5984. })(BABYLON.FreeCamera);
  5985. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  5986. })(BABYLON || (BABYLON = {}));
  5987. var __extends = this.__extends || function (d, b) {
  5988. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5989. function __() { this.constructor = d; }
  5990. __.prototype = b.prototype;
  5991. d.prototype = new __();
  5992. };
  5993. var BABYLON;
  5994. (function (BABYLON) {
  5995. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  5996. var ArcRotateCamera = (function (_super) {
  5997. __extends(ArcRotateCamera, _super);
  5998. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  5999. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6000. this.alpha = alpha;
  6001. this.beta = beta;
  6002. this.radius = radius;
  6003. this.target = target;
  6004. this.inertialAlphaOffset = 0;
  6005. this.inertialBetaOffset = 0;
  6006. this.inertialRadiusOffset = 0;
  6007. this.lowerAlphaLimit = null;
  6008. this.upperAlphaLimit = null;
  6009. this.lowerBetaLimit = 0.01;
  6010. this.upperBetaLimit = Math.PI;
  6011. this.lowerRadiusLimit = null;
  6012. this.upperRadiusLimit = null;
  6013. this.angularSensibility = 1000.0;
  6014. this.wheelPrecision = 3.0;
  6015. this.keysUp = [38];
  6016. this.keysDown = [40];
  6017. this.keysLeft = [37];
  6018. this.keysRight = [39];
  6019. this.zoomOnFactor = 1;
  6020. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6021. this._keys = [];
  6022. this._viewMatrix = new BABYLON.Matrix();
  6023. this.checkCollisions = false;
  6024. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6025. this._collider = new BABYLON.Collider();
  6026. this._previousPosition = BABYLON.Vector3.Zero();
  6027. this._collisionVelocity = BABYLON.Vector3.Zero();
  6028. this._newPosition = BABYLON.Vector3.Zero();
  6029. this.pinchPrecision = 20;
  6030. this.getViewMatrix();
  6031. }
  6032. ArcRotateCamera.prototype._getTargetPosition = function () {
  6033. return this.target.position || this.target;
  6034. };
  6035. ArcRotateCamera.prototype._initCache = function () {
  6036. _super.prototype._initCache.call(this);
  6037. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6038. this._cache.alpha = undefined;
  6039. this._cache.beta = undefined;
  6040. this._cache.radius = undefined;
  6041. this._cache.targetScreenOffset = undefined;
  6042. };
  6043. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6044. if (!ignoreParentClass) {
  6045. _super.prototype._updateCache.call(this);
  6046. }
  6047. this._cache.target.copyFrom(this._getTargetPosition());
  6048. this._cache.alpha = this.alpha;
  6049. this._cache.beta = this.beta;
  6050. this._cache.radius = this.radius;
  6051. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  6052. };
  6053. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  6054. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  6055. return false;
  6056. return this._cache.target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  6057. };
  6058. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  6059. var _this = this;
  6060. var previousPosition;
  6061. var pointerId;
  6062. var pinchStarted = false;
  6063. var pinchPointX1, pinchPointX2;
  6064. if (this._attachedElement) {
  6065. return;
  6066. }
  6067. this._attachedElement = element;
  6068. var engine = this.getEngine();
  6069. if (this._onPointerDown === undefined) {
  6070. this._onPointerDown = function (evt) {
  6071. if (pointerId) {
  6072. return;
  6073. }
  6074. pointerId = evt.pointerId;
  6075. previousPosition = {
  6076. x: evt.clientX,
  6077. y: evt.clientY
  6078. };
  6079. if (!noPreventDefault) {
  6080. evt.preventDefault();
  6081. }
  6082. };
  6083. this._onPointerUp = function (evt) {
  6084. previousPosition = null;
  6085. pointerId = null;
  6086. if (!noPreventDefault) {
  6087. evt.preventDefault();
  6088. }
  6089. };
  6090. this._onPointerMove = function (evt) {
  6091. if (!previousPosition) {
  6092. return;
  6093. }
  6094. if (pointerId !== evt.pointerId) {
  6095. return;
  6096. }
  6097. if (pinchStarted) {
  6098. return;
  6099. }
  6100. var offsetX = evt.clientX - previousPosition.x;
  6101. var offsetY = evt.clientY - previousPosition.y;
  6102. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6103. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6104. previousPosition = {
  6105. x: evt.clientX,
  6106. y: evt.clientY
  6107. };
  6108. if (!noPreventDefault) {
  6109. evt.preventDefault();
  6110. }
  6111. };
  6112. this._onMouseMove = function (evt) {
  6113. if (!engine.isPointerLock) {
  6114. return;
  6115. }
  6116. if (pinchStarted) {
  6117. return;
  6118. }
  6119. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6120. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6121. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6122. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6123. if (!noPreventDefault) {
  6124. evt.preventDefault();
  6125. }
  6126. };
  6127. this._wheel = function (event) {
  6128. var delta = 0;
  6129. if (event.wheelDelta) {
  6130. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  6131. } else if (event.detail) {
  6132. delta = -event.detail / _this.wheelPrecision;
  6133. }
  6134. if (delta)
  6135. _this.inertialRadiusOffset += delta;
  6136. if (event.preventDefault) {
  6137. if (!noPreventDefault) {
  6138. event.preventDefault();
  6139. }
  6140. }
  6141. };
  6142. this._onKeyDown = function (evt) {
  6143. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  6144. var index = _this._keys.indexOf(evt.keyCode);
  6145. if (index === -1) {
  6146. _this._keys.push(evt.keyCode);
  6147. }
  6148. if (evt.preventDefault) {
  6149. if (!noPreventDefault) {
  6150. evt.preventDefault();
  6151. }
  6152. }
  6153. }
  6154. };
  6155. this._onKeyUp = function (evt) {
  6156. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  6157. var index = _this._keys.indexOf(evt.keyCode);
  6158. if (index >= 0) {
  6159. _this._keys.splice(index, 1);
  6160. }
  6161. if (evt.preventDefault) {
  6162. if (!noPreventDefault) {
  6163. evt.preventDefault();
  6164. }
  6165. }
  6166. }
  6167. };
  6168. this._onLostFocus = function () {
  6169. _this._keys = [];
  6170. pointerId = null;
  6171. };
  6172. this._onGestureStart = function (e) {
  6173. if (window.MSGesture === undefined) {
  6174. return;
  6175. }
  6176. if (!_this._MSGestureHandler) {
  6177. _this._MSGestureHandler = new MSGesture();
  6178. _this._MSGestureHandler.target = element;
  6179. }
  6180. _this._MSGestureHandler.addPointer(e.pointerId);
  6181. };
  6182. this._onGesture = function (e) {
  6183. _this.radius *= e.scale;
  6184. if (e.preventDefault) {
  6185. if (!noPreventDefault) {
  6186. e.stopPropagation();
  6187. e.preventDefault();
  6188. }
  6189. }
  6190. };
  6191. this._reset = function () {
  6192. _this._keys = [];
  6193. _this.inertialAlphaOffset = 0;
  6194. _this.inertialBetaOffset = 0;
  6195. _this.inertialRadiusOffset = 0;
  6196. previousPosition = null;
  6197. pointerId = null;
  6198. };
  6199. this._touchStart = function (event) {
  6200. if (event.touches.length == 2) {
  6201. pinchStarted = true;
  6202. _this._pinchStart(event);
  6203. }
  6204. };
  6205. this._touchMove = function (event) {
  6206. if (pinchStarted) {
  6207. _this._pinchMove(event);
  6208. }
  6209. };
  6210. this._touchEnd = function (event) {
  6211. if (pinchStarted) {
  6212. _this._pinchEnd(event);
  6213. }
  6214. };
  6215. this._pinchStart = function (event) {
  6216. pinchPointX1 = event.touches[0].clientX;
  6217. pinchPointX2 = event.touches[1].clientX;
  6218. pinchStarted = true;
  6219. };
  6220. this._pinchMove = function (event) {
  6221. var delta = 0;
  6222. var direction = 1;
  6223. var distanceXOrigine, distanceXNow;
  6224. if (event.touches.length != 2)
  6225. return;
  6226. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  6227. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  6228. if (distanceXNow < distanceXOrigine) {
  6229. direction = -1;
  6230. }
  6231. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  6232. _this.inertialRadiusOffset += delta;
  6233. pinchPointX1 = event.touches[0].clientX;
  6234. pinchPointX2 = event.touches[1].clientX;
  6235. };
  6236. this._pinchEnd = function (event) {
  6237. pinchStarted = false;
  6238. };
  6239. }
  6240. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6241. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  6242. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  6243. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6244. element.addEventListener("mousemove", this._onMouseMove, false);
  6245. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  6246. element.addEventListener("MSGestureChange", this._onGesture, false);
  6247. element.addEventListener('mousewheel', this._wheel, false);
  6248. element.addEventListener('DOMMouseScroll', this._wheel, false);
  6249. element.addEventListener('touchstart', this._touchStart, false);
  6250. element.addEventListener('touchmove', this._touchMove, false);
  6251. element.addEventListener('touchend', this._touchEnd, false);
  6252. BABYLON.Tools.RegisterTopRootEvents([
  6253. { name: "keydown", handler: this._onKeyDown },
  6254. { name: "keyup", handler: this._onKeyUp },
  6255. { name: "blur", handler: this._onLostFocus }
  6256. ]);
  6257. };
  6258. ArcRotateCamera.prototype.detachControl = function (element) {
  6259. if (this._attachedElement != element) {
  6260. return;
  6261. }
  6262. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  6263. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  6264. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  6265. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  6266. element.removeEventListener("mousemove", this._onMouseMove);
  6267. element.removeEventListener("MSPointerDown", this._onGestureStart);
  6268. element.removeEventListener("MSGestureChange", this._onGesture);
  6269. element.removeEventListener('mousewheel', this._wheel);
  6270. element.removeEventListener('DOMMouseScroll', this._wheel);
  6271. element.removeEventListener('touchstart', this._touchStart);
  6272. element.removeEventListener('touchmove', this._touchMove);
  6273. element.removeEventListener('touchend', this._touchEnd);
  6274. BABYLON.Tools.UnregisterTopRootEvents([
  6275. { name: "keydown", handler: this._onKeyDown },
  6276. { name: "keyup", handler: this._onKeyUp },
  6277. { name: "blur", handler: this._onLostFocus }
  6278. ]);
  6279. this._MSGestureHandler = null;
  6280. this._attachedElement = null;
  6281. if (this._reset) {
  6282. this._reset();
  6283. }
  6284. };
  6285. ArcRotateCamera.prototype._update = function () {
  6286. for (var index = 0; index < this._keys.length; index++) {
  6287. var keyCode = this._keys[index];
  6288. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6289. this.inertialAlphaOffset -= 0.01;
  6290. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6291. this.inertialBetaOffset -= 0.01;
  6292. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6293. this.inertialAlphaOffset += 0.01;
  6294. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6295. this.inertialBetaOffset += 0.01;
  6296. }
  6297. }
  6298. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  6299. this.alpha += this.inertialAlphaOffset;
  6300. this.beta += this.inertialBetaOffset;
  6301. this.radius -= this.inertialRadiusOffset;
  6302. this.inertialAlphaOffset *= this.inertia;
  6303. this.inertialBetaOffset *= this.inertia;
  6304. this.inertialRadiusOffset *= this.inertia;
  6305. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  6306. this.inertialAlphaOffset = 0;
  6307. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  6308. this.inertialBetaOffset = 0;
  6309. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  6310. this.inertialRadiusOffset = 0;
  6311. }
  6312. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  6313. this.alpha = this.lowerAlphaLimit;
  6314. }
  6315. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  6316. this.alpha = this.upperAlphaLimit;
  6317. }
  6318. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  6319. this.beta = this.lowerBetaLimit;
  6320. }
  6321. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  6322. this.beta = this.upperBetaLimit;
  6323. }
  6324. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  6325. this.radius = this.lowerRadiusLimit;
  6326. }
  6327. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  6328. this.radius = this.upperRadiusLimit;
  6329. }
  6330. };
  6331. ArcRotateCamera.prototype.setPosition = function (position) {
  6332. var radiusv3 = position.subtract(this._getTargetPosition());
  6333. this.radius = radiusv3.length();
  6334. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  6335. if (radiusv3.z < 0) {
  6336. this.alpha = 2 * Math.PI - this.alpha;
  6337. }
  6338. this.beta = Math.acos(radiusv3.y / this.radius);
  6339. };
  6340. ArcRotateCamera.prototype._getViewMatrix = function () {
  6341. var cosa = Math.cos(this.alpha);
  6342. var sina = Math.sin(this.alpha);
  6343. var cosb = Math.cos(this.beta);
  6344. var sinb = Math.sin(this.beta);
  6345. var target = this._getTargetPosition();
  6346. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  6347. if (this.checkCollisions) {
  6348. this._collider.radius = this.collisionRadius;
  6349. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  6350. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  6351. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  6352. this.position.copyFrom(this._previousPosition);
  6353. this.alpha = this._previousAlpha;
  6354. this.beta = this._previousBeta;
  6355. this.radius = this._previousRadius;
  6356. if (this.onCollide) {
  6357. this.onCollide(this._collider.collidedMesh);
  6358. }
  6359. }
  6360. }
  6361. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  6362. this._previousAlpha = this.alpha;
  6363. this._previousBeta = this.beta;
  6364. this._previousRadius = this.radius;
  6365. this._previousPosition.copyFrom(this.position);
  6366. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  6367. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  6368. return this._viewMatrix;
  6369. };
  6370. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  6371. meshes = meshes || this.getScene().meshes;
  6372. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  6373. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  6374. this.radius = distance * this.zoomOnFactor;
  6375. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  6376. };
  6377. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  6378. var meshesOrMinMaxVector;
  6379. var distance;
  6380. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  6381. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  6382. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  6383. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  6384. } else {
  6385. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  6386. distance = meshesOrMinMaxVectorAndDistance.distance;
  6387. }
  6388. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  6389. this.maxZ = distance * 2;
  6390. };
  6391. return ArcRotateCamera;
  6392. })(BABYLON.Camera);
  6393. BABYLON.ArcRotateCamera = ArcRotateCamera;
  6394. })(BABYLON || (BABYLON = {}));
  6395. var BABYLON;
  6396. (function (BABYLON) {
  6397. var Scene = (function () {
  6398. function Scene(engine) {
  6399. this.autoClear = true;
  6400. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6401. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  6402. this.forceWireframe = false;
  6403. this.cameraToUseForPointers = null;
  6404. this.fogMode = BABYLON.Scene.FOGMODE_NONE;
  6405. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6406. this.fogDensity = 0.1;
  6407. this.fogStart = 0;
  6408. this.fogEnd = 1000.0;
  6409. this.shadowsEnabled = true;
  6410. this.lightsEnabled = true;
  6411. this.lights = new Array();
  6412. this.cameras = new Array();
  6413. this.activeCameras = new Array();
  6414. this.meshes = new Array();
  6415. this._geometries = new Array();
  6416. this.materials = new Array();
  6417. this.multiMaterials = new Array();
  6418. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  6419. this.texturesEnabled = true;
  6420. this.textures = new Array();
  6421. this.particlesEnabled = true;
  6422. this.particleSystems = new Array();
  6423. this.spriteManagers = new Array();
  6424. this.layers = new Array();
  6425. this.skeletons = new Array();
  6426. this.lensFlaresEnabled = true;
  6427. this.lensFlareSystems = new Array();
  6428. this.collisionsEnabled = true;
  6429. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  6430. this.postProcessesEnabled = true;
  6431. this.renderTargetsEnabled = true;
  6432. this.customRenderTargets = new Array();
  6433. this.importedMeshesFiles = new Array();
  6434. this._actionManagers = new Array();
  6435. this._meshesForIntersections = new BABYLON.SmartArray(256);
  6436. this.proceduralTexturesEnabled = true;
  6437. this._proceduralTextures = new Array();
  6438. this._totalVertices = 0;
  6439. this._activeVertices = 0;
  6440. this._activeParticles = 0;
  6441. this._lastFrameDuration = 0;
  6442. this._evaluateActiveMeshesDuration = 0;
  6443. this._renderTargetsDuration = 0;
  6444. this._particlesDuration = 0;
  6445. this._renderDuration = 0;
  6446. this._spritesDuration = 0;
  6447. this._animationRatio = 0;
  6448. this._renderId = 0;
  6449. this._executeWhenReadyTimeoutId = -1;
  6450. this._toBeDisposed = new BABYLON.SmartArray(256);
  6451. this._onReadyCallbacks = new Array();
  6452. this._pendingData = [];
  6453. this._onBeforeRenderCallbacks = new Array();
  6454. this._activeMeshes = new BABYLON.SmartArray(256);
  6455. this._processedMaterials = new BABYLON.SmartArray(256);
  6456. this._renderTargets = new BABYLON.SmartArray(256);
  6457. this._activeParticleSystems = new BABYLON.SmartArray(256);
  6458. this._activeSkeletons = new BABYLON.SmartArray(32);
  6459. this._activeAnimatables = new Array();
  6460. this._transformMatrix = BABYLON.Matrix.Zero();
  6461. this._scaledPosition = BABYLON.Vector3.Zero();
  6462. this._scaledVelocity = BABYLON.Vector3.Zero();
  6463. this._engine = engine;
  6464. engine.scenes.push(this);
  6465. this._renderingManager = new BABYLON.RenderingManager(this);
  6466. this.postProcessManager = new BABYLON.PostProcessManager(this);
  6467. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  6468. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  6469. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  6470. this.attachControl();
  6471. }
  6472. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  6473. get: function () {
  6474. return this._meshUnderPointer;
  6475. },
  6476. enumerable: true,
  6477. configurable: true
  6478. });
  6479. Object.defineProperty(Scene.prototype, "pointerX", {
  6480. get: function () {
  6481. return this._pointerX;
  6482. },
  6483. enumerable: true,
  6484. configurable: true
  6485. });
  6486. Object.defineProperty(Scene.prototype, "pointerY", {
  6487. get: function () {
  6488. return this._pointerY;
  6489. },
  6490. enumerable: true,
  6491. configurable: true
  6492. });
  6493. Scene.prototype.getBoundingBoxRenderer = function () {
  6494. return this._boundingBoxRenderer;
  6495. };
  6496. Scene.prototype.getOutlineRenderer = function () {
  6497. return this._outlineRenderer;
  6498. };
  6499. Scene.prototype.getEngine = function () {
  6500. return this._engine;
  6501. };
  6502. Scene.prototype.getTotalVertices = function () {
  6503. return this._totalVertices;
  6504. };
  6505. Scene.prototype.getActiveVertices = function () {
  6506. return this._activeVertices;
  6507. };
  6508. Scene.prototype.getActiveParticles = function () {
  6509. return this._activeParticles;
  6510. };
  6511. Scene.prototype.getLastFrameDuration = function () {
  6512. return this._lastFrameDuration;
  6513. };
  6514. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  6515. return this._evaluateActiveMeshesDuration;
  6516. };
  6517. Scene.prototype.getActiveMeshes = function () {
  6518. return this._activeMeshes;
  6519. };
  6520. Scene.prototype.getRenderTargetsDuration = function () {
  6521. return this._renderTargetsDuration;
  6522. };
  6523. Scene.prototype.getRenderDuration = function () {
  6524. return this._renderDuration;
  6525. };
  6526. Scene.prototype.getParticlesDuration = function () {
  6527. return this._particlesDuration;
  6528. };
  6529. Scene.prototype.getSpritesDuration = function () {
  6530. return this._spritesDuration;
  6531. };
  6532. Scene.prototype.getAnimationRatio = function () {
  6533. return this._animationRatio;
  6534. };
  6535. Scene.prototype.getRenderId = function () {
  6536. return this._renderId;
  6537. };
  6538. Scene.prototype._updatePointerPosition = function (evt) {
  6539. var canvasRect = this._engine.getRenderingCanvasClientRect();
  6540. this._pointerX = evt.clientX - canvasRect.left;
  6541. this._pointerY = evt.clientY - canvasRect.top;
  6542. if (this.cameraToUseForPointers) {
  6543. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  6544. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  6545. }
  6546. };
  6547. Scene.prototype.attachControl = function () {
  6548. var _this = this;
  6549. this._onPointerMove = function (evt) {
  6550. var canvas = _this._engine.getRenderingCanvas();
  6551. _this._updatePointerPosition(evt);
  6552. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  6553. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  6554. }, false, _this.cameraToUseForPointers);
  6555. if (pickResult.hit) {
  6556. _this._meshUnderPointer = pickResult.pickedMesh;
  6557. _this.setPointerOverMesh(pickResult.pickedMesh);
  6558. canvas.style.cursor = "pointer";
  6559. } else {
  6560. _this.setPointerOverMesh(null);
  6561. canvas.style.cursor = "";
  6562. _this._meshUnderPointer = null;
  6563. }
  6564. };
  6565. this._onPointerDown = function (evt) {
  6566. var predicate = null;
  6567. if (!_this.onPointerDown) {
  6568. predicate = function (mesh) {
  6569. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  6570. };
  6571. }
  6572. _this._updatePointerPosition(evt);
  6573. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  6574. if (pickResult.hit) {
  6575. if (pickResult.pickedMesh.actionManager) {
  6576. switch (evt.button) {
  6577. case 0:
  6578. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6579. break;
  6580. case 1:
  6581. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6582. break;
  6583. case 2:
  6584. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6585. break;
  6586. }
  6587. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6588. }
  6589. }
  6590. if (_this.onPointerDown) {
  6591. _this.onPointerDown(evt, pickResult);
  6592. }
  6593. };
  6594. this._onKeyDown = function (evt) {
  6595. if (_this.actionManager) {
  6596. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6597. }
  6598. };
  6599. this._onKeyUp = function (evt) {
  6600. if (_this.actionManager) {
  6601. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6602. }
  6603. };
  6604. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6605. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6606. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6607. window.addEventListener("keydown", this._onKeyDown, false);
  6608. window.addEventListener("keyup", this._onKeyUp, false);
  6609. };
  6610. Scene.prototype.detachControl = function () {
  6611. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6612. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  6613. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  6614. window.removeEventListener("keydown", this._onKeyDown);
  6615. window.removeEventListener("keyup", this._onKeyUp);
  6616. };
  6617. Scene.prototype.isReady = function () {
  6618. if (this._pendingData.length > 0) {
  6619. return false;
  6620. }
  6621. for (var index = 0; index < this._geometries.length; index++) {
  6622. var geometry = this._geometries[index];
  6623. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  6624. return false;
  6625. }
  6626. }
  6627. for (index = 0; index < this.meshes.length; index++) {
  6628. var mesh = this.meshes[index];
  6629. if (!mesh.isReady()) {
  6630. return false;
  6631. }
  6632. var mat = mesh.material;
  6633. if (mat) {
  6634. if (!mat.isReady(mesh)) {
  6635. return false;
  6636. }
  6637. }
  6638. }
  6639. return true;
  6640. };
  6641. Scene.prototype.registerBeforeRender = function (func) {
  6642. this._onBeforeRenderCallbacks.push(func);
  6643. };
  6644. Scene.prototype.unregisterBeforeRender = function (func) {
  6645. var index = this._onBeforeRenderCallbacks.indexOf(func);
  6646. if (index > -1) {
  6647. this._onBeforeRenderCallbacks.splice(index, 1);
  6648. }
  6649. };
  6650. Scene.prototype._addPendingData = function (data) {
  6651. this._pendingData.push(data);
  6652. };
  6653. Scene.prototype._removePendingData = function (data) {
  6654. var index = this._pendingData.indexOf(data);
  6655. if (index !== -1) {
  6656. this._pendingData.splice(index, 1);
  6657. }
  6658. };
  6659. Scene.prototype.getWaitingItemsCount = function () {
  6660. return this._pendingData.length;
  6661. };
  6662. Scene.prototype.executeWhenReady = function (func) {
  6663. var _this = this;
  6664. this._onReadyCallbacks.push(func);
  6665. if (this._executeWhenReadyTimeoutId !== -1) {
  6666. return;
  6667. }
  6668. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6669. _this._checkIsReady();
  6670. }, 150);
  6671. };
  6672. Scene.prototype._checkIsReady = function () {
  6673. var _this = this;
  6674. if (this.isReady()) {
  6675. this._onReadyCallbacks.forEach(function (func) {
  6676. func();
  6677. });
  6678. this._onReadyCallbacks = [];
  6679. this._executeWhenReadyTimeoutId = -1;
  6680. return;
  6681. }
  6682. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6683. _this._checkIsReady();
  6684. }, 150);
  6685. };
  6686. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  6687. if (speedRatio === undefined) {
  6688. speedRatio = 1.0;
  6689. }
  6690. this.stopAnimation(target);
  6691. if (!animatable) {
  6692. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  6693. }
  6694. if (target.animations) {
  6695. animatable.appendAnimations(target, target.animations);
  6696. }
  6697. if (target.getAnimatables) {
  6698. var animatables = target.getAnimatables();
  6699. for (var index = 0; index < animatables.length; index++) {
  6700. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  6701. }
  6702. }
  6703. return animatable;
  6704. };
  6705. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  6706. if (speedRatio === undefined) {
  6707. speedRatio = 1.0;
  6708. }
  6709. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  6710. return animatable;
  6711. };
  6712. Scene.prototype.getAnimatableByTarget = function (target) {
  6713. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6714. if (this._activeAnimatables[index].target === target) {
  6715. return this._activeAnimatables[index];
  6716. }
  6717. }
  6718. return null;
  6719. };
  6720. Scene.prototype.stopAnimation = function (target) {
  6721. var animatable = this.getAnimatableByTarget(target);
  6722. if (animatable) {
  6723. animatable.stop();
  6724. }
  6725. };
  6726. Scene.prototype._animate = function () {
  6727. if (!this._animationStartDate) {
  6728. this._animationStartDate = BABYLON.Tools.Now;
  6729. }
  6730. var now = BABYLON.Tools.Now;
  6731. var delay = now - this._animationStartDate;
  6732. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6733. if (!this._activeAnimatables[index]._animate(delay)) {
  6734. this._activeAnimatables.splice(index, 1);
  6735. index--;
  6736. }
  6737. }
  6738. };
  6739. Scene.prototype.getViewMatrix = function () {
  6740. return this._viewMatrix;
  6741. };
  6742. Scene.prototype.getProjectionMatrix = function () {
  6743. return this._projectionMatrix;
  6744. };
  6745. Scene.prototype.getTransformMatrix = function () {
  6746. return this._transformMatrix;
  6747. };
  6748. Scene.prototype.setTransformMatrix = function (view, projection) {
  6749. this._viewMatrix = view;
  6750. this._projectionMatrix = projection;
  6751. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6752. };
  6753. Scene.prototype.setActiveCameraByID = function (id) {
  6754. var camera = this.getCameraByID(id);
  6755. if (camera) {
  6756. this.activeCamera = camera;
  6757. return camera;
  6758. }
  6759. return null;
  6760. };
  6761. Scene.prototype.setActiveCameraByName = function (name) {
  6762. var camera = this.getCameraByName(name);
  6763. if (camera) {
  6764. this.activeCamera = camera;
  6765. return camera;
  6766. }
  6767. return null;
  6768. };
  6769. Scene.prototype.getMaterialByID = function (id) {
  6770. for (var index = 0; index < this.materials.length; index++) {
  6771. if (this.materials[index].id === id) {
  6772. return this.materials[index];
  6773. }
  6774. }
  6775. return null;
  6776. };
  6777. Scene.prototype.getMaterialByName = function (name) {
  6778. for (var index = 0; index < this.materials.length; index++) {
  6779. if (this.materials[index].name === name) {
  6780. return this.materials[index];
  6781. }
  6782. }
  6783. return null;
  6784. };
  6785. Scene.prototype.getCameraByID = function (id) {
  6786. for (var index = 0; index < this.cameras.length; index++) {
  6787. if (this.cameras[index].id === id) {
  6788. return this.cameras[index];
  6789. }
  6790. }
  6791. return null;
  6792. };
  6793. Scene.prototype.getCameraByName = function (name) {
  6794. for (var index = 0; index < this.cameras.length; index++) {
  6795. if (this.cameras[index].name === name) {
  6796. return this.cameras[index];
  6797. }
  6798. }
  6799. return null;
  6800. };
  6801. Scene.prototype.getLightByName = function (name) {
  6802. for (var index = 0; index < this.lights.length; index++) {
  6803. if (this.lights[index].name === name) {
  6804. return this.lights[index];
  6805. }
  6806. }
  6807. return null;
  6808. };
  6809. Scene.prototype.getLightByID = function (id) {
  6810. for (var index = 0; index < this.lights.length; index++) {
  6811. if (this.lights[index].id === id) {
  6812. return this.lights[index];
  6813. }
  6814. }
  6815. return null;
  6816. };
  6817. Scene.prototype.getGeometryByID = function (id) {
  6818. for (var index = 0; index < this._geometries.length; index++) {
  6819. if (this._geometries[index].id === id) {
  6820. return this._geometries[index];
  6821. }
  6822. }
  6823. return null;
  6824. };
  6825. Scene.prototype.pushGeometry = function (geometry, force) {
  6826. if (!force && this.getGeometryByID(geometry.id)) {
  6827. return false;
  6828. }
  6829. this._geometries.push(geometry);
  6830. return true;
  6831. };
  6832. Scene.prototype.getGeometries = function () {
  6833. return this._geometries;
  6834. };
  6835. Scene.prototype.getMeshByID = function (id) {
  6836. for (var index = 0; index < this.meshes.length; index++) {
  6837. if (this.meshes[index].id === id) {
  6838. return this.meshes[index];
  6839. }
  6840. }
  6841. return null;
  6842. };
  6843. Scene.prototype.getLastMeshByID = function (id) {
  6844. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6845. if (this.meshes[index].id === id) {
  6846. return this.meshes[index];
  6847. }
  6848. }
  6849. return null;
  6850. };
  6851. Scene.prototype.getLastEntryByID = function (id) {
  6852. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6853. if (this.meshes[index].id === id) {
  6854. return this.meshes[index];
  6855. }
  6856. }
  6857. for (index = this.cameras.length - 1; index >= 0; index--) {
  6858. if (this.cameras[index].id === id) {
  6859. return this.cameras[index];
  6860. }
  6861. }
  6862. for (index = this.lights.length - 1; index >= 0; index--) {
  6863. if (this.lights[index].id === id) {
  6864. return this.lights[index];
  6865. }
  6866. }
  6867. return null;
  6868. };
  6869. Scene.prototype.getMeshByName = function (name) {
  6870. for (var index = 0; index < this.meshes.length; index++) {
  6871. if (this.meshes[index].name === name) {
  6872. return this.meshes[index];
  6873. }
  6874. }
  6875. return null;
  6876. };
  6877. Scene.prototype.getLastSkeletonByID = function (id) {
  6878. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  6879. if (this.skeletons[index].id === id) {
  6880. return this.skeletons[index];
  6881. }
  6882. }
  6883. return null;
  6884. };
  6885. Scene.prototype.getSkeletonById = function (id) {
  6886. for (var index = 0; index < this.skeletons.length; index++) {
  6887. if (this.skeletons[index].id === id) {
  6888. return this.skeletons[index];
  6889. }
  6890. }
  6891. return null;
  6892. };
  6893. Scene.prototype.getSkeletonByName = function (name) {
  6894. for (var index = 0; index < this.skeletons.length; index++) {
  6895. if (this.skeletons[index].name === name) {
  6896. return this.skeletons[index];
  6897. }
  6898. }
  6899. return null;
  6900. };
  6901. Scene.prototype.isActiveMesh = function (mesh) {
  6902. return (this._activeMeshes.indexOf(mesh) !== -1);
  6903. };
  6904. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  6905. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  6906. var material = subMesh.getMaterial();
  6907. if (mesh.showSubMeshesBoundingBox) {
  6908. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  6909. }
  6910. if (material) {
  6911. if (material.getRenderTargetTextures) {
  6912. if (this._processedMaterials.indexOf(material) === -1) {
  6913. this._processedMaterials.push(material);
  6914. this._renderTargets.concat(material.getRenderTargetTextures());
  6915. }
  6916. }
  6917. this._activeVertices += subMesh.verticesCount;
  6918. this._renderingManager.dispatch(subMesh);
  6919. }
  6920. }
  6921. };
  6922. Scene.prototype._evaluateActiveMeshes = function () {
  6923. this._activeMeshes.reset();
  6924. this._renderingManager.reset();
  6925. this._processedMaterials.reset();
  6926. this._activeParticleSystems.reset();
  6927. this._activeSkeletons.reset();
  6928. this._boundingBoxRenderer.reset();
  6929. if (!this._frustumPlanes) {
  6930. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  6931. } else {
  6932. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  6933. }
  6934. var meshes;
  6935. var len;
  6936. if (this._selectionOctree) {
  6937. var selection = this._selectionOctree.select(this._frustumPlanes);
  6938. meshes = selection.data;
  6939. len = selection.length;
  6940. } else {
  6941. len = this.meshes.length;
  6942. meshes = this.meshes;
  6943. }
  6944. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  6945. var mesh = meshes[meshIndex];
  6946. if (mesh.isBlocked) {
  6947. continue;
  6948. }
  6949. this._totalVertices += mesh.getTotalVertices();
  6950. if (!mesh.isReady()) {
  6951. continue;
  6952. }
  6953. mesh.computeWorldMatrix();
  6954. mesh._preActivate();
  6955. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  6956. this._meshesForIntersections.pushNoDuplicate(mesh);
  6957. }
  6958. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) != 0) && mesh.isInFrustum(this._frustumPlanes)) {
  6959. this._activeMeshes.push(mesh);
  6960. mesh._activate(this._renderId);
  6961. this._activeMesh(mesh);
  6962. }
  6963. }
  6964. var beforeParticlesDate = BABYLON.Tools.Now;
  6965. if (this.particlesEnabled) {
  6966. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  6967. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  6968. var particleSystem = this.particleSystems[particleIndex];
  6969. if (!particleSystem.isStarted()) {
  6970. continue;
  6971. }
  6972. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  6973. this._activeParticleSystems.push(particleSystem);
  6974. particleSystem.animate();
  6975. }
  6976. }
  6977. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  6978. }
  6979. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  6980. };
  6981. Scene.prototype._activeMesh = function (mesh) {
  6982. if (mesh.skeleton) {
  6983. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  6984. }
  6985. if (mesh.showBoundingBox) {
  6986. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  6987. }
  6988. var activeMesh = mesh.getLOD(this.activeCamera);
  6989. if (activeMesh && activeMesh.subMeshes) {
  6990. var len;
  6991. var subMeshes;
  6992. if (activeMesh._submeshesOctree && activeMesh.useOctreeForRenderingSelection) {
  6993. var intersections = activeMesh._submeshesOctree.select(this._frustumPlanes);
  6994. len = intersections.length;
  6995. subMeshes = intersections.data;
  6996. } else {
  6997. subMeshes = activeMesh.subMeshes;
  6998. len = subMeshes.length;
  6999. }
  7000. for (var subIndex = 0; subIndex < len; subIndex++) {
  7001. var subMesh = subMeshes[subIndex];
  7002. this._evaluateSubMesh(subMesh, activeMesh);
  7003. }
  7004. }
  7005. };
  7006. Scene.prototype.updateTransformMatrix = function (force) {
  7007. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  7008. };
  7009. Scene.prototype._renderForCamera = function (camera) {
  7010. var engine = this._engine;
  7011. this.activeCamera = camera;
  7012. if (!this.activeCamera)
  7013. throw new Error("Active camera not set");
  7014. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7015. engine.setViewport(this.activeCamera.viewport);
  7016. this._renderId++;
  7017. this.updateTransformMatrix();
  7018. if (this.beforeCameraRender) {
  7019. this.beforeCameraRender(this.activeCamera);
  7020. }
  7021. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  7022. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  7023. this._evaluateActiveMeshes();
  7024. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  7025. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  7026. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  7027. var skeleton = this._activeSkeletons.data[skeletonIndex];
  7028. skeleton.prepare();
  7029. }
  7030. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7031. if (this.renderTargetsEnabled) {
  7032. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7033. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  7034. var renderTarget = this._renderTargets.data[renderIndex];
  7035. if (renderTarget._shouldRender()) {
  7036. this._renderId++;
  7037. renderTarget.render();
  7038. }
  7039. }
  7040. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7041. this._renderId++;
  7042. }
  7043. if (this._renderTargets.length > 0) {
  7044. engine.restoreDefaultFramebuffer();
  7045. }
  7046. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7047. this.postProcessManager._prepareFrame();
  7048. var beforeRenderDate = BABYLON.Tools.Now;
  7049. if (this.layers.length) {
  7050. engine.setDepthBuffer(false);
  7051. var layerIndex;
  7052. var layer;
  7053. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7054. layer = this.layers[layerIndex];
  7055. if (layer.isBackground) {
  7056. layer.render();
  7057. }
  7058. }
  7059. engine.setDepthBuffer(true);
  7060. }
  7061. BABYLON.Tools.StartPerformanceCounter("Main render");
  7062. this._renderingManager.render(null, null, true, true);
  7063. BABYLON.Tools.EndPerformanceCounter("Main render");
  7064. this._boundingBoxRenderer.render();
  7065. if (this.lensFlaresEnabled) {
  7066. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7067. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  7068. this.lensFlareSystems[lensFlareSystemIndex].render();
  7069. }
  7070. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7071. }
  7072. if (this.layers.length) {
  7073. engine.setDepthBuffer(false);
  7074. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7075. layer = this.layers[layerIndex];
  7076. if (!layer.isBackground) {
  7077. layer.render();
  7078. }
  7079. }
  7080. engine.setDepthBuffer(true);
  7081. }
  7082. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  7083. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  7084. this.activeCamera._updateFromScene();
  7085. this._renderTargets.reset();
  7086. if (this.afterCameraRender) {
  7087. this.afterCameraRender(this.activeCamera);
  7088. }
  7089. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7090. };
  7091. Scene.prototype._processSubCameras = function (camera) {
  7092. if (camera.subCameras.length == 0) {
  7093. this._renderForCamera(camera);
  7094. return;
  7095. }
  7096. for (var index = 0; index < camera.subCameras.length; index++) {
  7097. this._renderForCamera(camera.subCameras[index]);
  7098. }
  7099. this.activeCamera = camera;
  7100. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  7101. this.activeCamera._updateFromScene();
  7102. };
  7103. Scene.prototype._checkIntersections = function () {
  7104. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  7105. var sourceMesh = this._meshesForIntersections.data[index];
  7106. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  7107. var action = sourceMesh.actionManager.actions[actionIndex];
  7108. if (action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7109. var otherMesh = action.getTriggerParameter();
  7110. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  7111. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7112. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  7113. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  7114. sourceMesh._intersectionsInProgress.push(otherMesh);
  7115. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7116. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  7117. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7118. if (indexOfOther > -1) {
  7119. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  7120. }
  7121. }
  7122. }
  7123. }
  7124. }
  7125. };
  7126. Scene.prototype.render = function () {
  7127. var startDate = BABYLON.Tools.Now;
  7128. this._particlesDuration = 0;
  7129. this._spritesDuration = 0;
  7130. this._activeParticles = 0;
  7131. this._renderDuration = 0;
  7132. this._evaluateActiveMeshesDuration = 0;
  7133. this._totalVertices = 0;
  7134. this._activeVertices = 0;
  7135. this._meshesForIntersections.reset();
  7136. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  7137. if (this.actionManager) {
  7138. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  7139. }
  7140. if (this.beforeRender) {
  7141. this.beforeRender();
  7142. }
  7143. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  7144. this._onBeforeRenderCallbacks[callbackIndex]();
  7145. }
  7146. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  7147. this._animationRatio = deltaTime * (60.0 / 1000.0);
  7148. this._animate();
  7149. if (this._physicsEngine) {
  7150. BABYLON.Tools.StartPerformanceCounter("Physics");
  7151. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  7152. BABYLON.Tools.EndPerformanceCounter("Physics");
  7153. }
  7154. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7155. var engine = this.getEngine();
  7156. if (this.renderTargetsEnabled) {
  7157. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7158. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  7159. var renderTarget = this.customRenderTargets[customIndex];
  7160. if (renderTarget._shouldRender()) {
  7161. this._renderId++;
  7162. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  7163. if (!this.activeCamera)
  7164. throw new Error("Active camera not set");
  7165. engine.setViewport(this.activeCamera.viewport);
  7166. this.updateTransformMatrix();
  7167. renderTarget.render();
  7168. }
  7169. }
  7170. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7171. this._renderId++;
  7172. }
  7173. if (this.customRenderTargets.length > 0) {
  7174. engine.restoreDefaultFramebuffer();
  7175. }
  7176. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7177. if (this.proceduralTexturesEnabled) {
  7178. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7179. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  7180. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  7181. if (proceduralTexture._shouldRender()) {
  7182. proceduralTexture.render();
  7183. }
  7184. }
  7185. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7186. }
  7187. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  7188. if (this.shadowsEnabled) {
  7189. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  7190. var light = this.lights[lightIndex];
  7191. var shadowGenerator = light.getShadowGenerator();
  7192. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  7193. this._renderTargets.push(shadowGenerator.getShadowMap());
  7194. }
  7195. }
  7196. }
  7197. this.postProcessRenderPipelineManager.update();
  7198. if (this.activeCameras.length > 0) {
  7199. var currentRenderId = this._renderId;
  7200. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  7201. this._renderId = currentRenderId;
  7202. this._processSubCameras(this.activeCameras[cameraIndex]);
  7203. }
  7204. } else {
  7205. if (!this.activeCamera) {
  7206. throw new Error("No camera defined");
  7207. }
  7208. this._processSubCameras(this.activeCamera);
  7209. }
  7210. this._checkIntersections();
  7211. if (this.afterRender) {
  7212. this.afterRender();
  7213. }
  7214. for (var index = 0; index < this._toBeDisposed.length; index++) {
  7215. this._toBeDisposed.data[index].dispose();
  7216. this._toBeDisposed[index] = null;
  7217. }
  7218. this._toBeDisposed.reset();
  7219. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  7220. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  7221. };
  7222. Scene.prototype.dispose = function () {
  7223. this.beforeRender = null;
  7224. this.afterRender = null;
  7225. this.skeletons = [];
  7226. this._boundingBoxRenderer.dispose();
  7227. if (this.onDispose) {
  7228. this.onDispose();
  7229. }
  7230. this.detachControl();
  7231. var canvas = this._engine.getRenderingCanvas();
  7232. var index;
  7233. for (index = 0; index < this.cameras.length; index++) {
  7234. this.cameras[index].detachControl(canvas);
  7235. }
  7236. while (this.lights.length) {
  7237. this.lights[0].dispose();
  7238. }
  7239. while (this.meshes.length) {
  7240. this.meshes[0].dispose(true);
  7241. }
  7242. while (this.cameras.length) {
  7243. this.cameras[0].dispose();
  7244. }
  7245. while (this.materials.length) {
  7246. this.materials[0].dispose();
  7247. }
  7248. while (this.particleSystems.length) {
  7249. this.particleSystems[0].dispose();
  7250. }
  7251. while (this.spriteManagers.length) {
  7252. this.spriteManagers[0].dispose();
  7253. }
  7254. while (this.layers.length) {
  7255. this.layers[0].dispose();
  7256. }
  7257. while (this.textures.length) {
  7258. this.textures[0].dispose();
  7259. }
  7260. this.postProcessManager.dispose();
  7261. if (this._physicsEngine) {
  7262. this.disablePhysicsEngine();
  7263. }
  7264. index = this._engine.scenes.indexOf(this);
  7265. if (index > -1) {
  7266. this._engine.scenes.splice(index, 1);
  7267. }
  7268. this._engine.wipeCaches();
  7269. };
  7270. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7271. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7272. position.divideToRef(collider.radius, this._scaledPosition);
  7273. velocity.divideToRef(collider.radius, this._scaledVelocity);
  7274. collider.retry = 0;
  7275. collider.initialVelocity = this._scaledVelocity;
  7276. collider.initialPosition = this._scaledPosition;
  7277. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  7278. finalPosition.multiplyInPlace(collider.radius);
  7279. };
  7280. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7281. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7282. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  7283. if (collider.retry >= maximumRetry) {
  7284. finalPosition.copyFrom(position);
  7285. return;
  7286. }
  7287. collider._initialize(position, velocity, closeDistance);
  7288. for (var index = 0; index < this.meshes.length; index++) {
  7289. var mesh = this.meshes[index];
  7290. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  7291. mesh._checkCollision(collider);
  7292. }
  7293. }
  7294. if (!collider.collisionFound) {
  7295. position.addToRef(velocity, finalPosition);
  7296. return;
  7297. }
  7298. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  7299. collider._getResponse(position, velocity);
  7300. }
  7301. if (velocity.length() <= closeDistance) {
  7302. finalPosition.copyFrom(position);
  7303. return;
  7304. }
  7305. collider.retry++;
  7306. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  7307. };
  7308. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  7309. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7310. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7311. if (!this._selectionOctree) {
  7312. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  7313. }
  7314. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7315. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7316. for (var index = 0; index < this.meshes.length; index++) {
  7317. var mesh = this.meshes[index];
  7318. mesh.computeWorldMatrix(true);
  7319. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  7320. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  7321. BABYLON.Tools.CheckExtends(minBox, min, max);
  7322. BABYLON.Tools.CheckExtends(maxBox, min, max);
  7323. }
  7324. this._selectionOctree.update(min, max, this.meshes);
  7325. return this._selectionOctree;
  7326. };
  7327. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  7328. var engine = this._engine;
  7329. if (!camera) {
  7330. if (!this.activeCamera)
  7331. throw new Error("Active camera not set");
  7332. camera = this.activeCamera;
  7333. }
  7334. var cameraViewport = camera.viewport;
  7335. var viewport = cameraViewport.toGlobal(engine);
  7336. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  7337. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  7338. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  7339. };
  7340. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  7341. var pickingInfo = null;
  7342. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  7343. var mesh = this.meshes[meshIndex];
  7344. if (predicate) {
  7345. if (!predicate(mesh)) {
  7346. continue;
  7347. }
  7348. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  7349. continue;
  7350. }
  7351. var world = mesh.getWorldMatrix();
  7352. var ray = rayFunction(world);
  7353. var result = mesh.intersects(ray, fastCheck);
  7354. if (!result || !result.hit)
  7355. continue;
  7356. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  7357. continue;
  7358. pickingInfo = result;
  7359. if (fastCheck) {
  7360. break;
  7361. }
  7362. }
  7363. return pickingInfo || new BABYLON.PickingInfo();
  7364. };
  7365. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  7366. var _this = this;
  7367. return this._internalPick(function (world) {
  7368. return _this.createPickingRay(x, y, world, camera);
  7369. }, predicate, fastCheck);
  7370. };
  7371. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  7372. var _this = this;
  7373. return this._internalPick(function (world) {
  7374. if (!_this._pickWithRayInverseMatrix) {
  7375. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  7376. }
  7377. world.invertToRef(_this._pickWithRayInverseMatrix);
  7378. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  7379. }, predicate, fastCheck);
  7380. };
  7381. Scene.prototype.setPointerOverMesh = function (mesh) {
  7382. if (this._pointerOverMesh === mesh) {
  7383. return;
  7384. }
  7385. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  7386. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  7387. }
  7388. this._pointerOverMesh = mesh;
  7389. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  7390. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  7391. }
  7392. };
  7393. Scene.prototype.getPointerOverMesh = function () {
  7394. return this._pointerOverMesh;
  7395. };
  7396. Scene.prototype.getPhysicsEngine = function () {
  7397. return this._physicsEngine;
  7398. };
  7399. Scene.prototype.enablePhysics = function (gravity, plugin) {
  7400. if (this._physicsEngine) {
  7401. return true;
  7402. }
  7403. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  7404. if (!this._physicsEngine.isSupported()) {
  7405. this._physicsEngine = null;
  7406. return false;
  7407. }
  7408. this._physicsEngine._initialize(gravity);
  7409. return true;
  7410. };
  7411. Scene.prototype.disablePhysicsEngine = function () {
  7412. if (!this._physicsEngine) {
  7413. return;
  7414. }
  7415. this._physicsEngine.dispose();
  7416. this._physicsEngine = undefined;
  7417. };
  7418. Scene.prototype.isPhysicsEnabled = function () {
  7419. return this._physicsEngine !== undefined;
  7420. };
  7421. Scene.prototype.setGravity = function (gravity) {
  7422. if (!this._physicsEngine) {
  7423. return;
  7424. }
  7425. this._physicsEngine._setGravity(gravity);
  7426. };
  7427. Scene.prototype.createCompoundImpostor = function (parts, options) {
  7428. if (parts.parts) {
  7429. options = parts;
  7430. parts = parts.parts;
  7431. }
  7432. if (!this._physicsEngine) {
  7433. return null;
  7434. }
  7435. for (var index = 0; index < parts.length; index++) {
  7436. var mesh = parts[index].mesh;
  7437. mesh._physicImpostor = parts[index].impostor;
  7438. mesh._physicsMass = options.mass / parts.length;
  7439. mesh._physicsFriction = options.friction;
  7440. mesh._physicRestitution = options.restitution;
  7441. }
  7442. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  7443. };
  7444. Scene.prototype.deleteCompoundImpostor = function (compound) {
  7445. for (var index = 0; index < compound.parts.length; index++) {
  7446. var mesh = compound.parts[index].mesh;
  7447. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7448. this._physicsEngine._unregisterMesh(mesh);
  7449. }
  7450. };
  7451. Scene.prototype._getByTags = function (list, tagsQuery) {
  7452. if (tagsQuery === undefined) {
  7453. return list;
  7454. }
  7455. var listByTags = [];
  7456. for (var i in list) {
  7457. var item = list[i];
  7458. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  7459. listByTags.push(item);
  7460. }
  7461. }
  7462. return listByTags;
  7463. };
  7464. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  7465. return this._getByTags(this.meshes, tagsQuery);
  7466. };
  7467. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  7468. return this._getByTags(this.cameras, tagsQuery);
  7469. };
  7470. Scene.prototype.getLightsByTags = function (tagsQuery) {
  7471. return this._getByTags(this.lights, tagsQuery);
  7472. };
  7473. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  7474. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  7475. };
  7476. Scene.FOGMODE_NONE = 0;
  7477. Scene.FOGMODE_EXP = 1;
  7478. Scene.FOGMODE_EXP2 = 2;
  7479. Scene.FOGMODE_LINEAR = 3;
  7480. Scene.MinDeltaTime = 1.0;
  7481. Scene.MaxDeltaTime = 1000.0;
  7482. return Scene;
  7483. })();
  7484. BABYLON.Scene = Scene;
  7485. })(BABYLON || (BABYLON = {}));
  7486. var BABYLON;
  7487. (function (BABYLON) {
  7488. var VertexBuffer = (function () {
  7489. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation) {
  7490. if (engine instanceof BABYLON.Mesh) {
  7491. this._engine = engine.getScene().getEngine();
  7492. } else {
  7493. this._engine = engine;
  7494. }
  7495. this._updatable = updatable;
  7496. this._data = data;
  7497. if (!postponeInternalCreation) {
  7498. this.create();
  7499. }
  7500. this._kind = kind;
  7501. switch (kind) {
  7502. case VertexBuffer.PositionKind:
  7503. this._strideSize = 3;
  7504. break;
  7505. case VertexBuffer.NormalKind:
  7506. this._strideSize = 3;
  7507. break;
  7508. case VertexBuffer.UVKind:
  7509. this._strideSize = 2;
  7510. break;
  7511. case VertexBuffer.UV2Kind:
  7512. this._strideSize = 2;
  7513. break;
  7514. case VertexBuffer.ColorKind:
  7515. this._strideSize = 3;
  7516. break;
  7517. case VertexBuffer.MatricesIndicesKind:
  7518. this._strideSize = 4;
  7519. break;
  7520. case VertexBuffer.MatricesWeightsKind:
  7521. this._strideSize = 4;
  7522. break;
  7523. }
  7524. }
  7525. VertexBuffer.prototype.isUpdatable = function () {
  7526. return this._updatable;
  7527. };
  7528. VertexBuffer.prototype.getData = function () {
  7529. return this._data;
  7530. };
  7531. VertexBuffer.prototype.getBuffer = function () {
  7532. return this._buffer;
  7533. };
  7534. VertexBuffer.prototype.getStrideSize = function () {
  7535. return this._strideSize;
  7536. };
  7537. VertexBuffer.prototype.create = function (data) {
  7538. if (!data && this._buffer) {
  7539. return;
  7540. }
  7541. data = data || this._data;
  7542. if (!this._buffer) {
  7543. if (this._updatable) {
  7544. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  7545. } else {
  7546. this._buffer = this._engine.createVertexBuffer(data);
  7547. }
  7548. }
  7549. if (this._updatable) {
  7550. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7551. this._data = data;
  7552. }
  7553. };
  7554. VertexBuffer.prototype.update = function (data) {
  7555. this.create(data);
  7556. };
  7557. VertexBuffer.prototype.updateDirectly = function (data) {
  7558. if (!this._buffer) {
  7559. return;
  7560. }
  7561. if (this._updatable) {
  7562. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7563. this._data = null;
  7564. }
  7565. };
  7566. VertexBuffer.prototype.dispose = function () {
  7567. if (!this._buffer) {
  7568. return;
  7569. }
  7570. if (this._engine._releaseBuffer(this._buffer)) {
  7571. this._buffer = null;
  7572. }
  7573. };
  7574. Object.defineProperty(VertexBuffer, "PositionKind", {
  7575. get: function () {
  7576. return VertexBuffer._PositionKind;
  7577. },
  7578. enumerable: true,
  7579. configurable: true
  7580. });
  7581. Object.defineProperty(VertexBuffer, "NormalKind", {
  7582. get: function () {
  7583. return VertexBuffer._NormalKind;
  7584. },
  7585. enumerable: true,
  7586. configurable: true
  7587. });
  7588. Object.defineProperty(VertexBuffer, "UVKind", {
  7589. get: function () {
  7590. return VertexBuffer._UVKind;
  7591. },
  7592. enumerable: true,
  7593. configurable: true
  7594. });
  7595. Object.defineProperty(VertexBuffer, "UV2Kind", {
  7596. get: function () {
  7597. return VertexBuffer._UV2Kind;
  7598. },
  7599. enumerable: true,
  7600. configurable: true
  7601. });
  7602. Object.defineProperty(VertexBuffer, "ColorKind", {
  7603. get: function () {
  7604. return VertexBuffer._ColorKind;
  7605. },
  7606. enumerable: true,
  7607. configurable: true
  7608. });
  7609. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  7610. get: function () {
  7611. return VertexBuffer._MatricesIndicesKind;
  7612. },
  7613. enumerable: true,
  7614. configurable: true
  7615. });
  7616. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  7617. get: function () {
  7618. return VertexBuffer._MatricesWeightsKind;
  7619. },
  7620. enumerable: true,
  7621. configurable: true
  7622. });
  7623. VertexBuffer._PositionKind = "position";
  7624. VertexBuffer._NormalKind = "normal";
  7625. VertexBuffer._UVKind = "uv";
  7626. VertexBuffer._UV2Kind = "uv2";
  7627. VertexBuffer._ColorKind = "color";
  7628. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  7629. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  7630. return VertexBuffer;
  7631. })();
  7632. BABYLON.VertexBuffer = VertexBuffer;
  7633. })(BABYLON || (BABYLON = {}));
  7634. var __extends = this.__extends || function (d, b) {
  7635. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7636. function __() { this.constructor = d; }
  7637. __.prototype = b.prototype;
  7638. d.prototype = new __();
  7639. };
  7640. var BABYLON;
  7641. (function (BABYLON) {
  7642. var AbstractMesh = (function (_super) {
  7643. __extends(AbstractMesh, _super);
  7644. function AbstractMesh(name, scene) {
  7645. _super.call(this, name, scene);
  7646. this.position = new BABYLON.Vector3(0, 0, 0);
  7647. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7648. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7649. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  7650. this.visibility = 1.0;
  7651. this.infiniteDistance = false;
  7652. this.isVisible = true;
  7653. this.isPickable = true;
  7654. this.showBoundingBox = false;
  7655. this.showSubMeshesBoundingBox = false;
  7656. this.onDispose = null;
  7657. this.checkCollisions = false;
  7658. this.isBlocker = false;
  7659. this.renderingGroupId = 0;
  7660. this.receiveShadows = false;
  7661. this.renderOutline = false;
  7662. this.outlineColor = BABYLON.Color3.Red();
  7663. this.outlineWidth = 0.02;
  7664. this.useOctreeForRenderingSelection = true;
  7665. this.useOctreeForPicking = true;
  7666. this.useOctreeForCollisions = true;
  7667. this.layerMask = 0xFFFFFFFF;
  7668. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7669. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7670. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7671. this._collider = new BABYLON.Collider();
  7672. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7673. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7674. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7675. this._localScaling = BABYLON.Matrix.Zero();
  7676. this._localRotation = BABYLON.Matrix.Zero();
  7677. this._localTranslation = BABYLON.Matrix.Zero();
  7678. this._localBillboard = BABYLON.Matrix.Zero();
  7679. this._localPivotScaling = BABYLON.Matrix.Zero();
  7680. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7681. this._localWorld = BABYLON.Matrix.Zero();
  7682. this._worldMatrix = BABYLON.Matrix.Zero();
  7683. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7684. this._absolutePosition = BABYLON.Vector3.Zero();
  7685. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7686. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7687. this._isDirty = false;
  7688. this._pivotMatrix = BABYLON.Matrix.Identity();
  7689. this._isDisposed = false;
  7690. this._renderId = 0;
  7691. this._intersectionsInProgress = new Array();
  7692. scene.meshes.push(this);
  7693. }
  7694. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7695. get: function () {
  7696. return AbstractMesh._BILLBOARDMODE_NONE;
  7697. },
  7698. enumerable: true,
  7699. configurable: true
  7700. });
  7701. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7702. get: function () {
  7703. return AbstractMesh._BILLBOARDMODE_X;
  7704. },
  7705. enumerable: true,
  7706. configurable: true
  7707. });
  7708. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7709. get: function () {
  7710. return AbstractMesh._BILLBOARDMODE_Y;
  7711. },
  7712. enumerable: true,
  7713. configurable: true
  7714. });
  7715. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7716. get: function () {
  7717. return AbstractMesh._BILLBOARDMODE_Z;
  7718. },
  7719. enumerable: true,
  7720. configurable: true
  7721. });
  7722. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7723. get: function () {
  7724. return AbstractMesh._BILLBOARDMODE_ALL;
  7725. },
  7726. enumerable: true,
  7727. configurable: true
  7728. });
  7729. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7730. get: function () {
  7731. return false;
  7732. },
  7733. enumerable: true,
  7734. configurable: true
  7735. });
  7736. AbstractMesh.prototype.getLOD = function (camera) {
  7737. return this;
  7738. };
  7739. AbstractMesh.prototype.getTotalVertices = function () {
  7740. return 0;
  7741. };
  7742. AbstractMesh.prototype.getIndices = function () {
  7743. return null;
  7744. };
  7745. AbstractMesh.prototype.getVerticesData = function (kind) {
  7746. return null;
  7747. };
  7748. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7749. return false;
  7750. };
  7751. AbstractMesh.prototype.getBoundingInfo = function () {
  7752. if (!this._boundingInfo) {
  7753. this._updateBoundingInfo();
  7754. }
  7755. return this._boundingInfo;
  7756. };
  7757. AbstractMesh.prototype._preActivate = function () {
  7758. };
  7759. AbstractMesh.prototype._activate = function (renderId) {
  7760. this._renderId = renderId;
  7761. };
  7762. AbstractMesh.prototype.getWorldMatrix = function () {
  7763. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7764. this.computeWorldMatrix();
  7765. }
  7766. return this._worldMatrix;
  7767. };
  7768. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7769. get: function () {
  7770. return this._worldMatrix;
  7771. },
  7772. enumerable: true,
  7773. configurable: true
  7774. });
  7775. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7776. get: function () {
  7777. return this._absolutePosition;
  7778. },
  7779. enumerable: true,
  7780. configurable: true
  7781. });
  7782. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7783. if (!this.rotationQuaternion) {
  7784. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7785. this.rotation = BABYLON.Vector3.Zero();
  7786. }
  7787. if (!space || space == 0 /* LOCAL */) {
  7788. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7789. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7790. } else {
  7791. if (this.parent) {
  7792. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7793. invertParentWorldMatrix.invert();
  7794. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7795. }
  7796. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7797. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7798. }
  7799. };
  7800. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7801. var displacementVector = axis.scale(distance);
  7802. if (!space || space == 0 /* LOCAL */) {
  7803. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7804. this.setPositionWithLocalVector(tempV3);
  7805. } else {
  7806. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7807. }
  7808. };
  7809. AbstractMesh.prototype.getAbsolutePosition = function () {
  7810. this.computeWorldMatrix();
  7811. return this._absolutePosition;
  7812. };
  7813. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7814. if (!absolutePosition) {
  7815. return;
  7816. }
  7817. var absolutePositionX;
  7818. var absolutePositionY;
  7819. var absolutePositionZ;
  7820. if (absolutePosition.x === undefined) {
  7821. if (arguments.length < 3) {
  7822. return;
  7823. }
  7824. absolutePositionX = arguments[0];
  7825. absolutePositionY = arguments[1];
  7826. absolutePositionZ = arguments[2];
  7827. } else {
  7828. absolutePositionX = absolutePosition.x;
  7829. absolutePositionY = absolutePosition.y;
  7830. absolutePositionZ = absolutePosition.z;
  7831. }
  7832. if (this.parent) {
  7833. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7834. invertParentWorldMatrix.invert();
  7835. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7836. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7837. } else {
  7838. this.position.x = absolutePositionX;
  7839. this.position.y = absolutePositionY;
  7840. this.position.z = absolutePositionZ;
  7841. }
  7842. };
  7843. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7844. this._pivotMatrix = matrix;
  7845. this._cache.pivotMatrixUpdated = true;
  7846. };
  7847. AbstractMesh.prototype.getPivotMatrix = function () {
  7848. return this._pivotMatrix;
  7849. };
  7850. AbstractMesh.prototype._isSynchronized = function () {
  7851. if (this._isDirty) {
  7852. return false;
  7853. }
  7854. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7855. return false;
  7856. if (this._cache.pivotMatrixUpdated) {
  7857. return false;
  7858. }
  7859. if (this.infiniteDistance) {
  7860. return false;
  7861. }
  7862. if (!this._cache.position.equals(this.position))
  7863. return false;
  7864. if (this.rotationQuaternion) {
  7865. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7866. return false;
  7867. } else {
  7868. if (!this._cache.rotation.equals(this.rotation))
  7869. return false;
  7870. }
  7871. if (!this._cache.scaling.equals(this.scaling))
  7872. return false;
  7873. return true;
  7874. };
  7875. AbstractMesh.prototype._initCache = function () {
  7876. _super.prototype._initCache.call(this);
  7877. this._cache.localMatrixUpdated = false;
  7878. this._cache.position = BABYLON.Vector3.Zero();
  7879. this._cache.scaling = BABYLON.Vector3.Zero();
  7880. this._cache.rotation = BABYLON.Vector3.Zero();
  7881. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7882. };
  7883. AbstractMesh.prototype.markAsDirty = function (property) {
  7884. if (property === "rotation") {
  7885. this.rotationQuaternion = null;
  7886. }
  7887. this._currentRenderId = Number.MAX_VALUE;
  7888. this._isDirty = true;
  7889. };
  7890. AbstractMesh.prototype._updateBoundingInfo = function () {
  7891. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7892. this._boundingInfo._update(this.worldMatrixFromCache);
  7893. if (!this.subMeshes) {
  7894. return;
  7895. }
  7896. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7897. var subMesh = this.subMeshes[subIndex];
  7898. subMesh.updateBoundingInfo(this.worldMatrixFromCache);
  7899. }
  7900. };
  7901. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7902. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  7903. return this._worldMatrix;
  7904. }
  7905. this._cache.position.copyFrom(this.position);
  7906. this._cache.scaling.copyFrom(this.scaling);
  7907. this._cache.pivotMatrixUpdated = false;
  7908. this._currentRenderId = this.getScene().getRenderId();
  7909. this._isDirty = false;
  7910. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7911. if (this.rotationQuaternion) {
  7912. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7913. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7914. } else {
  7915. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7916. this._cache.rotation.copyFrom(this.rotation);
  7917. }
  7918. if (this.infiniteDistance && !this.parent) {
  7919. var camera = this.getScene().activeCamera;
  7920. var cameraWorldMatrix = camera.getWorldMatrix();
  7921. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7922. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7923. } else {
  7924. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7925. }
  7926. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7927. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7928. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7929. var localPosition = this.position.clone();
  7930. var zero = this.getScene().activeCamera.position.clone();
  7931. if (this.parent && this.parent.position) {
  7932. localPosition.addInPlace(this.parent.position);
  7933. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7934. }
  7935. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  7936. zero = this.getScene().activeCamera.position;
  7937. } else {
  7938. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  7939. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7940. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  7941. zero.y = localPosition.y + 0.001;
  7942. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  7943. zero.z = localPosition.z + 0.001;
  7944. }
  7945. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7946. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7947. this._localBillboard.invert();
  7948. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7949. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7950. }
  7951. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7952. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  7953. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7954. } else {
  7955. this._worldMatrix.copyFrom(this._localWorld);
  7956. }
  7957. this._updateBoundingInfo();
  7958. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7959. return this._worldMatrix;
  7960. };
  7961. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7962. this.computeWorldMatrix();
  7963. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7964. };
  7965. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7966. this.computeWorldMatrix();
  7967. var invLocalWorldMatrix = this._localWorld.clone();
  7968. invLocalWorldMatrix.invert();
  7969. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7970. };
  7971. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7972. this.computeWorldMatrix();
  7973. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7974. };
  7975. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7976. yawCor = yawCor || 0;
  7977. pitchCor = pitchCor || 0;
  7978. rollCor = rollCor || 0;
  7979. var dv = targetPoint.subtract(this.position);
  7980. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7981. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7982. var pitch = Math.atan2(dv.y, len);
  7983. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7984. };
  7985. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7986. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  7987. return false;
  7988. }
  7989. return true;
  7990. };
  7991. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  7992. if (!camera) {
  7993. camera = this.getScene().activeCamera;
  7994. }
  7995. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  7996. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  7997. return false;
  7998. }
  7999. return true;
  8000. };
  8001. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8002. if (!this._boundingInfo || !mesh._boundingInfo) {
  8003. return false;
  8004. }
  8005. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8006. };
  8007. AbstractMesh.prototype.intersectsPoint = function (point) {
  8008. if (!this._boundingInfo) {
  8009. return false;
  8010. }
  8011. return this._boundingInfo.intersectsPoint(point);
  8012. };
  8013. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8014. var physicsEngine = this.getScene().getPhysicsEngine();
  8015. if (!physicsEngine) {
  8016. return;
  8017. }
  8018. if (impostor.impostor) {
  8019. options = impostor;
  8020. impostor = impostor.impostor;
  8021. }
  8022. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8023. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8024. physicsEngine._unregisterMesh(this);
  8025. return;
  8026. }
  8027. options.mass = options.mass || 0;
  8028. options.friction = options.friction || 0.2;
  8029. options.restitution = options.restitution || 0.2;
  8030. this._physicImpostor = impostor;
  8031. this._physicsMass = options.mass;
  8032. this._physicsFriction = options.friction;
  8033. this._physicRestitution = options.restitution;
  8034. physicsEngine._registerMesh(this, impostor, options);
  8035. };
  8036. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8037. if (!this._physicImpostor) {
  8038. return BABYLON.PhysicsEngine.NoImpostor;
  8039. }
  8040. return this._physicImpostor;
  8041. };
  8042. AbstractMesh.prototype.getPhysicsMass = function () {
  8043. if (!this._physicsMass) {
  8044. return 0;
  8045. }
  8046. return this._physicsMass;
  8047. };
  8048. AbstractMesh.prototype.getPhysicsFriction = function () {
  8049. if (!this._physicsFriction) {
  8050. return 0;
  8051. }
  8052. return this._physicsFriction;
  8053. };
  8054. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8055. if (!this._physicRestitution) {
  8056. return 0;
  8057. }
  8058. return this._physicRestitution;
  8059. };
  8060. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8061. if (!this._physicImpostor) {
  8062. return;
  8063. }
  8064. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8065. };
  8066. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8067. if (!this._physicImpostor) {
  8068. return;
  8069. }
  8070. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8071. };
  8072. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8073. if (!this._physicImpostor) {
  8074. return;
  8075. }
  8076. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8077. };
  8078. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8079. var globalPosition = this.getAbsolutePosition();
  8080. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8081. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8082. this._collider.radius = this.ellipsoid;
  8083. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  8084. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  8085. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8086. this.position.addInPlace(this._diffPositionForCollisions);
  8087. }
  8088. };
  8089. /**
  8090. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8091. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8092. */
  8093. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8094. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8095. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8096. if (!this._submeshesOctree) {
  8097. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8098. }
  8099. this.computeWorldMatrix(true);
  8100. var bbox = this.getBoundingInfo().boundingBox;
  8101. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8102. return this._submeshesOctree;
  8103. };
  8104. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8105. this._generatePointsArray();
  8106. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8107. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8108. subMesh._lastColliderWorldVertices = [];
  8109. subMesh._trianglePlanes = [];
  8110. var start = subMesh.verticesStart;
  8111. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8112. for (var i = start; i < end; i++) {
  8113. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8114. }
  8115. }
  8116. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  8117. };
  8118. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8119. var subMeshes;
  8120. var len;
  8121. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8122. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8123. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8124. len = intersections.length;
  8125. subMeshes = intersections.data;
  8126. } else {
  8127. subMeshes = this.subMeshes;
  8128. len = subMeshes.length;
  8129. }
  8130. for (var index = 0; index < len; index++) {
  8131. var subMesh = subMeshes[index];
  8132. if (len > 1 && !subMesh._checkCollision(collider))
  8133. continue;
  8134. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8135. }
  8136. };
  8137. AbstractMesh.prototype._checkCollision = function (collider) {
  8138. if (!this._boundingInfo._checkCollision(collider))
  8139. return;
  8140. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8141. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8142. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8143. };
  8144. AbstractMesh.prototype._generatePointsArray = function () {
  8145. return false;
  8146. };
  8147. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8148. var pickingInfo = new BABYLON.PickingInfo();
  8149. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8150. return pickingInfo;
  8151. }
  8152. if (!this._generatePointsArray()) {
  8153. return pickingInfo;
  8154. }
  8155. var intersectInfo = null;
  8156. var subMeshes;
  8157. var len;
  8158. if (this._submeshesOctree && this.useOctreeForPicking) {
  8159. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8160. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8161. len = intersections.length;
  8162. subMeshes = intersections.data;
  8163. } else {
  8164. subMeshes = this.subMeshes;
  8165. len = subMeshes.length;
  8166. }
  8167. for (var index = 0; index < len; index++) {
  8168. var subMesh = subMeshes[index];
  8169. if (len > 1 && !subMesh.canIntersects(ray))
  8170. continue;
  8171. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8172. if (currentIntersectInfo) {
  8173. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8174. intersectInfo = currentIntersectInfo;
  8175. if (fastCheck) {
  8176. break;
  8177. }
  8178. }
  8179. }
  8180. }
  8181. if (intersectInfo) {
  8182. var world = this.getWorldMatrix();
  8183. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8184. var direction = ray.direction.clone();
  8185. direction.normalize();
  8186. direction = direction.scale(intersectInfo.distance);
  8187. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8188. var pickedPoint = worldOrigin.add(worldDirection);
  8189. pickingInfo.hit = true;
  8190. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8191. pickingInfo.pickedPoint = pickedPoint;
  8192. pickingInfo.pickedMesh = this;
  8193. pickingInfo.bu = intersectInfo.bu;
  8194. pickingInfo.bv = intersectInfo.bv;
  8195. pickingInfo.faceId = intersectInfo.faceId;
  8196. return pickingInfo;
  8197. }
  8198. return pickingInfo;
  8199. };
  8200. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8201. return null;
  8202. };
  8203. AbstractMesh.prototype.releaseSubMeshes = function () {
  8204. if (this.subMeshes) {
  8205. while (this.subMeshes.length) {
  8206. this.subMeshes[0].dispose();
  8207. }
  8208. } else {
  8209. this.subMeshes = new Array();
  8210. }
  8211. };
  8212. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8213. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  8214. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8215. }
  8216. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8217. var other = this._intersectionsInProgress[index];
  8218. var pos = other._intersectionsInProgress.indexOf(this);
  8219. other._intersectionsInProgress.splice(pos, 1);
  8220. }
  8221. this._intersectionsInProgress = [];
  8222. this.releaseSubMeshes();
  8223. var index = this.getScene().meshes.indexOf(this);
  8224. if (index != -1) {
  8225. this.getScene().meshes.splice(index, 1);
  8226. }
  8227. if (!doNotRecurse) {
  8228. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8229. if (this.getScene().particleSystems[index].emitter == this) {
  8230. this.getScene().particleSystems[index].dispose();
  8231. index--;
  8232. }
  8233. }
  8234. var objects = this.getScene().meshes.slice(0);
  8235. for (index = 0; index < objects.length; index++) {
  8236. if (objects[index].parent == this) {
  8237. objects[index].dispose();
  8238. }
  8239. }
  8240. } else {
  8241. for (index = 0; index < this.getScene().meshes.length; index++) {
  8242. var obj = this.getScene().meshes[index];
  8243. if (obj.parent === this) {
  8244. obj.parent = null;
  8245. obj.computeWorldMatrix(true);
  8246. }
  8247. }
  8248. }
  8249. this._isDisposed = true;
  8250. if (this.onDispose) {
  8251. this.onDispose();
  8252. }
  8253. };
  8254. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8255. AbstractMesh._BILLBOARDMODE_X = 1;
  8256. AbstractMesh._BILLBOARDMODE_Y = 2;
  8257. AbstractMesh._BILLBOARDMODE_Z = 4;
  8258. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8259. return AbstractMesh;
  8260. })(BABYLON.Node);
  8261. BABYLON.AbstractMesh = AbstractMesh;
  8262. })(BABYLON || (BABYLON = {}));
  8263. var __extends = this.__extends || function (d, b) {
  8264. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8265. function __() { this.constructor = d; }
  8266. __.prototype = b.prototype;
  8267. d.prototype = new __();
  8268. };
  8269. var BABYLON;
  8270. (function (BABYLON) {
  8271. var _InstancesBatch = (function () {
  8272. function _InstancesBatch() {
  8273. this.mustReturn = false;
  8274. this.visibleInstances = new Array();
  8275. this.renderSelf = new Array();
  8276. }
  8277. return _InstancesBatch;
  8278. })();
  8279. BABYLON._InstancesBatch = _InstancesBatch;
  8280. var Mesh = (function (_super) {
  8281. __extends(Mesh, _super);
  8282. function Mesh(name, scene) {
  8283. _super.call(this, name, scene);
  8284. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  8285. this.instances = new Array();
  8286. this._LODLevels = new Array();
  8287. this._onBeforeRenderCallbacks = new Array();
  8288. this._onAfterRenderCallbacks = new Array();
  8289. this._visibleInstances = {};
  8290. this._renderIdForInstances = new Array();
  8291. this._batchCache = new _InstancesBatch();
  8292. this._instancesBufferSize = 32 * 16 * 4;
  8293. }
  8294. Mesh.prototype._sortLODLevels = function () {
  8295. this._LODLevels.sort(function (a, b) {
  8296. if (a.distance < b.distance) {
  8297. return 1;
  8298. }
  8299. if (a.distance > b.distance) {
  8300. return -1;
  8301. }
  8302. return 0;
  8303. });
  8304. };
  8305. Mesh.prototype.addLODLevel = function (distance, mesh) {
  8306. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  8307. this._LODLevels.push(level);
  8308. if (mesh) {
  8309. mesh._attachedLODLevel = level;
  8310. }
  8311. this._sortLODLevels();
  8312. return this;
  8313. };
  8314. Mesh.prototype.removeLODLevel = function (mesh) {
  8315. if (mesh && !mesh._attachedLODLevel) {
  8316. return this;
  8317. }
  8318. var index;
  8319. if (mesh) {
  8320. index = this._LODLevels.indexOf(mesh._attachedLODLevel);
  8321. mesh._attachedLODLevel = null;
  8322. this._LODLevels.splice(index, 1);
  8323. this._sortLODLevels();
  8324. } else {
  8325. for (index = 0; index < this._LODLevels.length; index++) {
  8326. if (this._LODLevels[index].mesh === null) {
  8327. this._LODLevels.splice(index, 1);
  8328. break;
  8329. }
  8330. }
  8331. }
  8332. return this;
  8333. };
  8334. Mesh.prototype.getLOD = function (camera) {
  8335. if (!this._LODLevels || this._LODLevels.length === 0) {
  8336. return this;
  8337. }
  8338. var distanceToCamera = this.getBoundingInfo().boundingSphere.centerWorld.subtract(camera.position).length();
  8339. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  8340. return this;
  8341. }
  8342. for (var index = 0; index < this._LODLevels.length; index++) {
  8343. var level = this._LODLevels[index];
  8344. if (level.distance < distanceToCamera) {
  8345. if (level.mesh) {
  8346. level.mesh._worldMatrix = this._worldMatrix;
  8347. }
  8348. return level.mesh;
  8349. }
  8350. }
  8351. return this;
  8352. };
  8353. Mesh.prototype.getTotalVertices = function () {
  8354. if (!this._geometry) {
  8355. return 0;
  8356. }
  8357. return this._geometry.getTotalVertices();
  8358. };
  8359. Mesh.prototype.getVerticesData = function (kind) {
  8360. if (!this._geometry) {
  8361. return null;
  8362. }
  8363. return this._geometry.getVerticesData(kind);
  8364. };
  8365. Mesh.prototype.getVertexBuffer = function (kind) {
  8366. if (!this._geometry) {
  8367. return undefined;
  8368. }
  8369. return this._geometry.getVertexBuffer(kind);
  8370. };
  8371. Mesh.prototype.isVerticesDataPresent = function (kind) {
  8372. if (!this._geometry) {
  8373. if (this._delayInfo) {
  8374. return this._delayInfo.indexOf(kind) !== -1;
  8375. }
  8376. return false;
  8377. }
  8378. return this._geometry.isVerticesDataPresent(kind);
  8379. };
  8380. Mesh.prototype.getVerticesDataKinds = function () {
  8381. if (!this._geometry) {
  8382. var result = [];
  8383. if (this._delayInfo) {
  8384. for (var kind in this._delayInfo) {
  8385. result.push(kind);
  8386. }
  8387. }
  8388. return result;
  8389. }
  8390. return this._geometry.getVerticesDataKinds();
  8391. };
  8392. Mesh.prototype.getTotalIndices = function () {
  8393. if (!this._geometry) {
  8394. return 0;
  8395. }
  8396. return this._geometry.getTotalIndices();
  8397. };
  8398. Mesh.prototype.getIndices = function () {
  8399. if (!this._geometry) {
  8400. return [];
  8401. }
  8402. return this._geometry.getIndices();
  8403. };
  8404. Object.defineProperty(Mesh.prototype, "isBlocked", {
  8405. get: function () {
  8406. return this._attachedLODLevel !== null && this._attachedLODLevel !== undefined;
  8407. },
  8408. enumerable: true,
  8409. configurable: true
  8410. });
  8411. Mesh.prototype.isReady = function () {
  8412. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8413. return false;
  8414. }
  8415. return _super.prototype.isReady.call(this);
  8416. };
  8417. Mesh.prototype.isDisposed = function () {
  8418. return this._isDisposed;
  8419. };
  8420. Mesh.prototype._preActivate = function () {
  8421. var sceneRenderId = this.getScene().getRenderId();
  8422. if (this._preActivateId == sceneRenderId) {
  8423. return;
  8424. }
  8425. this._preActivateId = sceneRenderId;
  8426. this._visibleInstances = null;
  8427. };
  8428. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  8429. if (!this._visibleInstances) {
  8430. this._visibleInstances = {};
  8431. this._visibleInstances.defaultRenderId = renderId;
  8432. this._visibleInstances.selfDefaultRenderId = this._renderId;
  8433. }
  8434. if (!this._visibleInstances[renderId]) {
  8435. this._visibleInstances[renderId] = new Array();
  8436. }
  8437. this._visibleInstances[renderId].push(instance);
  8438. };
  8439. Mesh.prototype.refreshBoundingInfo = function () {
  8440. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8441. if (data) {
  8442. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  8443. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8444. }
  8445. if (this.subMeshes) {
  8446. for (var index = 0; index < this.subMeshes.length; index++) {
  8447. this.subMeshes[index].refreshBoundingInfo();
  8448. }
  8449. }
  8450. this._updateBoundingInfo();
  8451. };
  8452. Mesh.prototype._createGlobalSubMesh = function () {
  8453. var totalVertices = this.getTotalVertices();
  8454. if (!totalVertices || !this.getIndices()) {
  8455. return null;
  8456. }
  8457. this.releaseSubMeshes();
  8458. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  8459. };
  8460. Mesh.prototype.subdivide = function (count) {
  8461. if (count < 1) {
  8462. return;
  8463. }
  8464. var totalIndices = this.getTotalIndices();
  8465. var subdivisionSize = (totalIndices / count) | 0;
  8466. var offset = 0;
  8467. while (subdivisionSize % 3 != 0) {
  8468. subdivisionSize++;
  8469. }
  8470. this.releaseSubMeshes();
  8471. for (var index = 0; index < count; index++) {
  8472. if (offset >= totalIndices) {
  8473. break;
  8474. }
  8475. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  8476. offset += subdivisionSize;
  8477. }
  8478. this.synchronizeInstances();
  8479. };
  8480. Mesh.prototype.setVerticesData = function (kind, data, updatable) {
  8481. if (kind instanceof Array) {
  8482. var temp = data;
  8483. data = kind;
  8484. kind = temp;
  8485. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  8486. }
  8487. if (!this._geometry) {
  8488. var vertexData = new BABYLON.VertexData();
  8489. vertexData.set(data, kind);
  8490. var scene = this.getScene();
  8491. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  8492. } else {
  8493. this._geometry.setVerticesData(kind, data, updatable);
  8494. }
  8495. };
  8496. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  8497. if (!this._geometry) {
  8498. return;
  8499. }
  8500. if (!makeItUnique) {
  8501. this._geometry.updateVerticesData(kind, data, updateExtends);
  8502. } else {
  8503. this.makeGeometryUnique();
  8504. this.updateVerticesData(kind, data, updateExtends, false);
  8505. }
  8506. };
  8507. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, makeItUnique) {
  8508. if (!this._geometry) {
  8509. return;
  8510. }
  8511. if (!makeItUnique) {
  8512. this._geometry.updateVerticesDataDirectly(kind, data);
  8513. } else {
  8514. this.makeGeometryUnique();
  8515. this.updateVerticesDataDirectly(kind, data, false);
  8516. }
  8517. };
  8518. Mesh.prototype.makeGeometryUnique = function () {
  8519. if (!this._geometry) {
  8520. return;
  8521. }
  8522. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  8523. geometry.applyToMesh(this);
  8524. };
  8525. Mesh.prototype.setIndices = function (indices) {
  8526. if (!this._geometry) {
  8527. var vertexData = new BABYLON.VertexData();
  8528. vertexData.indices = indices;
  8529. var scene = this.getScene();
  8530. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  8531. } else {
  8532. this._geometry.setIndices(indices);
  8533. }
  8534. };
  8535. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  8536. var engine = this.getScene().getEngine();
  8537. var indexToBind;
  8538. switch (fillMode) {
  8539. case BABYLON.Material.PointFillMode:
  8540. indexToBind = null;
  8541. break;
  8542. case BABYLON.Material.WireFrameFillMode:
  8543. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  8544. break;
  8545. default:
  8546. case BABYLON.Material.TriangleFillMode:
  8547. indexToBind = this._geometry.getIndexBuffer();
  8548. break;
  8549. }
  8550. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  8551. };
  8552. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  8553. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8554. return;
  8555. }
  8556. var engine = this.getScene().getEngine();
  8557. switch (fillMode) {
  8558. case BABYLON.Material.PointFillMode:
  8559. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  8560. break;
  8561. case BABYLON.Material.WireFrameFillMode:
  8562. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  8563. break;
  8564. default:
  8565. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  8566. }
  8567. };
  8568. Mesh.prototype.registerBeforeRender = function (func) {
  8569. this._onBeforeRenderCallbacks.push(func);
  8570. };
  8571. Mesh.prototype.unregisterBeforeRender = function (func) {
  8572. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8573. if (index > -1) {
  8574. this._onBeforeRenderCallbacks.splice(index, 1);
  8575. }
  8576. };
  8577. Mesh.prototype.registerAfterRender = function (func) {
  8578. this._onAfterRenderCallbacks.push(func);
  8579. };
  8580. Mesh.prototype.unregisterAfterRender = function (func) {
  8581. var index = this._onAfterRenderCallbacks.indexOf(func);
  8582. if (index > -1) {
  8583. this._onAfterRenderCallbacks.splice(index, 1);
  8584. }
  8585. };
  8586. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  8587. var scene = this.getScene();
  8588. this._batchCache.mustReturn = false;
  8589. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  8590. this._batchCache.visibleInstances[subMeshId] = null;
  8591. if (this._visibleInstances) {
  8592. var currentRenderId = scene.getRenderId();
  8593. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  8594. var selfRenderId = this._renderId;
  8595. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  8596. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  8597. currentRenderId = this._visibleInstances.defaultRenderId;
  8598. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  8599. }
  8600. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  8601. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  8602. this._batchCache.mustReturn = true;
  8603. return this._batchCache;
  8604. }
  8605. if (currentRenderId !== selfRenderId) {
  8606. this._batchCache.renderSelf[subMeshId] = false;
  8607. }
  8608. }
  8609. this._renderIdForInstances[subMeshId] = currentRenderId;
  8610. }
  8611. return this._batchCache;
  8612. };
  8613. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  8614. var matricesCount = this.instances.length + 1;
  8615. var bufferSize = matricesCount * 16 * 4;
  8616. while (this._instancesBufferSize < bufferSize) {
  8617. this._instancesBufferSize *= 2;
  8618. }
  8619. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  8620. if (this._worldMatricesInstancesBuffer) {
  8621. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8622. }
  8623. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  8624. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  8625. }
  8626. var offset = 0;
  8627. var instancesCount = 0;
  8628. var world = this.getWorldMatrix();
  8629. if (batch.renderSelf[subMesh._id]) {
  8630. world.copyToArray(this._worldMatricesInstancesArray, offset);
  8631. offset += 16;
  8632. instancesCount++;
  8633. }
  8634. var visibleInstances = batch.visibleInstances[subMesh._id];
  8635. if (visibleInstances) {
  8636. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  8637. var instance = visibleInstances[instanceIndex];
  8638. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  8639. offset += 16;
  8640. instancesCount++;
  8641. }
  8642. }
  8643. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  8644. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  8645. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  8646. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  8647. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  8648. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  8649. this._draw(subMesh, fillMode, instancesCount);
  8650. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  8651. };
  8652. Mesh.prototype.render = function (subMesh) {
  8653. var scene = this.getScene();
  8654. var batch = this._getInstancesRenderList(subMesh._id);
  8655. if (batch.mustReturn) {
  8656. return;
  8657. }
  8658. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8659. return;
  8660. }
  8661. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8662. this._onBeforeRenderCallbacks[callbackIndex]();
  8663. }
  8664. var engine = scene.getEngine();
  8665. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8666. var effectiveMaterial = subMesh.getMaterial();
  8667. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  8668. return;
  8669. }
  8670. var savedDepthWrite = engine.getDepthWrite();
  8671. if (this.renderOutline) {
  8672. engine.setDepthWrite(false);
  8673. scene.getOutlineRenderer().render(subMesh, batch);
  8674. }
  8675. effectiveMaterial._preBind();
  8676. var effect = effectiveMaterial.getEffect();
  8677. var fillMode = engine.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode;
  8678. this._bind(subMesh, effect, fillMode);
  8679. var world = this.getWorldMatrix();
  8680. effectiveMaterial.bind(world, this);
  8681. if (hardwareInstancedRendering) {
  8682. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  8683. } else {
  8684. if (batch.renderSelf[subMesh._id]) {
  8685. this._draw(subMesh, fillMode);
  8686. }
  8687. if (batch.visibleInstances[subMesh._id]) {
  8688. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  8689. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  8690. world = instance.getWorldMatrix();
  8691. effectiveMaterial.bindOnlyWorldMatrix(world);
  8692. this._draw(subMesh, fillMode);
  8693. }
  8694. }
  8695. }
  8696. effectiveMaterial.unbind();
  8697. if (this.renderOutline && savedDepthWrite) {
  8698. engine.setDepthWrite(true);
  8699. engine.setColorWrite(false);
  8700. scene.getOutlineRenderer().render(subMesh, batch);
  8701. engine.setColorWrite(true);
  8702. }
  8703. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8704. this._onAfterRenderCallbacks[callbackIndex]();
  8705. }
  8706. };
  8707. Mesh.prototype.getEmittedParticleSystems = function () {
  8708. var results = new Array();
  8709. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8710. var particleSystem = this.getScene().particleSystems[index];
  8711. if (particleSystem.emitter === this) {
  8712. results.push(particleSystem);
  8713. }
  8714. }
  8715. return results;
  8716. };
  8717. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  8718. var results = new Array();
  8719. var descendants = this.getDescendants();
  8720. descendants.push(this);
  8721. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8722. var particleSystem = this.getScene().particleSystems[index];
  8723. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  8724. results.push(particleSystem);
  8725. }
  8726. }
  8727. return results;
  8728. };
  8729. Mesh.prototype.getChildren = function () {
  8730. var results = [];
  8731. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8732. var mesh = this.getScene().meshes[index];
  8733. if (mesh.parent == this) {
  8734. results.push(mesh);
  8735. }
  8736. }
  8737. return results;
  8738. };
  8739. Mesh.prototype._checkDelayState = function () {
  8740. var _this = this;
  8741. var that = this;
  8742. var scene = this.getScene();
  8743. if (this._geometry) {
  8744. this._geometry.load(scene);
  8745. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8746. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  8747. scene._addPendingData(that);
  8748. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  8749. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  8750. if (data instanceof ArrayBuffer) {
  8751. _this._delayLoadingFunction(data, _this);
  8752. } else {
  8753. _this._delayLoadingFunction(JSON.parse(data), _this);
  8754. }
  8755. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  8756. scene._removePendingData(_this);
  8757. }, function () {
  8758. }, scene.database, getBinaryData);
  8759. }
  8760. };
  8761. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  8762. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8763. return false;
  8764. }
  8765. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  8766. return false;
  8767. }
  8768. this._checkDelayState();
  8769. return true;
  8770. };
  8771. Mesh.prototype.setMaterialByID = function (id) {
  8772. var materials = this.getScene().materials;
  8773. for (var index = 0; index < materials.length; index++) {
  8774. if (materials[index].id == id) {
  8775. this.material = materials[index];
  8776. return;
  8777. }
  8778. }
  8779. var multiMaterials = this.getScene().multiMaterials;
  8780. for (index = 0; index < multiMaterials.length; index++) {
  8781. if (multiMaterials[index].id == id) {
  8782. this.material = multiMaterials[index];
  8783. return;
  8784. }
  8785. }
  8786. };
  8787. Mesh.prototype.getAnimatables = function () {
  8788. var results = [];
  8789. if (this.material) {
  8790. results.push(this.material);
  8791. }
  8792. if (this.skeleton) {
  8793. results.push(this.skeleton);
  8794. }
  8795. return results;
  8796. };
  8797. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  8798. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  8799. return;
  8800. }
  8801. this._resetPointsArrayCache();
  8802. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8803. var temp = [];
  8804. for (var index = 0; index < data.length; index += 3) {
  8805. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8806. }
  8807. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  8808. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8809. return;
  8810. }
  8811. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8812. for (index = 0; index < data.length; index += 3) {
  8813. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8814. }
  8815. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  8816. };
  8817. Mesh.prototype._resetPointsArrayCache = function () {
  8818. this._positions = null;
  8819. };
  8820. Mesh.prototype._generatePointsArray = function () {
  8821. if (this._positions)
  8822. return true;
  8823. this._positions = [];
  8824. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8825. if (!data) {
  8826. return false;
  8827. }
  8828. for (var index = 0; index < data.length; index += 3) {
  8829. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  8830. }
  8831. return true;
  8832. };
  8833. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8834. var result = new BABYLON.Mesh(name, this.getScene());
  8835. this._geometry.applyToMesh(result);
  8836. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  8837. result.material = this.material;
  8838. if (newParent) {
  8839. result.parent = newParent;
  8840. }
  8841. if (!doNotCloneChildren) {
  8842. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8843. var mesh = this.getScene().meshes[index];
  8844. if (mesh.parent == this) {
  8845. mesh.clone(mesh.name, result);
  8846. }
  8847. }
  8848. }
  8849. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8850. var system = this.getScene().particleSystems[index];
  8851. if (system.emitter == this) {
  8852. system.clone(system.name, result);
  8853. }
  8854. }
  8855. result.computeWorldMatrix(true);
  8856. return result;
  8857. };
  8858. Mesh.prototype.dispose = function (doNotRecurse) {
  8859. if (this._geometry) {
  8860. this._geometry.releaseForMesh(this, true);
  8861. }
  8862. if (this._worldMatricesInstancesBuffer) {
  8863. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8864. this._worldMatricesInstancesBuffer = null;
  8865. }
  8866. while (this.instances.length) {
  8867. this.instances[0].dispose();
  8868. }
  8869. _super.prototype.dispose.call(this, doNotRecurse);
  8870. };
  8871. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  8872. var _this = this;
  8873. var scene = this.getScene();
  8874. var onload = function (img) {
  8875. var canvas = document.createElement("canvas");
  8876. var context = canvas.getContext("2d");
  8877. var heightMapWidth = img.width;
  8878. var heightMapHeight = img.height;
  8879. canvas.width = heightMapWidth;
  8880. canvas.height = heightMapHeight;
  8881. context.drawImage(img, 0, 0);
  8882. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8883. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  8884. };
  8885. BABYLON.Tools.LoadImage(url, onload, function () {
  8886. }, scene.database);
  8887. };
  8888. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  8889. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8890. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  8891. return;
  8892. }
  8893. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8894. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8895. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8896. var position = BABYLON.Vector3.Zero();
  8897. var normal = BABYLON.Vector3.Zero();
  8898. var uv = BABYLON.Vector2.Zero();
  8899. for (var index = 0; index < positions.length; index += 3) {
  8900. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  8901. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  8902. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  8903. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  8904. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  8905. var pos = (u + v * heightMapWidth) * 4;
  8906. var r = buffer[pos] / 255.0;
  8907. var g = buffer[pos + 1] / 255.0;
  8908. var b = buffer[pos + 2] / 255.0;
  8909. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  8910. normal.normalize();
  8911. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  8912. position = position.add(normal);
  8913. position.toArray(positions, index);
  8914. }
  8915. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  8916. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  8917. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  8918. };
  8919. Mesh.prototype.convertToFlatShadedMesh = function () {
  8920. var kinds = this.getVerticesDataKinds();
  8921. var vbs = [];
  8922. var data = [];
  8923. var newdata = [];
  8924. var updatableNormals = false;
  8925. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8926. var kind = kinds[kindIndex];
  8927. var vertexBuffer = this.getVertexBuffer(kind);
  8928. if (kind === BABYLON.VertexBuffer.NormalKind) {
  8929. updatableNormals = vertexBuffer.isUpdatable();
  8930. kinds.splice(kindIndex, 1);
  8931. kindIndex--;
  8932. continue;
  8933. }
  8934. vbs[kind] = vertexBuffer;
  8935. data[kind] = vbs[kind].getData();
  8936. newdata[kind] = [];
  8937. }
  8938. var previousSubmeshes = this.subMeshes.slice(0);
  8939. var indices = this.getIndices();
  8940. var totalIndices = this.getTotalIndices();
  8941. for (index = 0; index < totalIndices; index++) {
  8942. var vertexIndex = indices[index];
  8943. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8944. kind = kinds[kindIndex];
  8945. var stride = vbs[kind].getStrideSize();
  8946. for (var offset = 0; offset < stride; offset++) {
  8947. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  8948. }
  8949. }
  8950. }
  8951. var normals = [];
  8952. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  8953. for (var index = 0; index < totalIndices; index += 3) {
  8954. indices[index] = index;
  8955. indices[index + 1] = index + 1;
  8956. indices[index + 2] = index + 2;
  8957. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  8958. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  8959. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  8960. var p1p2 = p1.subtract(p2);
  8961. var p3p2 = p3.subtract(p2);
  8962. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  8963. for (var localIndex = 0; localIndex < 3; localIndex++) {
  8964. normals.push(normal.x);
  8965. normals.push(normal.y);
  8966. normals.push(normal.z);
  8967. }
  8968. }
  8969. this.setIndices(indices);
  8970. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  8971. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8972. kind = kinds[kindIndex];
  8973. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  8974. }
  8975. this.releaseSubMeshes();
  8976. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  8977. var previousOne = previousSubmeshes[submeshIndex];
  8978. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  8979. }
  8980. this.synchronizeInstances();
  8981. };
  8982. Mesh.prototype.createInstance = function (name) {
  8983. return new BABYLON.InstancedMesh(name, this);
  8984. };
  8985. Mesh.prototype.synchronizeInstances = function () {
  8986. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  8987. var instance = this.instances[instanceIndex];
  8988. instance._syncSubMeshes();
  8989. }
  8990. };
  8991. Mesh.CreateBox = function (name, size, scene, updatable) {
  8992. var box = new BABYLON.Mesh(name, scene);
  8993. var vertexData = BABYLON.VertexData.CreateBox(size);
  8994. vertexData.applyToMesh(box, updatable);
  8995. return box;
  8996. };
  8997. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  8998. var sphere = new BABYLON.Mesh(name, scene);
  8999. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  9000. vertexData.applyToMesh(sphere, updatable);
  9001. return sphere;
  9002. };
  9003. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  9004. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  9005. if (scene !== undefined) {
  9006. updatable = scene;
  9007. }
  9008. scene = subdivisions;
  9009. subdivisions = 1;
  9010. }
  9011. var cylinder = new BABYLON.Mesh(name, scene);
  9012. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  9013. vertexData.applyToMesh(cylinder, updatable);
  9014. return cylinder;
  9015. };
  9016. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  9017. var torus = new BABYLON.Mesh(name, scene);
  9018. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  9019. vertexData.applyToMesh(torus, updatable);
  9020. return torus;
  9021. };
  9022. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  9023. var torusKnot = new BABYLON.Mesh(name, scene);
  9024. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  9025. vertexData.applyToMesh(torusKnot, updatable);
  9026. return torusKnot;
  9027. };
  9028. Mesh.CreateLines = function (name, points, scene, updatable) {
  9029. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  9030. var vertexData = BABYLON.VertexData.CreateLines(points);
  9031. vertexData.applyToMesh(lines, updatable);
  9032. return lines;
  9033. };
  9034. Mesh.CreatePlane = function (name, size, scene, updatable) {
  9035. var plane = new BABYLON.Mesh(name, scene);
  9036. var vertexData = BABYLON.VertexData.CreatePlane(size);
  9037. vertexData.applyToMesh(plane, updatable);
  9038. return plane;
  9039. };
  9040. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  9041. var ground = new BABYLON.GroundMesh(name, scene);
  9042. ground._setReady(false);
  9043. ground._subdivisions = subdivisions;
  9044. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  9045. vertexData.applyToMesh(ground, updatable);
  9046. ground._setReady(true);
  9047. return ground;
  9048. };
  9049. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  9050. var tiledGround = new BABYLON.Mesh(name, scene);
  9051. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  9052. vertexData.applyToMesh(tiledGround, updatable);
  9053. return tiledGround;
  9054. };
  9055. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  9056. var ground = new BABYLON.GroundMesh(name, scene);
  9057. ground._subdivisions = subdivisions;
  9058. ground._setReady(false);
  9059. var onload = function (img) {
  9060. var canvas = document.createElement("canvas");
  9061. var context = canvas.getContext("2d");
  9062. var heightMapWidth = img.width;
  9063. var heightMapHeight = img.height;
  9064. canvas.width = heightMapWidth;
  9065. canvas.height = heightMapHeight;
  9066. context.drawImage(img, 0, 0);
  9067. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  9068. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  9069. vertexData.applyToMesh(ground, updatable);
  9070. ground._setReady(true);
  9071. };
  9072. BABYLON.Tools.LoadImage(url, onload, function () {
  9073. }, scene.database);
  9074. return ground;
  9075. };
  9076. Mesh.MinMax = function (meshes) {
  9077. var minVector = null;
  9078. var maxVector = null;
  9079. for (var i in meshes) {
  9080. var mesh = meshes[i];
  9081. var boundingBox = mesh.getBoundingInfo().boundingBox;
  9082. if (!minVector) {
  9083. minVector = boundingBox.minimumWorld;
  9084. maxVector = boundingBox.maximumWorld;
  9085. continue;
  9086. }
  9087. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  9088. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  9089. }
  9090. return {
  9091. min: minVector,
  9092. max: maxVector
  9093. };
  9094. };
  9095. Mesh.Center = function (meshesOrMinMaxVector) {
  9096. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  9097. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  9098. };
  9099. return Mesh;
  9100. })(BABYLON.AbstractMesh);
  9101. BABYLON.Mesh = Mesh;
  9102. })(BABYLON || (BABYLON = {}));
  9103. var __extends = this.__extends || function (d, b) {
  9104. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9105. function __() { this.constructor = d; }
  9106. __.prototype = b.prototype;
  9107. d.prototype = new __();
  9108. };
  9109. var BABYLON;
  9110. (function (BABYLON) {
  9111. var GroundMesh = (function (_super) {
  9112. __extends(GroundMesh, _super);
  9113. function GroundMesh(name, scene) {
  9114. _super.call(this, name, scene);
  9115. this.generateOctree = false;
  9116. this._worldInverse = new BABYLON.Matrix();
  9117. }
  9118. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  9119. get: function () {
  9120. return this._subdivisions;
  9121. },
  9122. enumerable: true,
  9123. configurable: true
  9124. });
  9125. GroundMesh.prototype.optimize = function (chunksCount) {
  9126. this.subdivide(this._subdivisions);
  9127. this.createOrUpdateSubmeshesOctree(32);
  9128. };
  9129. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  9130. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  9131. this.getWorldMatrix().invertToRef(this._worldInverse);
  9132. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  9133. var pickInfo = this.intersects(ray);
  9134. if (pickInfo.hit) {
  9135. return pickInfo.pickedPoint.y;
  9136. }
  9137. return 0;
  9138. };
  9139. return GroundMesh;
  9140. })(BABYLON.Mesh);
  9141. BABYLON.GroundMesh = GroundMesh;
  9142. })(BABYLON || (BABYLON = {}));
  9143. var __extends = this.__extends || function (d, b) {
  9144. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9145. function __() { this.constructor = d; }
  9146. __.prototype = b.prototype;
  9147. d.prototype = new __();
  9148. };
  9149. var BABYLON;
  9150. (function (BABYLON) {
  9151. var InstancedMesh = (function (_super) {
  9152. __extends(InstancedMesh, _super);
  9153. function InstancedMesh(name, source) {
  9154. _super.call(this, name, source.getScene());
  9155. source.instances.push(this);
  9156. this._sourceMesh = source;
  9157. this.position.copyFrom(source.position);
  9158. this.rotation.copyFrom(source.rotation);
  9159. this.scaling.copyFrom(source.scaling);
  9160. if (source.rotationQuaternion) {
  9161. this.rotationQuaternion = source.rotationQuaternion.clone();
  9162. }
  9163. this.infiniteDistance = source.infiniteDistance;
  9164. this.setPivotMatrix(source.getPivotMatrix());
  9165. this.refreshBoundingInfo();
  9166. this._syncSubMeshes();
  9167. }
  9168. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  9169. get: function () {
  9170. return this._sourceMesh.receiveShadows;
  9171. },
  9172. enumerable: true,
  9173. configurable: true
  9174. });
  9175. Object.defineProperty(InstancedMesh.prototype, "material", {
  9176. get: function () {
  9177. return this._sourceMesh.material;
  9178. },
  9179. enumerable: true,
  9180. configurable: true
  9181. });
  9182. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  9183. get: function () {
  9184. return this._sourceMesh.visibility;
  9185. },
  9186. enumerable: true,
  9187. configurable: true
  9188. });
  9189. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  9190. get: function () {
  9191. return this._sourceMesh.skeleton;
  9192. },
  9193. enumerable: true,
  9194. configurable: true
  9195. });
  9196. InstancedMesh.prototype.getTotalVertices = function () {
  9197. return this._sourceMesh.getTotalVertices();
  9198. };
  9199. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  9200. get: function () {
  9201. return this._sourceMesh;
  9202. },
  9203. enumerable: true,
  9204. configurable: true
  9205. });
  9206. InstancedMesh.prototype.getVerticesData = function (kind) {
  9207. return this._sourceMesh.getVerticesData(kind);
  9208. };
  9209. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  9210. return this._sourceMesh.isVerticesDataPresent(kind);
  9211. };
  9212. InstancedMesh.prototype.getIndices = function () {
  9213. return this._sourceMesh.getIndices();
  9214. };
  9215. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  9216. get: function () {
  9217. return this._sourceMesh._positions;
  9218. },
  9219. enumerable: true,
  9220. configurable: true
  9221. });
  9222. InstancedMesh.prototype.refreshBoundingInfo = function () {
  9223. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9224. if (data) {
  9225. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  9226. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9227. }
  9228. this._updateBoundingInfo();
  9229. };
  9230. InstancedMesh.prototype._preActivate = function () {
  9231. this.sourceMesh._preActivate();
  9232. };
  9233. InstancedMesh.prototype._activate = function (renderId) {
  9234. this.sourceMesh._registerInstanceForRenderId(this, renderId);
  9235. };
  9236. InstancedMesh.prototype._syncSubMeshes = function () {
  9237. this.releaseSubMeshes();
  9238. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  9239. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  9240. }
  9241. };
  9242. InstancedMesh.prototype._generatePointsArray = function () {
  9243. return this._sourceMesh._generatePointsArray();
  9244. };
  9245. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9246. var result = this._sourceMesh.createInstance(name);
  9247. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  9248. this.refreshBoundingInfo();
  9249. if (newParent) {
  9250. result.parent = newParent;
  9251. }
  9252. if (!doNotCloneChildren) {
  9253. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9254. var mesh = this.getScene().meshes[index];
  9255. if (mesh.parent == this) {
  9256. mesh.clone(mesh.name, result);
  9257. }
  9258. }
  9259. }
  9260. result.computeWorldMatrix(true);
  9261. return result;
  9262. };
  9263. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  9264. var index = this._sourceMesh.instances.indexOf(this);
  9265. this._sourceMesh.instances.splice(index, 1);
  9266. _super.prototype.dispose.call(this, doNotRecurse);
  9267. };
  9268. return InstancedMesh;
  9269. })(BABYLON.AbstractMesh);
  9270. BABYLON.InstancedMesh = InstancedMesh;
  9271. })(BABYLON || (BABYLON = {}));
  9272. var BABYLON;
  9273. (function (BABYLON) {
  9274. var SubMesh = (function () {
  9275. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  9276. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  9277. this.materialIndex = materialIndex;
  9278. this.verticesStart = verticesStart;
  9279. this.verticesCount = verticesCount;
  9280. this.indexStart = indexStart;
  9281. this.indexCount = indexCount;
  9282. this._renderId = 0;
  9283. this._mesh = mesh;
  9284. this._renderingMesh = renderingMesh || mesh;
  9285. mesh.subMeshes.push(this);
  9286. this._id = mesh.subMeshes.length - 1;
  9287. if (createBoundingBox) {
  9288. this.refreshBoundingInfo();
  9289. }
  9290. }
  9291. SubMesh.prototype.getBoundingInfo = function () {
  9292. return this._boundingInfo;
  9293. };
  9294. SubMesh.prototype.getMesh = function () {
  9295. return this._mesh;
  9296. };
  9297. SubMesh.prototype.getRenderingMesh = function () {
  9298. return this._renderingMesh;
  9299. };
  9300. SubMesh.prototype.getMaterial = function () {
  9301. var rootMaterial = this._renderingMesh.material;
  9302. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  9303. var multiMaterial = rootMaterial;
  9304. return multiMaterial.getSubMaterial(this.materialIndex);
  9305. }
  9306. if (!rootMaterial) {
  9307. return this._mesh.getScene().defaultMaterial;
  9308. }
  9309. return rootMaterial;
  9310. };
  9311. SubMesh.prototype.refreshBoundingInfo = function () {
  9312. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9313. if (!data) {
  9314. this._boundingInfo = this._mesh._boundingInfo;
  9315. return;
  9316. }
  9317. var indices = this._renderingMesh.getIndices();
  9318. var extend;
  9319. if (this.indexStart === 0 && this.indexCount === indices.length) {
  9320. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  9321. } else {
  9322. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  9323. }
  9324. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9325. };
  9326. SubMesh.prototype._checkCollision = function (collider) {
  9327. return this._boundingInfo._checkCollision(collider);
  9328. };
  9329. SubMesh.prototype.updateBoundingInfo = function (world) {
  9330. if (!this._boundingInfo) {
  9331. this.refreshBoundingInfo();
  9332. }
  9333. this._boundingInfo._update(world);
  9334. };
  9335. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  9336. return this._boundingInfo.isInFrustum(frustumPlanes);
  9337. };
  9338. SubMesh.prototype.render = function () {
  9339. this._renderingMesh.render(this);
  9340. };
  9341. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  9342. if (!this._linesIndexBuffer) {
  9343. var linesIndices = [];
  9344. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  9345. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  9346. }
  9347. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  9348. this.linesIndexCount = linesIndices.length;
  9349. }
  9350. return this._linesIndexBuffer;
  9351. };
  9352. SubMesh.prototype.canIntersects = function (ray) {
  9353. return ray.intersectsBox(this._boundingInfo.boundingBox);
  9354. };
  9355. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  9356. var intersectInfo = null;
  9357. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  9358. var p0 = positions[indices[index]];
  9359. var p1 = positions[indices[index + 1]];
  9360. var p2 = positions[indices[index + 2]];
  9361. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  9362. if (currentIntersectInfo) {
  9363. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9364. intersectInfo = currentIntersectInfo;
  9365. intersectInfo.faceId = index / 3;
  9366. if (fastCheck) {
  9367. break;
  9368. }
  9369. }
  9370. }
  9371. }
  9372. return intersectInfo;
  9373. };
  9374. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  9375. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  9376. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  9377. return result;
  9378. };
  9379. SubMesh.prototype.dispose = function () {
  9380. if (this._linesIndexBuffer) {
  9381. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  9382. this._linesIndexBuffer = null;
  9383. }
  9384. var index = this._mesh.subMeshes.indexOf(this);
  9385. this._mesh.subMeshes.splice(index, 1);
  9386. };
  9387. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  9388. var minVertexIndex = Number.MAX_VALUE;
  9389. var maxVertexIndex = -Number.MAX_VALUE;
  9390. renderingMesh = renderingMesh || mesh;
  9391. var indices = renderingMesh.getIndices();
  9392. for (var index = startIndex; index < startIndex + indexCount; index++) {
  9393. var vertexIndex = indices[index];
  9394. if (vertexIndex < minVertexIndex)
  9395. minVertexIndex = vertexIndex;
  9396. if (vertexIndex > maxVertexIndex)
  9397. maxVertexIndex = vertexIndex;
  9398. }
  9399. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  9400. };
  9401. return SubMesh;
  9402. })();
  9403. BABYLON.SubMesh = SubMesh;
  9404. })(BABYLON || (BABYLON = {}));
  9405. var BABYLON;
  9406. (function (BABYLON) {
  9407. var BaseTexture = (function () {
  9408. function BaseTexture(scene) {
  9409. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9410. this.hasAlpha = false;
  9411. this.getAlphaFromRGB = false;
  9412. this.level = 1;
  9413. this.isCube = false;
  9414. this.isRenderTarget = false;
  9415. this.animations = new Array();
  9416. this.coordinatesIndex = 0;
  9417. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  9418. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  9419. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  9420. this.anisotropicFilteringLevel = 4;
  9421. this._scene = scene;
  9422. this._scene.textures.push(this);
  9423. }
  9424. BaseTexture.prototype.getScene = function () {
  9425. return this._scene;
  9426. };
  9427. BaseTexture.prototype.getTextureMatrix = function () {
  9428. return null;
  9429. };
  9430. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  9431. return null;
  9432. };
  9433. BaseTexture.prototype.getInternalTexture = function () {
  9434. return this._texture;
  9435. };
  9436. BaseTexture.prototype.isReady = function () {
  9437. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9438. return true;
  9439. }
  9440. if (this._texture) {
  9441. return this._texture.isReady;
  9442. }
  9443. return false;
  9444. };
  9445. BaseTexture.prototype.getSize = function () {
  9446. if (this._texture._width) {
  9447. return { width: this._texture._width, height: this._texture._height };
  9448. }
  9449. if (this._texture._size) {
  9450. return { width: this._texture._size, height: this._texture._size };
  9451. }
  9452. return { width: 0, height: 0 };
  9453. };
  9454. BaseTexture.prototype.getBaseSize = function () {
  9455. if (!this.isReady())
  9456. return { width: 0, height: 0 };
  9457. if (this._texture._size) {
  9458. return { width: this._texture._size, height: this._texture._size };
  9459. }
  9460. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  9461. };
  9462. BaseTexture.prototype.scale = function (ratio) {
  9463. };
  9464. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  9465. get: function () {
  9466. return false;
  9467. },
  9468. enumerable: true,
  9469. configurable: true
  9470. });
  9471. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  9472. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9473. for (var index = 0; index < texturesCache.length; index++) {
  9474. var texturesCacheEntry = texturesCache[index];
  9475. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  9476. texturesCache.splice(index, 1);
  9477. return;
  9478. }
  9479. }
  9480. };
  9481. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  9482. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9483. for (var index = 0; index < texturesCache.length; index++) {
  9484. var texturesCacheEntry = texturesCache[index];
  9485. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  9486. texturesCacheEntry.references++;
  9487. return texturesCacheEntry;
  9488. }
  9489. }
  9490. return null;
  9491. };
  9492. BaseTexture.prototype.delayLoad = function () {
  9493. };
  9494. BaseTexture.prototype.releaseInternalTexture = function () {
  9495. if (!this._texture) {
  9496. return;
  9497. }
  9498. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9499. this._texture.references--;
  9500. if (this._texture.references == 0) {
  9501. var index = texturesCache.indexOf(this._texture);
  9502. texturesCache.splice(index, 1);
  9503. this._scene.getEngine()._releaseTexture(this._texture);
  9504. delete this._texture;
  9505. }
  9506. };
  9507. BaseTexture.prototype.clone = function () {
  9508. return null;
  9509. };
  9510. BaseTexture.prototype.dispose = function () {
  9511. var index = this._scene.textures.indexOf(this);
  9512. if (index >= 0) {
  9513. this._scene.textures.splice(index, 1);
  9514. }
  9515. if (this._texture === undefined) {
  9516. return;
  9517. }
  9518. this.releaseInternalTexture();
  9519. if (this.onDispose) {
  9520. this.onDispose();
  9521. }
  9522. };
  9523. return BaseTexture;
  9524. })();
  9525. BABYLON.BaseTexture = BaseTexture;
  9526. })(BABYLON || (BABYLON = {}));
  9527. var BABYLON;
  9528. (function (BABYLON) {
  9529. var RenderingGroup = (function () {
  9530. function RenderingGroup(index, scene) {
  9531. this.index = index;
  9532. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  9533. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  9534. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  9535. this._scene = scene;
  9536. }
  9537. RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
  9538. if (customRenderFunction) {
  9539. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
  9540. return true;
  9541. }
  9542. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  9543. return false;
  9544. }
  9545. var engine = this._scene.getEngine();
  9546. var subIndex;
  9547. var submesh;
  9548. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  9549. submesh = this._opaqueSubMeshes.data[subIndex];
  9550. this._activeVertices += submesh.verticesCount;
  9551. submesh.render();
  9552. }
  9553. engine.setAlphaTesting(true);
  9554. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  9555. submesh = this._alphaTestSubMeshes.data[subIndex];
  9556. this._activeVertices += submesh.verticesCount;
  9557. submesh.render();
  9558. }
  9559. engine.setAlphaTesting(false);
  9560. if (beforeTransparents) {
  9561. beforeTransparents();
  9562. }
  9563. if (this._transparentSubMeshes.length) {
  9564. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  9565. submesh = this._transparentSubMeshes.data[subIndex];
  9566. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  9567. }
  9568. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  9569. sortedArray.sort(function (a, b) {
  9570. if (a._distanceToCamera < b._distanceToCamera) {
  9571. return 1;
  9572. }
  9573. if (a._distanceToCamera > b._distanceToCamera) {
  9574. return -1;
  9575. }
  9576. return 0;
  9577. });
  9578. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9579. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  9580. submesh = sortedArray[subIndex];
  9581. this._activeVertices += submesh.verticesCount;
  9582. submesh.render();
  9583. }
  9584. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  9585. }
  9586. return true;
  9587. };
  9588. RenderingGroup.prototype.prepare = function () {
  9589. this._opaqueSubMeshes.reset();
  9590. this._transparentSubMeshes.reset();
  9591. this._alphaTestSubMeshes.reset();
  9592. };
  9593. RenderingGroup.prototype.dispatch = function (subMesh) {
  9594. var material = subMesh.getMaterial();
  9595. var mesh = subMesh.getMesh();
  9596. if (material.needAlphaBlending() || mesh.visibility < 1.0) {
  9597. if (material.alpha > 0 || mesh.visibility < 1.0) {
  9598. this._transparentSubMeshes.push(subMesh);
  9599. }
  9600. } else if (material.needAlphaTesting()) {
  9601. this._alphaTestSubMeshes.push(subMesh);
  9602. } else {
  9603. this._opaqueSubMeshes.push(subMesh);
  9604. }
  9605. };
  9606. return RenderingGroup;
  9607. })();
  9608. BABYLON.RenderingGroup = RenderingGroup;
  9609. })(BABYLON || (BABYLON = {}));
  9610. var BABYLON;
  9611. (function (BABYLON) {
  9612. var RenderingManager = (function () {
  9613. function RenderingManager(scene) {
  9614. this._renderingGroups = new Array();
  9615. this._scene = scene;
  9616. }
  9617. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  9618. if (this._scene._activeParticleSystems.length === 0) {
  9619. return;
  9620. }
  9621. var beforeParticlesDate = BABYLON.Tools.Now;
  9622. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  9623. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  9624. if (particleSystem.renderingGroupId !== index) {
  9625. continue;
  9626. }
  9627. this._clearDepthBuffer();
  9628. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  9629. this._scene._activeParticles += particleSystem.render();
  9630. }
  9631. }
  9632. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  9633. };
  9634. RenderingManager.prototype._renderSprites = function (index) {
  9635. if (this._scene.spriteManagers.length === 0) {
  9636. return;
  9637. }
  9638. var beforeSpritessDate = BABYLON.Tools.Now;
  9639. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  9640. var spriteManager = this._scene.spriteManagers[id];
  9641. if (spriteManager.renderingGroupId === index) {
  9642. this._clearDepthBuffer();
  9643. spriteManager.render();
  9644. }
  9645. }
  9646. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  9647. };
  9648. RenderingManager.prototype._clearDepthBuffer = function () {
  9649. if (this._depthBufferAlreadyCleaned) {
  9650. return;
  9651. }
  9652. this._scene.getEngine().clear(0, false, true);
  9653. this._depthBufferAlreadyCleaned = true;
  9654. };
  9655. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  9656. var _this = this;
  9657. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  9658. this._depthBufferAlreadyCleaned = false;
  9659. var renderingGroup = this._renderingGroups[index];
  9660. if (renderingGroup) {
  9661. this._clearDepthBuffer();
  9662. if (!renderingGroup.render(customRenderFunction, function () {
  9663. if (renderSprites) {
  9664. _this._renderSprites(index);
  9665. }
  9666. })) {
  9667. this._renderingGroups.splice(index, 1);
  9668. }
  9669. } else if (renderSprites) {
  9670. this._renderSprites(index);
  9671. }
  9672. if (renderParticles) {
  9673. this._renderParticles(index, activeMeshes);
  9674. }
  9675. }
  9676. };
  9677. RenderingManager.prototype.reset = function () {
  9678. for (var index in this._renderingGroups) {
  9679. var renderingGroup = this._renderingGroups[index];
  9680. renderingGroup.prepare();
  9681. }
  9682. };
  9683. RenderingManager.prototype.dispatch = function (subMesh) {
  9684. var mesh = subMesh.getMesh();
  9685. var renderingGroupId = mesh.renderingGroupId || 0;
  9686. if (!this._renderingGroups[renderingGroupId]) {
  9687. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  9688. }
  9689. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  9690. };
  9691. RenderingManager.MAX_RENDERINGGROUPS = 4;
  9692. return RenderingManager;
  9693. })();
  9694. BABYLON.RenderingManager = RenderingManager;
  9695. })(BABYLON || (BABYLON = {}));
  9696. var __extends = this.__extends || function (d, b) {
  9697. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9698. function __() { this.constructor = d; }
  9699. __.prototype = b.prototype;
  9700. d.prototype = new __();
  9701. };
  9702. var BABYLON;
  9703. (function (BABYLON) {
  9704. var Texture = (function (_super) {
  9705. __extends(Texture, _super);
  9706. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  9707. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  9708. if (typeof onLoad === "undefined") { onLoad = null; }
  9709. if (typeof onError === "undefined") { onError = null; }
  9710. if (typeof buffer === "undefined") { buffer = null; }
  9711. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  9712. _super.call(this, scene);
  9713. this.uOffset = 0;
  9714. this.vOffset = 0;
  9715. this.uScale = 1.0;
  9716. this.vScale = 1.0;
  9717. this.uAng = 0;
  9718. this.vAng = 0;
  9719. this.wAng = 0;
  9720. this.name = url;
  9721. this.url = url;
  9722. this._noMipmap = noMipmap;
  9723. this._invertY = invertY;
  9724. this._samplingMode = samplingMode;
  9725. this._buffer = buffer;
  9726. this._deleteBuffer = deleteBuffer;
  9727. if (!url) {
  9728. return;
  9729. }
  9730. this._texture = this._getFromCache(url, noMipmap);
  9731. if (!this._texture) {
  9732. if (!scene.useDelayedTextureLoading) {
  9733. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  9734. if (deleteBuffer) {
  9735. delete this._buffer;
  9736. }
  9737. } else {
  9738. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9739. }
  9740. }
  9741. }
  9742. Texture.prototype.delayLoad = function () {
  9743. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9744. return;
  9745. }
  9746. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9747. this._texture = this._getFromCache(this.url, this._noMipmap);
  9748. if (!this._texture) {
  9749. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  9750. if (this._deleteBuffer) {
  9751. delete this._buffer;
  9752. }
  9753. }
  9754. };
  9755. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  9756. x -= this.uOffset + 0.5;
  9757. y -= this.vOffset + 0.5;
  9758. z -= 0.5;
  9759. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  9760. t.x *= this.uScale;
  9761. t.y *= this.vScale;
  9762. t.x += 0.5;
  9763. t.y += 0.5;
  9764. t.z += 0.5;
  9765. };
  9766. Texture.prototype.getTextureMatrix = function () {
  9767. 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) {
  9768. return this._cachedTextureMatrix;
  9769. }
  9770. this._cachedUOffset = this.uOffset;
  9771. this._cachedVOffset = this.vOffset;
  9772. this._cachedUScale = this.uScale;
  9773. this._cachedVScale = this.vScale;
  9774. this._cachedUAng = this.uAng;
  9775. this._cachedVAng = this.vAng;
  9776. this._cachedWAng = this.wAng;
  9777. if (!this._cachedTextureMatrix) {
  9778. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9779. this._rowGenerationMatrix = new BABYLON.Matrix();
  9780. this._t0 = BABYLON.Vector3.Zero();
  9781. this._t1 = BABYLON.Vector3.Zero();
  9782. this._t2 = BABYLON.Vector3.Zero();
  9783. }
  9784. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  9785. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  9786. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  9787. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  9788. this._t1.subtractInPlace(this._t0);
  9789. this._t2.subtractInPlace(this._t0);
  9790. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9791. this._cachedTextureMatrix.m[0] = this._t1.x;
  9792. this._cachedTextureMatrix.m[1] = this._t1.y;
  9793. this._cachedTextureMatrix.m[2] = this._t1.z;
  9794. this._cachedTextureMatrix.m[4] = this._t2.x;
  9795. this._cachedTextureMatrix.m[5] = this._t2.y;
  9796. this._cachedTextureMatrix.m[6] = this._t2.z;
  9797. this._cachedTextureMatrix.m[8] = this._t0.x;
  9798. this._cachedTextureMatrix.m[9] = this._t0.y;
  9799. this._cachedTextureMatrix.m[10] = this._t0.z;
  9800. return this._cachedTextureMatrix;
  9801. };
  9802. Texture.prototype.getReflectionTextureMatrix = function () {
  9803. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  9804. return this._cachedTextureMatrix;
  9805. }
  9806. if (!this._cachedTextureMatrix) {
  9807. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9808. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  9809. }
  9810. switch (this.coordinatesMode) {
  9811. case BABYLON.Texture.SPHERICAL_MODE:
  9812. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9813. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  9814. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  9815. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  9816. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  9817. break;
  9818. case BABYLON.Texture.PLANAR_MODE:
  9819. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9820. this._cachedTextureMatrix[0] = this.uScale;
  9821. this._cachedTextureMatrix[5] = this.vScale;
  9822. this._cachedTextureMatrix[12] = this.uOffset;
  9823. this._cachedTextureMatrix[13] = this.vOffset;
  9824. break;
  9825. case BABYLON.Texture.PROJECTION_MODE:
  9826. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  9827. this._projectionModeMatrix.m[0] = 0.5;
  9828. this._projectionModeMatrix.m[5] = -0.5;
  9829. this._projectionModeMatrix.m[10] = 0.0;
  9830. this._projectionModeMatrix.m[12] = 0.5;
  9831. this._projectionModeMatrix.m[13] = 0.5;
  9832. this._projectionModeMatrix.m[14] = 1.0;
  9833. this._projectionModeMatrix.m[15] = 1.0;
  9834. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  9835. break;
  9836. default:
  9837. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9838. break;
  9839. }
  9840. return this._cachedTextureMatrix;
  9841. };
  9842. Texture.prototype.clone = function () {
  9843. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  9844. newTexture.hasAlpha = this.hasAlpha;
  9845. newTexture.level = this.level;
  9846. newTexture.wrapU = this.wrapU;
  9847. newTexture.wrapV = this.wrapV;
  9848. newTexture.coordinatesIndex = this.coordinatesIndex;
  9849. newTexture.coordinatesMode = this.coordinatesMode;
  9850. newTexture.uOffset = this.uOffset;
  9851. newTexture.vOffset = this.vOffset;
  9852. newTexture.uScale = this.uScale;
  9853. newTexture.vScale = this.vScale;
  9854. newTexture.uAng = this.uAng;
  9855. newTexture.vAng = this.vAng;
  9856. newTexture.wAng = this.wAng;
  9857. return newTexture;
  9858. };
  9859. Texture.NEAREST_SAMPLINGMODE = 1;
  9860. Texture.BILINEAR_SAMPLINGMODE = 2;
  9861. Texture.TRILINEAR_SAMPLINGMODE = 3;
  9862. Texture.EXPLICIT_MODE = 0;
  9863. Texture.SPHERICAL_MODE = 1;
  9864. Texture.PLANAR_MODE = 2;
  9865. Texture.CUBIC_MODE = 3;
  9866. Texture.PROJECTION_MODE = 4;
  9867. Texture.SKYBOX_MODE = 5;
  9868. Texture.CLAMP_ADDRESSMODE = 0;
  9869. Texture.WRAP_ADDRESSMODE = 1;
  9870. Texture.MIRROR_ADDRESSMODE = 2;
  9871. return Texture;
  9872. })(BABYLON.BaseTexture);
  9873. BABYLON.Texture = Texture;
  9874. })(BABYLON || (BABYLON = {}));
  9875. var __extends = this.__extends || function (d, b) {
  9876. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9877. function __() { this.constructor = d; }
  9878. __.prototype = b.prototype;
  9879. d.prototype = new __();
  9880. };
  9881. var BABYLON;
  9882. (function (BABYLON) {
  9883. var CubeTexture = (function (_super) {
  9884. __extends(CubeTexture, _super);
  9885. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  9886. _super.call(this, scene);
  9887. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  9888. this.name = rootUrl;
  9889. this.url = rootUrl;
  9890. this._noMipmap = noMipmap;
  9891. this.hasAlpha = false;
  9892. this._texture = this._getFromCache(rootUrl, noMipmap);
  9893. if (!extensions) {
  9894. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  9895. }
  9896. this._extensions = extensions;
  9897. if (!this._texture) {
  9898. if (!scene.useDelayedTextureLoading) {
  9899. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  9900. } else {
  9901. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9902. }
  9903. }
  9904. this.isCube = true;
  9905. this._textureMatrix = BABYLON.Matrix.Identity();
  9906. }
  9907. CubeTexture.prototype.clone = function () {
  9908. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  9909. newTexture.level = this.level;
  9910. newTexture.wrapU = this.wrapU;
  9911. newTexture.wrapV = this.wrapV;
  9912. newTexture.coordinatesIndex = this.coordinatesIndex;
  9913. newTexture.coordinatesMode = this.coordinatesMode;
  9914. return newTexture;
  9915. };
  9916. CubeTexture.prototype.delayLoad = function () {
  9917. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9918. return;
  9919. }
  9920. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9921. this._texture = this._getFromCache(this.url, this._noMipmap);
  9922. if (!this._texture) {
  9923. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  9924. }
  9925. };
  9926. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  9927. return this._textureMatrix;
  9928. };
  9929. return CubeTexture;
  9930. })(BABYLON.BaseTexture);
  9931. BABYLON.CubeTexture = CubeTexture;
  9932. })(BABYLON || (BABYLON = {}));
  9933. var __extends = this.__extends || function (d, b) {
  9934. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9935. function __() { this.constructor = d; }
  9936. __.prototype = b.prototype;
  9937. d.prototype = new __();
  9938. };
  9939. var BABYLON;
  9940. (function (BABYLON) {
  9941. var RenderTargetTexture = (function (_super) {
  9942. __extends(RenderTargetTexture, _super);
  9943. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  9944. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  9945. _super.call(this, null, scene, !generateMipMaps);
  9946. this.renderList = new Array();
  9947. this.renderParticles = true;
  9948. this.renderSprites = false;
  9949. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  9950. this._currentRefreshId = -1;
  9951. this._refreshRate = 1;
  9952. this.name = name;
  9953. this.isRenderTarget = true;
  9954. this._size = size;
  9955. this._generateMipMaps = generateMipMaps;
  9956. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  9957. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  9958. this._renderingManager = new BABYLON.RenderingManager(scene);
  9959. }
  9960. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  9961. this._currentRefreshId = -1;
  9962. };
  9963. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  9964. get: function () {
  9965. return this._refreshRate;
  9966. },
  9967. set: function (value) {
  9968. this._refreshRate = value;
  9969. this.resetRefreshCounter();
  9970. },
  9971. enumerable: true,
  9972. configurable: true
  9973. });
  9974. RenderTargetTexture.prototype._shouldRender = function () {
  9975. if (this._currentRefreshId === -1) {
  9976. this._currentRefreshId = 1;
  9977. return true;
  9978. }
  9979. if (this.refreshRate == this._currentRefreshId) {
  9980. this._currentRefreshId = 1;
  9981. return true;
  9982. }
  9983. this._currentRefreshId++;
  9984. return false;
  9985. };
  9986. RenderTargetTexture.prototype.isReady = function () {
  9987. if (!this.getScene().renderTargetsEnabled) {
  9988. return false;
  9989. }
  9990. return _super.prototype.isReady.call(this);
  9991. };
  9992. RenderTargetTexture.prototype.getRenderSize = function () {
  9993. return this._size;
  9994. };
  9995. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  9996. get: function () {
  9997. return true;
  9998. },
  9999. enumerable: true,
  10000. configurable: true
  10001. });
  10002. RenderTargetTexture.prototype.scale = function (ratio) {
  10003. var newSize = this._size * ratio;
  10004. this.resize(newSize, this._generateMipMaps);
  10005. };
  10006. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  10007. this.releaseInternalTexture();
  10008. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  10009. };
  10010. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  10011. var scene = this.getScene();
  10012. var engine = scene.getEngine();
  10013. if (this._waitingRenderList) {
  10014. this.renderList = [];
  10015. for (var index = 0; index < this._waitingRenderList.length; index++) {
  10016. var id = this._waitingRenderList[index];
  10017. this.renderList.push(scene.getMeshByID(id));
  10018. }
  10019. delete this._waitingRenderList;
  10020. }
  10021. if (!this.renderList) {
  10022. return;
  10023. }
  10024. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  10025. engine.bindFramebuffer(this._texture);
  10026. }
  10027. engine.clear(scene.clearColor, true, true);
  10028. this._renderingManager.reset();
  10029. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  10030. var mesh = this.renderList[meshIndex];
  10031. if (mesh) {
  10032. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  10033. this.resetRefreshCounter();
  10034. continue;
  10035. }
  10036. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  10037. mesh._activate(scene.getRenderId());
  10038. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  10039. var subMesh = mesh.subMeshes[subIndex];
  10040. scene._activeVertices += subMesh.verticesCount;
  10041. this._renderingManager.dispatch(subMesh);
  10042. }
  10043. }
  10044. }
  10045. }
  10046. if (!this._doNotChangeAspectRatio) {
  10047. scene.updateTransformMatrix(true);
  10048. }
  10049. if (this.onBeforeRender) {
  10050. this.onBeforeRender();
  10051. }
  10052. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  10053. if (useCameraPostProcess) {
  10054. scene.postProcessManager._finalizeFrame(false, this._texture);
  10055. }
  10056. if (this.onAfterRender) {
  10057. this.onAfterRender();
  10058. }
  10059. engine.unBindFramebuffer(this._texture);
  10060. if (!this._doNotChangeAspectRatio) {
  10061. scene.updateTransformMatrix(true);
  10062. }
  10063. };
  10064. RenderTargetTexture.prototype.clone = function () {
  10065. var textureSize = this.getSize();
  10066. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10067. newTexture.hasAlpha = this.hasAlpha;
  10068. newTexture.level = this.level;
  10069. newTexture.coordinatesMode = this.coordinatesMode;
  10070. newTexture.renderList = this.renderList.slice(0);
  10071. return newTexture;
  10072. };
  10073. return RenderTargetTexture;
  10074. })(BABYLON.Texture);
  10075. BABYLON.RenderTargetTexture = RenderTargetTexture;
  10076. })(BABYLON || (BABYLON = {}));
  10077. var __extends = this.__extends || function (d, b) {
  10078. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10079. function __() { this.constructor = d; }
  10080. __.prototype = b.prototype;
  10081. d.prototype = new __();
  10082. };
  10083. var BABYLON;
  10084. (function (BABYLON) {
  10085. var ProceduralTexture = (function (_super) {
  10086. __extends(ProceduralTexture, _super);
  10087. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  10088. _super.call(this, null, scene, !generateMipMaps);
  10089. this._currentRefreshId = -1;
  10090. this._refreshRate = 1;
  10091. this._vertexDeclaration = [2];
  10092. this._vertexStrideSize = 2 * 4;
  10093. this._uniforms = new Array();
  10094. this._samplers = new Array();
  10095. this._textures = new Array();
  10096. this._floats = new Array();
  10097. this._floatsArrays = {};
  10098. this._colors3 = new Array();
  10099. this._colors4 = new Array();
  10100. this._vectors2 = new Array();
  10101. this._vectors3 = new Array();
  10102. this._matrices = new Array();
  10103. scene._proceduralTextures.push(this);
  10104. this.name = name;
  10105. this.isRenderTarget = true;
  10106. this._size = size;
  10107. this._generateMipMaps = generateMipMaps;
  10108. this._fragment = fragment;
  10109. this._fallbackTexture = fallbackTexture;
  10110. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  10111. var vertices = [];
  10112. vertices.push(1, 1);
  10113. vertices.push(-1, 1);
  10114. vertices.push(-1, -1);
  10115. vertices.push(1, -1);
  10116. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  10117. var indices = [];
  10118. indices.push(0);
  10119. indices.push(1);
  10120. indices.push(2);
  10121. indices.push(0);
  10122. indices.push(2);
  10123. indices.push(3);
  10124. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  10125. }
  10126. ProceduralTexture.prototype.isReady = function () {
  10127. var _this = this;
  10128. var engine = this.getScene().getEngine();
  10129. this._effect = engine.createEffect({ vertex: "procedural", fragment: this._fragment }, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  10130. _this.releaseInternalTexture();
  10131. _this._texture = _this._fallbackTexture._texture;
  10132. _this._texture.references++;
  10133. });
  10134. return this._effect.isReady();
  10135. };
  10136. ProceduralTexture.prototype.resetRefreshCounter = function () {
  10137. this._currentRefreshId = -1;
  10138. };
  10139. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  10140. get: function () {
  10141. return this._refreshRate;
  10142. },
  10143. set: function (value) {
  10144. this._refreshRate = value;
  10145. this.resetRefreshCounter();
  10146. },
  10147. enumerable: true,
  10148. configurable: true
  10149. });
  10150. ProceduralTexture.prototype._shouldRender = function () {
  10151. if (!this.isReady() || !this._texture) {
  10152. return false;
  10153. }
  10154. if (this._currentRefreshId === -1) {
  10155. this._currentRefreshId = 1;
  10156. return true;
  10157. }
  10158. if (this.refreshRate == this._currentRefreshId) {
  10159. this._currentRefreshId = 1;
  10160. return true;
  10161. }
  10162. this._currentRefreshId++;
  10163. return false;
  10164. };
  10165. ProceduralTexture.prototype.getRenderSize = function () {
  10166. return this._size;
  10167. };
  10168. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  10169. this.releaseInternalTexture();
  10170. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  10171. };
  10172. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  10173. if (this._uniforms.indexOf(uniformName) === -1) {
  10174. this._uniforms.push(uniformName);
  10175. }
  10176. };
  10177. ProceduralTexture.prototype.setTexture = function (name, texture) {
  10178. if (this._samplers.indexOf(name) === -1) {
  10179. this._samplers.push(name);
  10180. }
  10181. this._textures[name] = texture;
  10182. return this;
  10183. };
  10184. ProceduralTexture.prototype.setFloat = function (name, value) {
  10185. this._checkUniform(name);
  10186. this._floats[name] = value;
  10187. return this;
  10188. };
  10189. ProceduralTexture.prototype.setFloats = function (name, value) {
  10190. this._checkUniform(name);
  10191. this._floatsArrays[name] = value;
  10192. return this;
  10193. };
  10194. ProceduralTexture.prototype.setColor3 = function (name, value) {
  10195. this._checkUniform(name);
  10196. this._colors3[name] = value;
  10197. return this;
  10198. };
  10199. ProceduralTexture.prototype.setColor4 = function (name, value) {
  10200. this._checkUniform(name);
  10201. this._colors4[name] = value;
  10202. return this;
  10203. };
  10204. ProceduralTexture.prototype.setVector2 = function (name, value) {
  10205. this._checkUniform(name);
  10206. this._vectors2[name] = value;
  10207. return this;
  10208. };
  10209. ProceduralTexture.prototype.setVector3 = function (name, value) {
  10210. this._checkUniform(name);
  10211. this._vectors3[name] = value;
  10212. return this;
  10213. };
  10214. ProceduralTexture.prototype.setMatrix = function (name, value) {
  10215. this._checkUniform(name);
  10216. this._matrices[name] = value;
  10217. return this;
  10218. };
  10219. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  10220. var scene = this.getScene();
  10221. var engine = scene.getEngine();
  10222. engine.bindFramebuffer(this._texture);
  10223. engine.clear(scene.clearColor, true, true);
  10224. engine.enableEffect(this._effect);
  10225. engine.setState(false);
  10226. for (var name in this._textures) {
  10227. this._effect.setTexture(name, this._textures[name]);
  10228. }
  10229. for (name in this._floats) {
  10230. this._effect.setFloat(name, this._floats[name]);
  10231. }
  10232. for (name in this._floatsArrays) {
  10233. this._effect.setArray(name, this._floatsArrays[name]);
  10234. }
  10235. for (name in this._colors3) {
  10236. this._effect.setColor3(name, this._colors3[name]);
  10237. }
  10238. for (name in this._colors4) {
  10239. var color = this._colors4[name];
  10240. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  10241. }
  10242. for (name in this._vectors2) {
  10243. this._effect.setVector2(name, this._vectors2[name]);
  10244. }
  10245. for (name in this._vectors3) {
  10246. this._effect.setVector3(name, this._vectors3[name]);
  10247. }
  10248. for (name in this._matrices) {
  10249. this._effect.setMatrix(name, this._matrices[name]);
  10250. }
  10251. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  10252. engine.draw(true, 0, 6);
  10253. engine.unBindFramebuffer(this._texture);
  10254. };
  10255. ProceduralTexture.prototype.clone = function () {
  10256. var textureSize = this.getSize();
  10257. var newTexture = new BABYLON.ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  10258. newTexture.hasAlpha = this.hasAlpha;
  10259. newTexture.level = this.level;
  10260. newTexture.coordinatesMode = this.coordinatesMode;
  10261. return newTexture;
  10262. };
  10263. ProceduralTexture.prototype.dispose = function () {
  10264. var index = this.getScene()._proceduralTextures.indexOf(this);
  10265. if (index >= 0) {
  10266. this.getScene()._proceduralTextures.splice(index, 1);
  10267. }
  10268. _super.prototype.dispose.call(this);
  10269. };
  10270. return ProceduralTexture;
  10271. })(BABYLON.Texture);
  10272. BABYLON.ProceduralTexture = ProceduralTexture;
  10273. })(BABYLON || (BABYLON = {}));
  10274. var __extends = this.__extends || function (d, b) {
  10275. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10276. function __() { this.constructor = d; }
  10277. __.prototype = b.prototype;
  10278. d.prototype = new __();
  10279. };
  10280. var BABYLON;
  10281. (function (BABYLON) {
  10282. var WoodProceduralTexture = (function (_super) {
  10283. __extends(WoodProceduralTexture, _super);
  10284. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10285. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  10286. this._ampScale = 0.03;
  10287. this._ringScale = 5;
  10288. this._woodColor1 = new BABYLON.Color3(0.80, 0.55, 0.01);
  10289. this._woodColor2 = new BABYLON.Color3(0.60, 0.41, 0.0);
  10290. this.updateShaderUniforms();
  10291. this.refreshRate = 0;
  10292. }
  10293. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  10294. this.setFloat("ampScale", this._ampScale);
  10295. this.setFloat("ringScale", this._ringScale);
  10296. this.setColor3("woodColor1", this._woodColor1);
  10297. this.setColor3("woodColor2", this._woodColor2);
  10298. };
  10299. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  10300. get: function () {
  10301. return this._ampScale;
  10302. },
  10303. set: function (value) {
  10304. this._ampScale = value;
  10305. this.updateShaderUniforms();
  10306. },
  10307. enumerable: true,
  10308. configurable: true
  10309. });
  10310. Object.defineProperty(WoodProceduralTexture.prototype, "ringScale", {
  10311. get: function () {
  10312. return this._ringScale;
  10313. },
  10314. set: function (value) {
  10315. this._ringScale = value;
  10316. this.updateShaderUniforms();
  10317. },
  10318. enumerable: true,
  10319. configurable: true
  10320. });
  10321. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor1", {
  10322. get: function () {
  10323. return this._woodColor1;
  10324. },
  10325. set: function (value) {
  10326. this._woodColor1 = value;
  10327. this.updateShaderUniforms();
  10328. },
  10329. enumerable: true,
  10330. configurable: true
  10331. });
  10332. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor2", {
  10333. get: function () {
  10334. return this._woodColor2;
  10335. },
  10336. set: function (value) {
  10337. this._woodColor2 = value;
  10338. this.updateShaderUniforms();
  10339. },
  10340. enumerable: true,
  10341. configurable: true
  10342. });
  10343. return WoodProceduralTexture;
  10344. })(BABYLON.ProceduralTexture);
  10345. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  10346. var FireProceduralTexture = (function (_super) {
  10347. __extends(FireProceduralTexture, _super);
  10348. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10349. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  10350. this._time = 0.0;
  10351. this._speed = new BABYLON.Vector2(0.5, 0.3);
  10352. this._shift = 1.6;
  10353. this._alpha = 1.0;
  10354. this._autoGenerateTime = true;
  10355. this._fireColors = FireProceduralTexture.RedFireColors;
  10356. this.updateShaderUniforms();
  10357. this.refreshRate = 1;
  10358. }
  10359. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  10360. this.setFloat("iGlobalTime", this._time);
  10361. this.setVector2("speed", this._speed);
  10362. this.setFloat("shift", this._shift);
  10363. this.setFloat("alpha", this._alpha);
  10364. this.setColor3("c1", new BABYLON.Color3(this._fireColors[0][0], this._fireColors[0][1], this._fireColors[0][2]));
  10365. this.setColor3("c2", new BABYLON.Color3(this._fireColors[1][0], this._fireColors[1][1], this._fireColors[1][2]));
  10366. this.setColor3("c3", new BABYLON.Color3(this._fireColors[2][0], this._fireColors[2][1], this._fireColors[2][2]));
  10367. this.setColor3("c4", new BABYLON.Color3(this._fireColors[3][0], this._fireColors[3][1], this._fireColors[3][2]));
  10368. this.setColor3("c5", new BABYLON.Color3(this._fireColors[4][0], this._fireColors[4][1], this._fireColors[4][2]));
  10369. this.setColor3("c6", new BABYLON.Color3(this._fireColors[5][0], this._fireColors[5][1], this._fireColors[5][2]));
  10370. };
  10371. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  10372. if (this._autoGenerateTime) {
  10373. this._time += this.getScene().getAnimationRatio() * 0.03;
  10374. this.updateShaderUniforms();
  10375. }
  10376. _super.prototype.render.call(this, useCameraPostProcess);
  10377. };
  10378. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  10379. get: function () {
  10380. return [
  10381. [0.5, 0.0, 1.0],
  10382. [0.9, 0.0, 1.0],
  10383. [0.2, 0.0, 1.0],
  10384. [1.0, 0.9, 1.0],
  10385. [0.1, 0.1, 1.0],
  10386. [0.9, 0.9, 1.0]
  10387. ];
  10388. },
  10389. enumerable: true,
  10390. configurable: true
  10391. });
  10392. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  10393. get: function () {
  10394. return [
  10395. [0.5, 1.0, 0.0],
  10396. [0.5, 1.0, 0.0],
  10397. [0.3, 0.4, 0.0],
  10398. [0.5, 1.0, 0.0],
  10399. [0.2, 0.0, 0.0],
  10400. [0.5, 1.0, 0.0]
  10401. ];
  10402. },
  10403. enumerable: true,
  10404. configurable: true
  10405. });
  10406. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  10407. get: function () {
  10408. return [
  10409. [0.5, 0.0, 0.1],
  10410. [0.9, 0.0, 0.0],
  10411. [0.2, 0.0, 0.0],
  10412. [1.0, 0.9, 0.0],
  10413. [0.1, 0.1, 0.1],
  10414. [0.9, 0.9, 0.9]
  10415. ];
  10416. },
  10417. enumerable: true,
  10418. configurable: true
  10419. });
  10420. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  10421. get: function () {
  10422. return [
  10423. [0.1, 0.0, 0.5],
  10424. [0.0, 0.0, 0.5],
  10425. [0.1, 0.0, 0.2],
  10426. [0.0, 0.0, 1.0],
  10427. [0.1, 0.2, 0.3],
  10428. [0.0, 0.2, 0.9]
  10429. ];
  10430. },
  10431. enumerable: true,
  10432. configurable: true
  10433. });
  10434. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  10435. get: function () {
  10436. return this._fireColors;
  10437. },
  10438. set: function (value) {
  10439. this._fireColors = value;
  10440. this.updateShaderUniforms();
  10441. },
  10442. enumerable: true,
  10443. configurable: true
  10444. });
  10445. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  10446. get: function () {
  10447. return this._time;
  10448. },
  10449. set: function (value) {
  10450. this._time = value;
  10451. this.updateShaderUniforms();
  10452. },
  10453. enumerable: true,
  10454. configurable: true
  10455. });
  10456. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  10457. get: function () {
  10458. return this._speed;
  10459. },
  10460. set: function (value) {
  10461. this._speed = value;
  10462. this.updateShaderUniforms();
  10463. },
  10464. enumerable: true,
  10465. configurable: true
  10466. });
  10467. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  10468. get: function () {
  10469. return this._shift;
  10470. },
  10471. set: function (value) {
  10472. this._shift = value;
  10473. this.updateShaderUniforms();
  10474. },
  10475. enumerable: true,
  10476. configurable: true
  10477. });
  10478. Object.defineProperty(FireProceduralTexture.prototype, "alpha", {
  10479. get: function () {
  10480. return this._alpha;
  10481. },
  10482. set: function (value) {
  10483. this._alpha = value;
  10484. this.updateShaderUniforms();
  10485. },
  10486. enumerable: true,
  10487. configurable: true
  10488. });
  10489. return FireProceduralTexture;
  10490. })(BABYLON.ProceduralTexture);
  10491. BABYLON.FireProceduralTexture = FireProceduralTexture;
  10492. var CloudProceduralTexture = (function (_super) {
  10493. __extends(CloudProceduralTexture, _super);
  10494. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10495. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  10496. this.refreshRate = 0;
  10497. }
  10498. return CloudProceduralTexture;
  10499. })(BABYLON.ProceduralTexture);
  10500. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  10501. })(BABYLON || (BABYLON = {}));
  10502. var __extends = this.__extends || function (d, b) {
  10503. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10504. function __() { this.constructor = d; }
  10505. __.prototype = b.prototype;
  10506. d.prototype = new __();
  10507. };
  10508. var BABYLON;
  10509. (function (BABYLON) {
  10510. var MirrorTexture = (function (_super) {
  10511. __extends(MirrorTexture, _super);
  10512. function MirrorTexture(name, size, scene, generateMipMaps) {
  10513. var _this = this;
  10514. _super.call(this, name, size, scene, generateMipMaps, true);
  10515. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  10516. this._transformMatrix = BABYLON.Matrix.Zero();
  10517. this._mirrorMatrix = BABYLON.Matrix.Zero();
  10518. this.onBeforeRender = function () {
  10519. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  10520. _this._savedViewMatrix = scene.getViewMatrix();
  10521. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  10522. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  10523. scene.clipPlane = _this.mirrorPlane;
  10524. scene.getEngine().cullBackFaces = false;
  10525. };
  10526. this.onAfterRender = function () {
  10527. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  10528. scene.getEngine().cullBackFaces = true;
  10529. delete scene.clipPlane;
  10530. };
  10531. }
  10532. MirrorTexture.prototype.clone = function () {
  10533. var textureSize = this.getSize();
  10534. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10535. newTexture.hasAlpha = this.hasAlpha;
  10536. newTexture.level = this.level;
  10537. newTexture.mirrorPlane = this.mirrorPlane.clone();
  10538. newTexture.renderList = this.renderList.slice(0);
  10539. return newTexture;
  10540. };
  10541. return MirrorTexture;
  10542. })(BABYLON.RenderTargetTexture);
  10543. BABYLON.MirrorTexture = MirrorTexture;
  10544. })(BABYLON || (BABYLON = {}));
  10545. var __extends = this.__extends || function (d, b) {
  10546. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10547. function __() { this.constructor = d; }
  10548. __.prototype = b.prototype;
  10549. d.prototype = new __();
  10550. };
  10551. var BABYLON;
  10552. (function (BABYLON) {
  10553. var DynamicTexture = (function (_super) {
  10554. __extends(DynamicTexture, _super);
  10555. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  10556. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10557. _super.call(this, null, scene, !generateMipMaps);
  10558. this.name = name;
  10559. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10560. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10561. this._generateMipMaps = generateMipMaps;
  10562. if (options.getContext) {
  10563. this._canvas = options;
  10564. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  10565. } else {
  10566. this._canvas = document.createElement("canvas");
  10567. if (options.width) {
  10568. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  10569. } else {
  10570. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  10571. }
  10572. }
  10573. var textureSize = this.getSize();
  10574. this._canvas.width = textureSize.width;
  10575. this._canvas.height = textureSize.height;
  10576. this._context = this._canvas.getContext("2d");
  10577. }
  10578. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  10579. get: function () {
  10580. return true;
  10581. },
  10582. enumerable: true,
  10583. configurable: true
  10584. });
  10585. DynamicTexture.prototype.scale = function (ratio) {
  10586. var textureSize = this.getSize();
  10587. textureSize.width *= ratio;
  10588. textureSize.height *= ratio;
  10589. this._canvas.width = textureSize.width;
  10590. this._canvas.height = textureSize.height;
  10591. this.releaseInternalTexture();
  10592. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  10593. };
  10594. DynamicTexture.prototype.getContext = function () {
  10595. return this._context;
  10596. };
  10597. DynamicTexture.prototype.update = function (invertY) {
  10598. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  10599. };
  10600. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  10601. var size = this.getSize();
  10602. if (clearColor) {
  10603. this._context.fillStyle = clearColor;
  10604. this._context.fillRect(0, 0, size.width, size.height);
  10605. }
  10606. this._context.font = font;
  10607. if (x === null) {
  10608. var textSize = this._context.measureText(text);
  10609. x = (size.width - textSize.width) / 2;
  10610. }
  10611. this._context.fillStyle = color;
  10612. this._context.fillText(text, x, y);
  10613. this.update(invertY);
  10614. };
  10615. DynamicTexture.prototype.clone = function () {
  10616. var textureSize = this.getSize();
  10617. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10618. newTexture.hasAlpha = this.hasAlpha;
  10619. newTexture.level = this.level;
  10620. newTexture.wrapU = this.wrapU;
  10621. newTexture.wrapV = this.wrapV;
  10622. return newTexture;
  10623. };
  10624. return DynamicTexture;
  10625. })(BABYLON.Texture);
  10626. BABYLON.DynamicTexture = DynamicTexture;
  10627. })(BABYLON || (BABYLON = {}));
  10628. var __extends = this.__extends || function (d, b) {
  10629. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10630. function __() { this.constructor = d; }
  10631. __.prototype = b.prototype;
  10632. d.prototype = new __();
  10633. };
  10634. var BABYLON;
  10635. (function (BABYLON) {
  10636. var VideoTexture = (function (_super) {
  10637. __extends(VideoTexture, _super);
  10638. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  10639. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10640. var _this = this;
  10641. _super.call(this, null, scene, !generateMipMaps, invertY);
  10642. this._autoLaunch = true;
  10643. this.name = name;
  10644. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  10645. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  10646. var requiredWidth = size.width || size;
  10647. var requiredHeight = size.height || size;
  10648. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  10649. var textureSize = this.getSize();
  10650. this.video = document.createElement("video");
  10651. this.video.width = textureSize.width;
  10652. this.video.height = textureSize.height;
  10653. this.video.autoplay = false;
  10654. this.video.loop = true;
  10655. this.video.addEventListener("canplaythrough", function () {
  10656. if (_this._texture) {
  10657. _this._texture.isReady = true;
  10658. }
  10659. });
  10660. urls.forEach(function (url) {
  10661. var source = document.createElement("source");
  10662. source.src = url;
  10663. _this.video.appendChild(source);
  10664. });
  10665. this._lastUpdate = BABYLON.Tools.Now;
  10666. }
  10667. VideoTexture.prototype.update = function () {
  10668. if (this._autoLaunch) {
  10669. this._autoLaunch = false;
  10670. this.video.play();
  10671. }
  10672. var now = BABYLON.Tools.Now;
  10673. if (now - this._lastUpdate < 15) {
  10674. return false;
  10675. }
  10676. this._lastUpdate = now;
  10677. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  10678. return true;
  10679. };
  10680. return VideoTexture;
  10681. })(BABYLON.Texture);
  10682. BABYLON.VideoTexture = VideoTexture;
  10683. })(BABYLON || (BABYLON = {}));
  10684. var BABYLON;
  10685. (function (BABYLON) {
  10686. var EffectFallbacks = (function () {
  10687. function EffectFallbacks() {
  10688. this._defines = {};
  10689. this._currentRank = 32;
  10690. this._maxRank = -1;
  10691. }
  10692. EffectFallbacks.prototype.addFallback = function (rank, define) {
  10693. if (!this._defines[rank]) {
  10694. if (rank < this._currentRank) {
  10695. this._currentRank = rank;
  10696. }
  10697. if (rank > this._maxRank) {
  10698. this._maxRank = rank;
  10699. }
  10700. this._defines[rank] = new Array();
  10701. }
  10702. this._defines[rank].push(define);
  10703. };
  10704. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  10705. get: function () {
  10706. return this._currentRank <= this._maxRank;
  10707. },
  10708. enumerable: true,
  10709. configurable: true
  10710. });
  10711. EffectFallbacks.prototype.reduce = function (currentDefines) {
  10712. var currentFallbacks = this._defines[this._currentRank];
  10713. for (var index = 0; index < currentFallbacks.length; index++) {
  10714. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  10715. }
  10716. this._currentRank++;
  10717. return currentDefines;
  10718. };
  10719. return EffectFallbacks;
  10720. })();
  10721. BABYLON.EffectFallbacks = EffectFallbacks;
  10722. var Effect = (function () {
  10723. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  10724. var _this = this;
  10725. this._isReady = false;
  10726. this._compilationError = "";
  10727. this._valueCache = [];
  10728. this._engine = engine;
  10729. this.name = baseName;
  10730. this.defines = defines;
  10731. this._uniformsNames = uniformsNames.concat(samplers);
  10732. this._samplers = samplers;
  10733. this._attributesNames = attributesNames;
  10734. this.onError = onError;
  10735. this.onCompiled = onCompiled;
  10736. var vertexSource;
  10737. var fragmentSource;
  10738. if (baseName.vertexElement) {
  10739. vertexSource = document.getElementById(baseName.vertexElement);
  10740. if (!vertexSource) {
  10741. vertexSource = baseName.vertexElement;
  10742. }
  10743. } else {
  10744. vertexSource = baseName.vertex || baseName;
  10745. }
  10746. if (baseName.fragmentElement) {
  10747. fragmentSource = document.getElementById(baseName.fragmentElement);
  10748. if (!fragmentSource) {
  10749. fragmentSource = baseName.fragmentElement;
  10750. }
  10751. } else {
  10752. fragmentSource = baseName.fragment || baseName;
  10753. }
  10754. this._loadVertexShader(vertexSource, function (vertexCode) {
  10755. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  10756. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  10757. });
  10758. });
  10759. }
  10760. Effect.prototype.isReady = function () {
  10761. return this._isReady;
  10762. };
  10763. Effect.prototype.getProgram = function () {
  10764. return this._program;
  10765. };
  10766. Effect.prototype.getAttributesNames = function () {
  10767. return this._attributesNames;
  10768. };
  10769. Effect.prototype.getAttributeLocation = function (index) {
  10770. return this._attributes[index];
  10771. };
  10772. Effect.prototype.getAttributeLocationByName = function (name) {
  10773. var index = this._attributesNames.indexOf(name);
  10774. return this._attributes[index];
  10775. };
  10776. Effect.prototype.getAttributesCount = function () {
  10777. return this._attributes.length;
  10778. };
  10779. Effect.prototype.getUniformIndex = function (uniformName) {
  10780. return this._uniformsNames.indexOf(uniformName);
  10781. };
  10782. Effect.prototype.getUniform = function (uniformName) {
  10783. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  10784. };
  10785. Effect.prototype.getSamplers = function () {
  10786. return this._samplers;
  10787. };
  10788. Effect.prototype.getCompilationError = function () {
  10789. return this._compilationError;
  10790. };
  10791. Effect.prototype._loadVertexShader = function (vertex, callback) {
  10792. if (vertex instanceof HTMLElement) {
  10793. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  10794. callback(vertexCode);
  10795. return;
  10796. }
  10797. if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
  10798. callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
  10799. return;
  10800. }
  10801. var vertexShaderUrl;
  10802. if (vertex[0] === ".") {
  10803. vertexShaderUrl = vertex;
  10804. } else {
  10805. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  10806. }
  10807. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  10808. };
  10809. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  10810. if (fragment instanceof HTMLElement) {
  10811. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  10812. callback(fragmentCode);
  10813. return;
  10814. }
  10815. if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
  10816. callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
  10817. return;
  10818. }
  10819. if (BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]) {
  10820. callback(BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]);
  10821. return;
  10822. }
  10823. var fragmentShaderUrl;
  10824. if (fragment[0] === ".") {
  10825. fragmentShaderUrl = fragment;
  10826. } else {
  10827. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  10828. }
  10829. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  10830. };
  10831. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  10832. try {
  10833. var engine = this._engine;
  10834. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  10835. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  10836. this._attributes = engine.getAttributes(this._program, attributesNames);
  10837. for (var index = 0; index < this._samplers.length; index++) {
  10838. var sampler = this.getUniform(this._samplers[index]);
  10839. if (sampler == null) {
  10840. this._samplers.splice(index, 1);
  10841. index--;
  10842. }
  10843. }
  10844. engine.bindSamplers(this);
  10845. this._isReady = true;
  10846. if (this.onCompiled) {
  10847. this.onCompiled(this);
  10848. }
  10849. } catch (e) {
  10850. if (e.message.indexOf("highp") !== -1) {
  10851. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  10852. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  10853. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  10854. return;
  10855. }
  10856. if (fallbacks && fallbacks.isMoreFallbacks) {
  10857. defines = fallbacks.reduce(defines);
  10858. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  10859. } else {
  10860. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  10861. BABYLON.Tools.Error("Defines: " + defines);
  10862. BABYLON.Tools.Error("Error: " + e.message);
  10863. this._compilationError = e.message;
  10864. if (this.onError) {
  10865. this.onError(this, this._compilationError);
  10866. }
  10867. }
  10868. }
  10869. };
  10870. Effect.prototype._bindTexture = function (channel, texture) {
  10871. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  10872. };
  10873. Effect.prototype.setTexture = function (channel, texture) {
  10874. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  10875. };
  10876. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10877. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  10878. };
  10879. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  10880. if (!this._valueCache[uniformName]) {
  10881. this._valueCache[uniformName] = [x, y];
  10882. return;
  10883. }
  10884. this._valueCache[uniformName][0] = x;
  10885. this._valueCache[uniformName][1] = y;
  10886. };
  10887. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  10888. if (!this._valueCache[uniformName]) {
  10889. this._valueCache[uniformName] = [x, y, z];
  10890. return;
  10891. }
  10892. this._valueCache[uniformName][0] = x;
  10893. this._valueCache[uniformName][1] = y;
  10894. this._valueCache[uniformName][2] = z;
  10895. };
  10896. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  10897. if (!this._valueCache[uniformName]) {
  10898. this._valueCache[uniformName] = [x, y, z, w];
  10899. return;
  10900. }
  10901. this._valueCache[uniformName][0] = x;
  10902. this._valueCache[uniformName][1] = y;
  10903. this._valueCache[uniformName][2] = z;
  10904. this._valueCache[uniformName][3] = w;
  10905. };
  10906. Effect.prototype.setArray = function (uniformName, array) {
  10907. this._engine.setArray(this.getUniform(uniformName), array);
  10908. return this;
  10909. };
  10910. Effect.prototype.setMatrices = function (uniformName, matrices) {
  10911. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  10912. return this;
  10913. };
  10914. Effect.prototype.setMatrix = function (uniformName, matrix) {
  10915. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  10916. return this;
  10917. };
  10918. Effect.prototype.setFloat = function (uniformName, value) {
  10919. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  10920. return this;
  10921. this._valueCache[uniformName] = value;
  10922. this._engine.setFloat(this.getUniform(uniformName), value);
  10923. return this;
  10924. };
  10925. Effect.prototype.setBool = function (uniformName, bool) {
  10926. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  10927. return this;
  10928. this._valueCache[uniformName] = bool;
  10929. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  10930. return this;
  10931. };
  10932. Effect.prototype.setVector2 = function (uniformName, vector2) {
  10933. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector2.x && this._valueCache[uniformName][1] == vector2.y)
  10934. return this;
  10935. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  10936. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  10937. return this;
  10938. };
  10939. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  10940. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y)
  10941. return this;
  10942. this._cacheFloat2(uniformName, x, y);
  10943. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  10944. return this;
  10945. };
  10946. Effect.prototype.setVector3 = function (uniformName, vector3) {
  10947. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector3.x && this._valueCache[uniformName][1] == vector3.y && this._valueCache[uniformName][2] == vector3.z)
  10948. return this;
  10949. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  10950. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  10951. return this;
  10952. };
  10953. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  10954. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z)
  10955. return this;
  10956. this._cacheFloat3(uniformName, x, y, z);
  10957. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  10958. return this;
  10959. };
  10960. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  10961. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z && this._valueCache[uniformName][3] == w)
  10962. return this;
  10963. this._cacheFloat4(uniformName, x, y, z, w);
  10964. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  10965. return this;
  10966. };
  10967. Effect.prototype.setColor3 = function (uniformName, color3) {
  10968. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b)
  10969. return this;
  10970. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  10971. this._engine.setColor3(this.getUniform(uniformName), color3);
  10972. return this;
  10973. };
  10974. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  10975. 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)
  10976. return this;
  10977. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  10978. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  10979. return this;
  10980. };
  10981. 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}",
  10982. 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}",
  10983. 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}",
  10984. cloudPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform float iGlobalTime;\nuniform vec3 c1;\nuniform vec3 c2;\nuniform vec3 c3;\nuniform vec3 c4;\nuniform vec3 c5;\nuniform vec3 c6;\nuniform vec2 speed;\nuniform float shift;\nuniform float alpha;\n\nvarying vec2 vUV;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main() {\n\n vec2 p = vUV * 12.0;\n vec3 c = mix(vec3(0.15, 0.68, 1.0), vec3(1,1,1), fbm(p));\n gl_FragColor = vec4(c, 1);\n\n}",
  10985. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  10986. 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}",
  10987. 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}",
  10988. defaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform float darkness0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform float darkness1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform float darkness2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform float darkness3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / 1500.0)) < depth.z) visibility -= 0.2;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz * vBumpInfos.y;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n diffuseColor *= vColor;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, darkness0);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, darkness1);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, darkness2);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, darkness3);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  10989. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec3 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef REFLECTION\n vPositionUVW = position;\n#endif \n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n finalWorld = world;\n#endif\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n\n // Point size\n#ifdef POINTSIZE\n gl_PointSize = pointSize;\n#endif\n}",
  10990. 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}",
  10991. 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}",
  10992. firePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform float iGlobalTime;\nuniform vec3 c1;\nuniform vec3 c2;\nuniform vec3 c3;\nuniform vec3 c4;\nuniform vec3 c5;\nuniform vec3 c6;\nuniform vec2 speed;\nuniform float shift;\nuniform float alpha;\n\nvarying vec2 vUV;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main() {\n\n vec2 p = vUV * 8.0;\n float q = fbm(p - iGlobalTime * 0.1);\n vec2 r = vec2(fbm(p + q + iGlobalTime * speed.x - p.x - p.y), fbm(p + q - iGlobalTime * speed.y));\n vec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\n gl_FragColor = vec4(c * cos(shift * vUV.y), alpha);\n\n}",
  10993. 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}",
  10994. 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}",
  10995. 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}",
  10996. legacydefaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_PROJECTION 4.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return 0.;\n }\n return 1.;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW;\n if (lightData.w == 0.)\n {\n lightVectorW = normalize(lightData.xyz - vPositionW);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\n result[0] = ndl * diffuseColor.rgb;\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = ndl * spotAtten * diffuseColor.rgb;\n result[1] = specComp * specularColor * spotAtten;\n result[2] = vec3(0.);\n\n return result;\n }\n\n result[0] = vec3(0.);\n result[1] = vec3(0.);\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\n mat3 result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = mix(groundColor, diffuseColor.rgb, ndl);\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\n diffuseColor *= vColor;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n mat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\n mat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n mat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  10997. legacydefaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec3 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return position;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n finalWorld = world;\n#endif\n\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef REFLECTION\n vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}",
  10998. 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}",
  10999. 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}",
  11000. 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}",
  11001. outlinePixelShader:"precision highp float;\n\nuniform vec3 color;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void) {\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n gl_FragColor = vec4(color, 1.);\n}",
  11002. 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}",
  11003. 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}",
  11004. 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}",
  11005. 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}",
  11006. 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}",
  11007. 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}",
  11008. 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}",
  11009. 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}",
  11010. 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}",
  11011. 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}",
  11012. 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}",
  11013. woodPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition; \nvarying vec2 vUV; \n\nuniform float ampScale;\nuniform float ringScale;\nuniform vec3 woodColor1;\nuniform vec3 woodColor2;\n\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n\n vec2 positionWood = vPosition;\n float r = ringScale * sqrt(dot(positionWood.xy, positionWood.xy));\n r = r + fbm(vPosition);\n r = r - floor(r);\n r = smoothstep(0.0, 0.8, r) - smoothstep(0.8, 1.0, r);\n\n gl_FragColor = vec4(mix(woodColor1, woodColor2, r), 1.0);\n}",
  11014. };
  11015. return Effect;
  11016. })();
  11017. BABYLON.Effect = Effect;
  11018. })(BABYLON || (BABYLON = {}));
  11019. var BABYLON;
  11020. (function (BABYLON) {
  11021. var Material = (function () {
  11022. function Material(name, scene, doNotAdd) {
  11023. this.name = name;
  11024. this.checkReadyOnEveryCall = true;
  11025. this.checkReadyOnlyOnce = false;
  11026. this.state = "";
  11027. this.alpha = 1.0;
  11028. this.backFaceCulling = true;
  11029. this._wasPreviouslyReady = false;
  11030. this._fillMode = Material.TriangleFillMode;
  11031. this.pointSize = 1.0;
  11032. this.id = name;
  11033. this._scene = scene;
  11034. if (!doNotAdd) {
  11035. scene.materials.push(this);
  11036. }
  11037. }
  11038. Object.defineProperty(Material, "TriangleFillMode", {
  11039. get: function () {
  11040. return Material._TriangleFillMode;
  11041. },
  11042. enumerable: true,
  11043. configurable: true
  11044. });
  11045. Object.defineProperty(Material, "WireFrameFillMode", {
  11046. get: function () {
  11047. return Material._WireFrameFillMode;
  11048. },
  11049. enumerable: true,
  11050. configurable: true
  11051. });
  11052. Object.defineProperty(Material, "PointFillMode", {
  11053. get: function () {
  11054. return Material._PointFillMode;
  11055. },
  11056. enumerable: true,
  11057. configurable: true
  11058. });
  11059. Object.defineProperty(Material.prototype, "wireframe", {
  11060. get: function () {
  11061. return this._fillMode === Material.WireFrameFillMode;
  11062. },
  11063. set: function (value) {
  11064. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  11065. },
  11066. enumerable: true,
  11067. configurable: true
  11068. });
  11069. Object.defineProperty(Material.prototype, "pointsCloud", {
  11070. get: function () {
  11071. return this._fillMode === Material.PointFillMode;
  11072. },
  11073. set: function (value) {
  11074. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  11075. },
  11076. enumerable: true,
  11077. configurable: true
  11078. });
  11079. Object.defineProperty(Material.prototype, "fillMode", {
  11080. get: function () {
  11081. return this._fillMode;
  11082. },
  11083. set: function (value) {
  11084. this._fillMode = value;
  11085. },
  11086. enumerable: true,
  11087. configurable: true
  11088. });
  11089. Material.prototype.isReady = function (mesh, useInstances) {
  11090. return true;
  11091. };
  11092. Material.prototype.getEffect = function () {
  11093. return this._effect;
  11094. };
  11095. Material.prototype.getScene = function () {
  11096. return this._scene;
  11097. };
  11098. Material.prototype.needAlphaBlending = function () {
  11099. return (this.alpha < 1.0);
  11100. };
  11101. Material.prototype.needAlphaTesting = function () {
  11102. return false;
  11103. };
  11104. Material.prototype.getAlphaTestTexture = function () {
  11105. return null;
  11106. };
  11107. Material.prototype.trackCreation = function (onCompiled, onError) {
  11108. };
  11109. Material.prototype._preBind = function () {
  11110. var engine = this._scene.getEngine();
  11111. engine.enableEffect(this._effect);
  11112. engine.setState(this.backFaceCulling);
  11113. };
  11114. Material.prototype.bind = function (world, mesh) {
  11115. };
  11116. Material.prototype.bindOnlyWorldMatrix = function (world) {
  11117. };
  11118. Material.prototype.unbind = function () {
  11119. };
  11120. Material.prototype.dispose = function (forceDisposeEffect) {
  11121. var index = this._scene.materials.indexOf(this);
  11122. this._scene.materials.splice(index, 1);
  11123. if (forceDisposeEffect && this._effect) {
  11124. this._scene.getEngine()._releaseEffect(this._effect);
  11125. this._effect = null;
  11126. }
  11127. if (this.onDispose) {
  11128. this.onDispose();
  11129. }
  11130. };
  11131. Material._TriangleFillMode = 0;
  11132. Material._WireFrameFillMode = 1;
  11133. Material._PointFillMode = 2;
  11134. return Material;
  11135. })();
  11136. BABYLON.Material = Material;
  11137. })(BABYLON || (BABYLON = {}));
  11138. var __extends = this.__extends || function (d, b) {
  11139. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11140. function __() { this.constructor = d; }
  11141. __.prototype = b.prototype;
  11142. d.prototype = new __();
  11143. };
  11144. var BABYLON;
  11145. (function (BABYLON) {
  11146. var maxSimultaneousLights = 4;
  11147. var FresnelParameters = (function () {
  11148. function FresnelParameters() {
  11149. this.isEnabled = true;
  11150. this.leftColor = BABYLON.Color3.White();
  11151. this.rightColor = BABYLON.Color3.Black();
  11152. this.bias = 0;
  11153. this.power = 1;
  11154. }
  11155. return FresnelParameters;
  11156. })();
  11157. BABYLON.FresnelParameters = FresnelParameters;
  11158. var StandardMaterial = (function (_super) {
  11159. __extends(StandardMaterial, _super);
  11160. function StandardMaterial(name, scene) {
  11161. var _this = this;
  11162. _super.call(this, name, scene);
  11163. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11164. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  11165. this.specularColor = new BABYLON.Color3(1, 1, 1);
  11166. this.specularPower = 64;
  11167. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  11168. this.useAlphaFromDiffuseTexture = false;
  11169. this.useSpecularOverAlpha = true;
  11170. this.fogEnabled = true;
  11171. this._cachedDefines = null;
  11172. this._renderTargets = new BABYLON.SmartArray(16);
  11173. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  11174. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  11175. this._scaledDiffuse = new BABYLON.Color3();
  11176. this._scaledSpecular = new BABYLON.Color3();
  11177. this.getRenderTargetTextures = function () {
  11178. _this._renderTargets.reset();
  11179. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  11180. _this._renderTargets.push(_this.reflectionTexture);
  11181. }
  11182. return _this._renderTargets;
  11183. };
  11184. }
  11185. StandardMaterial.prototype.needAlphaBlending = function () {
  11186. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  11187. };
  11188. StandardMaterial.prototype.needAlphaTesting = function () {
  11189. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  11190. };
  11191. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  11192. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  11193. };
  11194. StandardMaterial.prototype.getAlphaTestTexture = function () {
  11195. return this.diffuseTexture;
  11196. };
  11197. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  11198. if (this.checkReadyOnlyOnce) {
  11199. if (this._wasPreviouslyReady) {
  11200. return true;
  11201. }
  11202. }
  11203. var scene = this.getScene();
  11204. if (!this.checkReadyOnEveryCall) {
  11205. if (this._renderId === scene.getRenderId()) {
  11206. return true;
  11207. }
  11208. }
  11209. var engine = scene.getEngine();
  11210. var defines = [];
  11211. var fallbacks = new BABYLON.EffectFallbacks();
  11212. if (scene.texturesEnabled) {
  11213. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  11214. if (!this.diffuseTexture.isReady()) {
  11215. return false;
  11216. } else {
  11217. defines.push("#define DIFFUSE");
  11218. }
  11219. }
  11220. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  11221. if (!this.ambientTexture.isReady()) {
  11222. return false;
  11223. } else {
  11224. defines.push("#define AMBIENT");
  11225. }
  11226. }
  11227. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  11228. if (!this.opacityTexture.isReady()) {
  11229. return false;
  11230. } else {
  11231. defines.push("#define OPACITY");
  11232. if (this.opacityTexture.getAlphaFromRGB) {
  11233. defines.push("#define OPACITYRGB");
  11234. }
  11235. }
  11236. }
  11237. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  11238. if (!this.reflectionTexture.isReady()) {
  11239. return false;
  11240. } else {
  11241. defines.push("#define REFLECTION");
  11242. fallbacks.addFallback(0, "REFLECTION");
  11243. }
  11244. }
  11245. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  11246. if (!this.emissiveTexture.isReady()) {
  11247. return false;
  11248. } else {
  11249. defines.push("#define EMISSIVE");
  11250. }
  11251. }
  11252. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  11253. if (!this.specularTexture.isReady()) {
  11254. return false;
  11255. } else {
  11256. defines.push("#define SPECULAR");
  11257. fallbacks.addFallback(0, "SPECULAR");
  11258. }
  11259. }
  11260. }
  11261. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  11262. if (!this.bumpTexture.isReady()) {
  11263. return false;
  11264. } else {
  11265. defines.push("#define BUMP");
  11266. fallbacks.addFallback(0, "BUMP");
  11267. }
  11268. }
  11269. if (this.useSpecularOverAlpha) {
  11270. defines.push("#define SPECULAROVERALPHA");
  11271. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  11272. }
  11273. if (scene.clipPlane) {
  11274. defines.push("#define CLIPPLANE");
  11275. }
  11276. if (engine.getAlphaTesting()) {
  11277. defines.push("#define ALPHATEST");
  11278. }
  11279. if (this._shouldUseAlphaFromDiffuseTexture()) {
  11280. defines.push("#define ALPHAFROMDIFFUSE");
  11281. }
  11282. if (this.pointsCloud) {
  11283. defines.push("#define POINTSIZE");
  11284. }
  11285. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  11286. defines.push("#define FOG");
  11287. fallbacks.addFallback(1, "FOG");
  11288. }
  11289. var shadowsActivated = false;
  11290. var lightIndex = 0;
  11291. if (scene.lightsEnabled) {
  11292. for (var index = 0; index < scene.lights.length; index++) {
  11293. var light = scene.lights[index];
  11294. if (!light.isEnabled()) {
  11295. continue;
  11296. }
  11297. if (light._excludedMeshesIds.length > 0) {
  11298. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  11299. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  11300. if (excludedMesh) {
  11301. light.excludedMeshes.push(excludedMesh);
  11302. }
  11303. }
  11304. light._excludedMeshesIds = [];
  11305. }
  11306. if (light._includedOnlyMeshesIds.length > 0) {
  11307. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  11308. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  11309. if (includedOnlyMesh) {
  11310. light.includedOnlyMeshes.push(includedOnlyMesh);
  11311. }
  11312. }
  11313. light._includedOnlyMeshesIds = [];
  11314. }
  11315. if (!light.canAffectMesh(mesh)) {
  11316. continue;
  11317. }
  11318. defines.push("#define LIGHT" + lightIndex);
  11319. if (lightIndex > 0) {
  11320. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  11321. }
  11322. var type;
  11323. if (light instanceof BABYLON.SpotLight) {
  11324. type = "#define SPOTLIGHT" + lightIndex;
  11325. } else if (light instanceof BABYLON.HemisphericLight) {
  11326. type = "#define HEMILIGHT" + lightIndex;
  11327. } else {
  11328. type = "#define POINTDIRLIGHT" + lightIndex;
  11329. }
  11330. defines.push(type);
  11331. if (lightIndex > 0) {
  11332. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  11333. }
  11334. if (scene.shadowsEnabled) {
  11335. var shadowGenerator = light.getShadowGenerator();
  11336. if (mesh && mesh.receiveShadows && shadowGenerator) {
  11337. defines.push("#define SHADOW" + lightIndex);
  11338. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  11339. if (!shadowsActivated) {
  11340. defines.push("#define SHADOWS");
  11341. shadowsActivated = true;
  11342. }
  11343. if (shadowGenerator.useVarianceShadowMap) {
  11344. defines.push("#define SHADOWVSM" + lightIndex);
  11345. if (lightIndex > 0) {
  11346. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  11347. }
  11348. }
  11349. if (shadowGenerator.usePoissonSampling) {
  11350. defines.push("#define SHADOWPCF" + lightIndex);
  11351. if (lightIndex > 0) {
  11352. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  11353. }
  11354. }
  11355. }
  11356. }
  11357. lightIndex++;
  11358. if (lightIndex == maxSimultaneousLights)
  11359. break;
  11360. }
  11361. }
  11362. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  11363. var fresnelRank = 1;
  11364. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  11365. defines.push("#define DIFFUSEFRESNEL");
  11366. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  11367. fresnelRank++;
  11368. }
  11369. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  11370. defines.push("#define OPACITYFRESNEL");
  11371. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  11372. fresnelRank++;
  11373. }
  11374. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  11375. defines.push("#define REFLECTIONFRESNEL");
  11376. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  11377. fresnelRank++;
  11378. }
  11379. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  11380. defines.push("#define EMISSIVEFRESNEL");
  11381. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  11382. fresnelRank++;
  11383. }
  11384. defines.push("#define FRESNEL");
  11385. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  11386. }
  11387. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  11388. if (mesh) {
  11389. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11390. attribs.push(BABYLON.VertexBuffer.UVKind);
  11391. defines.push("#define UV1");
  11392. }
  11393. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11394. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11395. defines.push("#define UV2");
  11396. }
  11397. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  11398. attribs.push(BABYLON.VertexBuffer.ColorKind);
  11399. defines.push("#define VERTEXCOLOR");
  11400. }
  11401. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  11402. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11403. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11404. defines.push("#define BONES");
  11405. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11406. defines.push("#define BONES4");
  11407. fallbacks.addFallback(0, "BONES4");
  11408. }
  11409. if (useInstances) {
  11410. defines.push("#define INSTANCES");
  11411. attribs.push("world0");
  11412. attribs.push("world1");
  11413. attribs.push("world2");
  11414. attribs.push("world3");
  11415. }
  11416. }
  11417. var join = defines.join("\n");
  11418. if (this._cachedDefines != join) {
  11419. this._cachedDefines = join;
  11420. var shaderName = "default";
  11421. if (!scene.getEngine().getCaps().standardDerivatives) {
  11422. shaderName = "legacydefault";
  11423. }
  11424. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  11425. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  11426. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  11427. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  11428. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  11429. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  11430. "vFogInfos", "vFogColor", "pointSize",
  11431. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  11432. "mBones",
  11433. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  11434. "darkness0", "darkness1", "darkness2", "darkness3",
  11435. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  11436. ], [
  11437. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  11438. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  11439. ], join, fallbacks, this.onCompiled, this.onError);
  11440. }
  11441. if (!this._effect.isReady()) {
  11442. return false;
  11443. }
  11444. this._renderId = scene.getRenderId();
  11445. this._wasPreviouslyReady = true;
  11446. return true;
  11447. };
  11448. StandardMaterial.prototype.unbind = function () {
  11449. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  11450. this._effect.setTexture("reflection2DSampler", null);
  11451. }
  11452. };
  11453. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  11454. this._effect.setMatrix("world", world);
  11455. };
  11456. StandardMaterial.prototype.bind = function (world, mesh) {
  11457. var scene = this.getScene();
  11458. this.bindOnlyWorldMatrix(world);
  11459. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  11460. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  11461. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  11462. }
  11463. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  11464. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  11465. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  11466. }
  11467. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  11468. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  11469. }
  11470. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  11471. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  11472. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  11473. }
  11474. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  11475. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  11476. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  11477. }
  11478. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  11479. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  11480. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  11481. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  11482. }
  11483. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  11484. this._effect.setTexture("ambientSampler", this.ambientTexture);
  11485. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  11486. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  11487. }
  11488. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  11489. this._effect.setTexture("opacitySampler", this.opacityTexture);
  11490. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  11491. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  11492. }
  11493. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  11494. if (this.reflectionTexture.isCube) {
  11495. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  11496. } else {
  11497. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  11498. }
  11499. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  11500. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  11501. }
  11502. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  11503. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  11504. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  11505. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  11506. }
  11507. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  11508. this._effect.setTexture("specularSampler", this.specularTexture);
  11509. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  11510. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  11511. }
  11512. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
  11513. this._effect.setTexture("bumpSampler", this.bumpTexture);
  11514. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
  11515. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  11516. }
  11517. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  11518. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  11519. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  11520. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  11521. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  11522. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  11523. if (scene.lightsEnabled) {
  11524. var lightIndex = 0;
  11525. for (var index = 0; index < scene.lights.length; index++) {
  11526. var light = scene.lights[index];
  11527. if (!light.isEnabled()) {
  11528. continue;
  11529. }
  11530. if (!light.canAffectMesh(mesh)) {
  11531. continue;
  11532. }
  11533. if (light instanceof BABYLON.PointLight) {
  11534. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  11535. } else if (light instanceof BABYLON.DirectionalLight) {
  11536. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  11537. } else if (light instanceof BABYLON.SpotLight) {
  11538. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  11539. } else if (light instanceof BABYLON.HemisphericLight) {
  11540. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  11541. }
  11542. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  11543. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  11544. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  11545. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  11546. if (scene.shadowsEnabled) {
  11547. var shadowGenerator = light.getShadowGenerator();
  11548. if (mesh.receiveShadows && shadowGenerator) {
  11549. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  11550. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  11551. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  11552. }
  11553. }
  11554. lightIndex++;
  11555. if (lightIndex == maxSimultaneousLights)
  11556. break;
  11557. }
  11558. }
  11559. if (scene.clipPlane) {
  11560. var clipPlane = scene.clipPlane;
  11561. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  11562. }
  11563. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  11564. this._effect.setMatrix("view", scene.getViewMatrix());
  11565. }
  11566. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11567. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  11568. this._effect.setColor3("vFogColor", scene.fogColor);
  11569. }
  11570. if (this.pointsCloud) {
  11571. this._effect.setFloat("pointSize", this.pointSize);
  11572. }
  11573. };
  11574. StandardMaterial.prototype.getAnimatables = function () {
  11575. var results = [];
  11576. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  11577. results.push(this.diffuseTexture);
  11578. }
  11579. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  11580. results.push(this.ambientTexture);
  11581. }
  11582. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  11583. results.push(this.opacityTexture);
  11584. }
  11585. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  11586. results.push(this.reflectionTexture);
  11587. }
  11588. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  11589. results.push(this.emissiveTexture);
  11590. }
  11591. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  11592. results.push(this.specularTexture);
  11593. }
  11594. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  11595. results.push(this.bumpTexture);
  11596. }
  11597. return results;
  11598. };
  11599. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  11600. if (this.diffuseTexture) {
  11601. this.diffuseTexture.dispose();
  11602. }
  11603. if (this.ambientTexture) {
  11604. this.ambientTexture.dispose();
  11605. }
  11606. if (this.opacityTexture) {
  11607. this.opacityTexture.dispose();
  11608. }
  11609. if (this.reflectionTexture) {
  11610. this.reflectionTexture.dispose();
  11611. }
  11612. if (this.emissiveTexture) {
  11613. this.emissiveTexture.dispose();
  11614. }
  11615. if (this.specularTexture) {
  11616. this.specularTexture.dispose();
  11617. }
  11618. if (this.bumpTexture) {
  11619. this.bumpTexture.dispose();
  11620. }
  11621. _super.prototype.dispose.call(this, forceDisposeEffect);
  11622. };
  11623. StandardMaterial.prototype.clone = function (name) {
  11624. var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
  11625. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  11626. newStandardMaterial.alpha = this.alpha;
  11627. newStandardMaterial.fillMode = this.fillMode;
  11628. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  11629. if (this.diffuseTexture && this.diffuseTexture.clone) {
  11630. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  11631. }
  11632. if (this.ambientTexture && this.ambientTexture.clone) {
  11633. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  11634. }
  11635. if (this.opacityTexture && this.opacityTexture.clone) {
  11636. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  11637. }
  11638. if (this.reflectionTexture && this.reflectionTexture.clone) {
  11639. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  11640. }
  11641. if (this.emissiveTexture && this.emissiveTexture.clone) {
  11642. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  11643. }
  11644. if (this.specularTexture && this.specularTexture.clone) {
  11645. newStandardMaterial.specularTexture = this.specularTexture.clone();
  11646. }
  11647. if (this.bumpTexture && this.bumpTexture.clone) {
  11648. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  11649. }
  11650. newStandardMaterial.ambientColor = this.ambientColor.clone();
  11651. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  11652. newStandardMaterial.specularColor = this.specularColor.clone();
  11653. newStandardMaterial.specularPower = this.specularPower;
  11654. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  11655. return newStandardMaterial;
  11656. };
  11657. StandardMaterial.DiffuseTextureEnabled = true;
  11658. StandardMaterial.AmbientTextureEnabled = true;
  11659. StandardMaterial.OpacityTextureEnabled = true;
  11660. StandardMaterial.ReflectionTextureEnabled = true;
  11661. StandardMaterial.EmissiveTextureEnabled = true;
  11662. StandardMaterial.SpecularTextureEnabled = true;
  11663. StandardMaterial.BumpTextureEnabled = true;
  11664. return StandardMaterial;
  11665. })(BABYLON.Material);
  11666. BABYLON.StandardMaterial = StandardMaterial;
  11667. })(BABYLON || (BABYLON = {}));
  11668. var __extends = this.__extends || function (d, b) {
  11669. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11670. function __() { this.constructor = d; }
  11671. __.prototype = b.prototype;
  11672. d.prototype = new __();
  11673. };
  11674. var BABYLON;
  11675. (function (BABYLON) {
  11676. var MultiMaterial = (function (_super) {
  11677. __extends(MultiMaterial, _super);
  11678. function MultiMaterial(name, scene) {
  11679. _super.call(this, name, scene, true);
  11680. this.subMaterials = new Array();
  11681. scene.multiMaterials.push(this);
  11682. }
  11683. MultiMaterial.prototype.getSubMaterial = function (index) {
  11684. if (index < 0 || index >= this.subMaterials.length) {
  11685. return this.getScene().defaultMaterial;
  11686. }
  11687. return this.subMaterials[index];
  11688. };
  11689. MultiMaterial.prototype.isReady = function (mesh) {
  11690. for (var index = 0; index < this.subMaterials.length; index++) {
  11691. var subMaterial = this.subMaterials[index];
  11692. if (subMaterial) {
  11693. if (!this.subMaterials[index].isReady(mesh)) {
  11694. return false;
  11695. }
  11696. }
  11697. }
  11698. return true;
  11699. };
  11700. return MultiMaterial;
  11701. })(BABYLON.Material);
  11702. BABYLON.MultiMaterial = MultiMaterial;
  11703. })(BABYLON || (BABYLON = {}));
  11704. var BABYLON;
  11705. (function (BABYLON) {
  11706. var Database = (function () {
  11707. function Database(urlToScene, callbackManifestChecked) {
  11708. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  11709. this.callbackManifestChecked = callbackManifestChecked;
  11710. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  11711. this.db = null;
  11712. this.enableSceneOffline = false;
  11713. this.enableTexturesOffline = false;
  11714. this.manifestVersionFound = 0;
  11715. this.mustUpdateRessources = false;
  11716. this.hasReachedQuota = false;
  11717. this.checkManifestFile();
  11718. }
  11719. Database.prototype.checkManifestFile = function () {
  11720. var _this = this;
  11721. function noManifestFile() {
  11722. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  11723. that.enableSceneOffline = false;
  11724. that.enableTexturesOffline = false;
  11725. that.callbackManifestChecked(false);
  11726. }
  11727. var that = this;
  11728. var manifestURL = this.currentSceneUrl + ".manifest";
  11729. var xhr = new XMLHttpRequest();
  11730. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  11731. xhr.open("GET", manifestURLTimeStamped, true);
  11732. xhr.addEventListener("load", function () {
  11733. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  11734. try {
  11735. var manifestFile = JSON.parse(xhr.response);
  11736. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  11737. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  11738. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  11739. _this.manifestVersionFound = manifestFile.version;
  11740. }
  11741. if (_this.callbackManifestChecked) {
  11742. _this.callbackManifestChecked(true);
  11743. }
  11744. } catch (ex) {
  11745. noManifestFile();
  11746. }
  11747. } else {
  11748. noManifestFile();
  11749. }
  11750. }, false);
  11751. xhr.addEventListener("error", function (event) {
  11752. noManifestFile();
  11753. }, false);
  11754. try {
  11755. xhr.send();
  11756. } catch (ex) {
  11757. BABYLON.Tools.Error("Error on XHR send request.");
  11758. that.callbackManifestChecked(false);
  11759. }
  11760. };
  11761. Database.prototype.openAsync = function (successCallback, errorCallback) {
  11762. var _this = this;
  11763. function handleError() {
  11764. that.isSupported = false;
  11765. if (errorCallback)
  11766. errorCallback();
  11767. }
  11768. var that = this;
  11769. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  11770. this.isSupported = false;
  11771. if (errorCallback)
  11772. errorCallback();
  11773. } else {
  11774. if (!this.db) {
  11775. this.hasReachedQuota = false;
  11776. this.isSupported = true;
  11777. var request = this.idbFactory.open("babylonjs", 1);
  11778. request.onerror = function (event) {
  11779. handleError();
  11780. };
  11781. request.onblocked = function (event) {
  11782. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  11783. handleError();
  11784. };
  11785. request.onsuccess = function (event) {
  11786. _this.db = request.result;
  11787. successCallback();
  11788. };
  11789. request.onupgradeneeded = function (event) {
  11790. _this.db = (event.target).result;
  11791. try {
  11792. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  11793. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  11794. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  11795. } catch (ex) {
  11796. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  11797. handleError();
  11798. }
  11799. };
  11800. } else {
  11801. if (successCallback)
  11802. successCallback();
  11803. }
  11804. }
  11805. };
  11806. Database.prototype.loadImageFromDB = function (url, image) {
  11807. var _this = this;
  11808. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  11809. var saveAndLoadImage = function () {
  11810. if (!_this.hasReachedQuota && _this.db !== null) {
  11811. _this._saveImageIntoDBAsync(completeURL, image);
  11812. } else {
  11813. image.src = url;
  11814. }
  11815. };
  11816. if (!this.mustUpdateRessources) {
  11817. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  11818. } else {
  11819. saveAndLoadImage();
  11820. }
  11821. };
  11822. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  11823. if (this.isSupported && this.db !== null) {
  11824. var texture;
  11825. var transaction = this.db.transaction(["textures"]);
  11826. transaction.onabort = function (event) {
  11827. image.src = url;
  11828. };
  11829. transaction.oncomplete = function (event) {
  11830. var blobTextureURL;
  11831. if (texture) {
  11832. var URL = window.URL || window.webkitURL;
  11833. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  11834. image.onerror = function () {
  11835. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  11836. image.src = url;
  11837. };
  11838. image.src = blobTextureURL;
  11839. } else {
  11840. notInDBCallback();
  11841. }
  11842. };
  11843. var getRequest = transaction.objectStore("textures").get(url);
  11844. getRequest.onsuccess = function (event) {
  11845. texture = (event.target).result;
  11846. };
  11847. getRequest.onerror = function (event) {
  11848. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  11849. image.src = url;
  11850. };
  11851. } else {
  11852. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11853. image.src = url;
  11854. }
  11855. };
  11856. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  11857. var _this = this;
  11858. if (this.isSupported) {
  11859. var generateBlobUrl = function () {
  11860. var blobTextureURL;
  11861. if (blob) {
  11862. var URL = window.URL || window.webkitURL;
  11863. try {
  11864. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  11865. } catch (ex) {
  11866. blobTextureURL = URL.createObjectURL(blob);
  11867. }
  11868. }
  11869. image.src = blobTextureURL;
  11870. };
  11871. if (BABYLON.Database.isUASupportingBlobStorage) {
  11872. var xhr = new XMLHttpRequest(), blob;
  11873. xhr.open("GET", url, true);
  11874. xhr.responseType = "blob";
  11875. xhr.addEventListener("load", function () {
  11876. if (xhr.status === 200) {
  11877. blob = xhr.response;
  11878. var transaction = _this.db.transaction(["textures"], "readwrite");
  11879. transaction.onabort = function (event) {
  11880. try {
  11881. if (event.srcElement.error.name === "QuotaExceededError") {
  11882. this.hasReachedQuota = true;
  11883. }
  11884. } catch (ex) {
  11885. }
  11886. generateBlobUrl();
  11887. };
  11888. transaction.oncomplete = function (event) {
  11889. generateBlobUrl();
  11890. };
  11891. var newTexture = { textureUrl: url, data: blob };
  11892. try {
  11893. var addRequest = transaction.objectStore("textures").put(newTexture);
  11894. addRequest.onsuccess = function (event) {
  11895. };
  11896. addRequest.onerror = function (event) {
  11897. generateBlobUrl();
  11898. };
  11899. } catch (ex) {
  11900. if (ex.code === 25) {
  11901. BABYLON.Database.isUASupportingBlobStorage = false;
  11902. }
  11903. image.src = url;
  11904. }
  11905. } else {
  11906. image.src = url;
  11907. }
  11908. }, false);
  11909. xhr.addEventListener("error", function (event) {
  11910. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  11911. image.src = url;
  11912. }, false);
  11913. xhr.send();
  11914. } else {
  11915. image.src = url;
  11916. }
  11917. } else {
  11918. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11919. image.src = url;
  11920. }
  11921. };
  11922. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  11923. var _this = this;
  11924. var updateVersion = function (event) {
  11925. _this._saveVersionIntoDBAsync(url, versionLoaded);
  11926. };
  11927. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  11928. };
  11929. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  11930. var _this = this;
  11931. if (this.isSupported) {
  11932. var version;
  11933. try {
  11934. var transaction = this.db.transaction(["versions"]);
  11935. transaction.oncomplete = function (event) {
  11936. if (version) {
  11937. if (_this.manifestVersionFound > version.data) {
  11938. _this.mustUpdateRessources = true;
  11939. updateInDBCallback();
  11940. } else {
  11941. callback(version.data);
  11942. }
  11943. } else {
  11944. _this.mustUpdateRessources = true;
  11945. updateInDBCallback();
  11946. }
  11947. };
  11948. transaction.onabort = function (event) {
  11949. callback(-1);
  11950. };
  11951. var getRequest = transaction.objectStore("versions").get(url);
  11952. getRequest.onsuccess = function (event) {
  11953. version = (event.target).result;
  11954. };
  11955. getRequest.onerror = function (event) {
  11956. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  11957. callback(-1);
  11958. };
  11959. } catch (ex) {
  11960. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  11961. callback(-1);
  11962. }
  11963. } else {
  11964. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11965. callback(-1);
  11966. }
  11967. };
  11968. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  11969. var _this = this;
  11970. if (this.isSupported && !this.hasReachedQuota) {
  11971. try {
  11972. var transaction = this.db.transaction(["versions"], "readwrite");
  11973. transaction.onabort = function (event) {
  11974. try {
  11975. if (event.srcElement.error.name === "QuotaExceededError") {
  11976. _this.hasReachedQuota = true;
  11977. }
  11978. } catch (ex) {
  11979. }
  11980. callback(-1);
  11981. };
  11982. transaction.oncomplete = function (event) {
  11983. callback(_this.manifestVersionFound);
  11984. };
  11985. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  11986. var addRequest = transaction.objectStore("versions").put(newVersion);
  11987. addRequest.onsuccess = function (event) {
  11988. };
  11989. addRequest.onerror = function (event) {
  11990. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  11991. };
  11992. } catch (ex) {
  11993. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  11994. callback(-1);
  11995. }
  11996. } else {
  11997. callback(-1);
  11998. }
  11999. };
  12000. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  12001. var _this = this;
  12002. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  12003. var saveAndLoadFile = function (event) {
  12004. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  12005. };
  12006. this._checkVersionFromDB(completeUrl, function (version) {
  12007. if (version !== -1) {
  12008. if (!_this.mustUpdateRessources) {
  12009. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  12010. } else {
  12011. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  12012. }
  12013. } else {
  12014. errorCallback();
  12015. }
  12016. });
  12017. };
  12018. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  12019. if (this.isSupported) {
  12020. var targetStore;
  12021. if (url.indexOf(".babylon") !== -1) {
  12022. targetStore = "scenes";
  12023. } else {
  12024. targetStore = "textures";
  12025. }
  12026. var file;
  12027. var transaction = this.db.transaction([targetStore]);
  12028. transaction.oncomplete = function (event) {
  12029. if (file) {
  12030. callback(file.data);
  12031. } else {
  12032. notInDBCallback();
  12033. }
  12034. };
  12035. transaction.onabort = function (event) {
  12036. notInDBCallback();
  12037. };
  12038. var getRequest = transaction.objectStore(targetStore).get(url);
  12039. getRequest.onsuccess = function (event) {
  12040. file = (event.target).result;
  12041. };
  12042. getRequest.onerror = function (event) {
  12043. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  12044. notInDBCallback();
  12045. };
  12046. } else {
  12047. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12048. callback();
  12049. }
  12050. };
  12051. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  12052. var _this = this;
  12053. if (this.isSupported) {
  12054. var targetStore;
  12055. if (url.indexOf(".babylon") !== -1) {
  12056. targetStore = "scenes";
  12057. } else {
  12058. targetStore = "textures";
  12059. }
  12060. var xhr = new XMLHttpRequest(), fileData;
  12061. xhr.open("GET", url, true);
  12062. if (useArrayBuffer) {
  12063. xhr.responseType = "arraybuffer";
  12064. }
  12065. xhr.onprogress = progressCallback;
  12066. xhr.addEventListener("load", function () {
  12067. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  12068. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  12069. if (!_this.hasReachedQuota) {
  12070. var transaction = _this.db.transaction([targetStore], "readwrite");
  12071. transaction.onabort = function (event) {
  12072. try {
  12073. if (event.srcElement.error.name === "QuotaExceededError") {
  12074. this.hasReachedQuota = true;
  12075. }
  12076. } catch (ex) {
  12077. }
  12078. callback(fileData);
  12079. };
  12080. transaction.oncomplete = function (event) {
  12081. callback(fileData);
  12082. };
  12083. var newFile;
  12084. if (targetStore === "scenes") {
  12085. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  12086. } else {
  12087. newFile = { textureUrl: url, data: fileData };
  12088. }
  12089. try {
  12090. var addRequest = transaction.objectStore(targetStore).put(newFile);
  12091. addRequest.onsuccess = function (event) {
  12092. };
  12093. addRequest.onerror = function (event) {
  12094. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  12095. };
  12096. } catch (ex) {
  12097. callback(fileData);
  12098. }
  12099. } else {
  12100. callback(fileData);
  12101. }
  12102. } else {
  12103. callback();
  12104. }
  12105. }, false);
  12106. xhr.addEventListener("error", function (event) {
  12107. BABYLON.Tools.Error("error on XHR request.");
  12108. callback();
  12109. }, false);
  12110. xhr.send();
  12111. } else {
  12112. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12113. callback();
  12114. }
  12115. };
  12116. Database.isUASupportingBlobStorage = true;
  12117. Database.parseURL = function (url) {
  12118. var a = document.createElement('a');
  12119. a.href = url;
  12120. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  12121. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  12122. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  12123. return absLocation;
  12124. };
  12125. Database.ReturnFullUrlLocation = function (url) {
  12126. if (url.indexOf("http:/") === -1) {
  12127. return (BABYLON.Database.parseURL(window.location.href) + url);
  12128. } else {
  12129. return url;
  12130. }
  12131. };
  12132. return Database;
  12133. })();
  12134. BABYLON.Database = Database;
  12135. })(BABYLON || (BABYLON = {}));
  12136. var BABYLON;
  12137. (function (BABYLON) {
  12138. var SpriteManager = (function () {
  12139. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  12140. this.name = name;
  12141. this.cellSize = cellSize;
  12142. this.sprites = new Array();
  12143. this.renderingGroupId = 0;
  12144. this.fogEnabled = true;
  12145. this._vertexDeclaration = [3, 4, 4, 4];
  12146. this._vertexStrideSize = 15 * 4;
  12147. this._capacity = capacity;
  12148. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  12149. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12150. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12151. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  12152. this._scene = scene;
  12153. this._scene.spriteManagers.push(this);
  12154. this._vertexDeclaration = [3, 4, 4, 4];
  12155. this._vertexStrideSize = 15 * 4;
  12156. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  12157. var indices = [];
  12158. var index = 0;
  12159. for (var count = 0; count < capacity; count++) {
  12160. indices.push(index);
  12161. indices.push(index + 1);
  12162. indices.push(index + 2);
  12163. indices.push(index);
  12164. indices.push(index + 2);
  12165. indices.push(index + 3);
  12166. index += 4;
  12167. }
  12168. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12169. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  12170. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  12171. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  12172. }
  12173. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  12174. var arrayOffset = index * 15;
  12175. if (offsetX == 0)
  12176. offsetX = this._epsilon;
  12177. else if (offsetX == 1)
  12178. offsetX = 1 - this._epsilon;
  12179. if (offsetY == 0)
  12180. offsetY = this._epsilon;
  12181. else if (offsetY == 1)
  12182. offsetY = 1 - this._epsilon;
  12183. this._vertices[arrayOffset] = sprite.position.x;
  12184. this._vertices[arrayOffset + 1] = sprite.position.y;
  12185. this._vertices[arrayOffset + 2] = sprite.position.z;
  12186. this._vertices[arrayOffset + 3] = sprite.angle;
  12187. this._vertices[arrayOffset + 4] = sprite.size;
  12188. this._vertices[arrayOffset + 5] = offsetX;
  12189. this._vertices[arrayOffset + 6] = offsetY;
  12190. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  12191. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  12192. var offset = (sprite.cellIndex / rowSize) >> 0;
  12193. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  12194. this._vertices[arrayOffset + 10] = offset;
  12195. this._vertices[arrayOffset + 11] = sprite.color.r;
  12196. this._vertices[arrayOffset + 12] = sprite.color.g;
  12197. this._vertices[arrayOffset + 13] = sprite.color.b;
  12198. this._vertices[arrayOffset + 14] = sprite.color.a;
  12199. };
  12200. SpriteManager.prototype.render = function () {
  12201. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  12202. return;
  12203. var engine = this._scene.getEngine();
  12204. var baseSize = this._spriteTexture.getBaseSize();
  12205. var deltaTime = BABYLON.Tools.GetDeltaTime();
  12206. var max = Math.min(this._capacity, this.sprites.length);
  12207. var rowSize = baseSize.width / this.cellSize;
  12208. var offset = 0;
  12209. for (var index = 0; index < max; index++) {
  12210. var sprite = this.sprites[index];
  12211. if (!sprite) {
  12212. continue;
  12213. }
  12214. sprite._animate(deltaTime);
  12215. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  12216. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  12217. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  12218. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  12219. }
  12220. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
  12221. var effect = this._effectBase;
  12222. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12223. effect = this._effectFog;
  12224. }
  12225. engine.enableEffect(effect);
  12226. var viewMatrix = this._scene.getViewMatrix();
  12227. effect.setTexture("diffuseSampler", this._spriteTexture);
  12228. effect.setMatrix("view", viewMatrix);
  12229. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  12230. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  12231. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12232. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  12233. effect.setColor3("vFogColor", this._scene.fogColor);
  12234. }
  12235. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12236. effect.setBool("alphaTest", true);
  12237. engine.setColorWrite(false);
  12238. engine.draw(true, 0, max * 6);
  12239. engine.setColorWrite(true);
  12240. effect.setBool("alphaTest", false);
  12241. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12242. engine.draw(true, 0, max * 6);
  12243. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12244. };
  12245. SpriteManager.prototype.dispose = function () {
  12246. if (this._vertexBuffer) {
  12247. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12248. this._vertexBuffer = null;
  12249. }
  12250. if (this._indexBuffer) {
  12251. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12252. this._indexBuffer = null;
  12253. }
  12254. if (this._spriteTexture) {
  12255. this._spriteTexture.dispose();
  12256. this._spriteTexture = null;
  12257. }
  12258. var index = this._scene.spriteManagers.indexOf(this);
  12259. this._scene.spriteManagers.splice(index, 1);
  12260. if (this.onDispose) {
  12261. this.onDispose();
  12262. }
  12263. };
  12264. return SpriteManager;
  12265. })();
  12266. BABYLON.SpriteManager = SpriteManager;
  12267. })(BABYLON || (BABYLON = {}));
  12268. var BABYLON;
  12269. (function (BABYLON) {
  12270. var Sprite = (function () {
  12271. function Sprite(name, manager) {
  12272. this.name = name;
  12273. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12274. this.size = 1.0;
  12275. this.angle = 0;
  12276. this.cellIndex = 0;
  12277. this.invertU = 0;
  12278. this.invertV = 0;
  12279. this.animations = new Array();
  12280. this._animationStarted = false;
  12281. this._loopAnimation = false;
  12282. this._fromIndex = 0;
  12283. this._toIndex = 0;
  12284. this._delay = 0;
  12285. this._direction = 1;
  12286. this._frameCount = 0;
  12287. this._time = 0;
  12288. this._manager = manager;
  12289. this._manager.sprites.push(this);
  12290. this.position = BABYLON.Vector3.Zero();
  12291. }
  12292. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  12293. this._fromIndex = from;
  12294. this._toIndex = to;
  12295. this._loopAnimation = loop;
  12296. this._delay = delay;
  12297. this._animationStarted = true;
  12298. this._direction = from < to ? 1 : -1;
  12299. this.cellIndex = from;
  12300. this._time = 0;
  12301. };
  12302. Sprite.prototype.stopAnimation = function () {
  12303. this._animationStarted = false;
  12304. };
  12305. Sprite.prototype._animate = function (deltaTime) {
  12306. if (!this._animationStarted)
  12307. return;
  12308. this._time += deltaTime;
  12309. if (this._time > this._delay) {
  12310. this._time = this._time % this._delay;
  12311. this.cellIndex += this._direction;
  12312. if (this.cellIndex == this._toIndex) {
  12313. if (this._loopAnimation) {
  12314. this.cellIndex = this._fromIndex;
  12315. } else {
  12316. this._animationStarted = false;
  12317. if (this.disposeWhenFinishedAnimating) {
  12318. this.dispose();
  12319. }
  12320. }
  12321. }
  12322. }
  12323. };
  12324. Sprite.prototype.dispose = function () {
  12325. for (var i = 0; i < this._manager.sprites.length; i++) {
  12326. if (this._manager.sprites[i] == this) {
  12327. this._manager.sprites.splice(i, 1);
  12328. }
  12329. }
  12330. };
  12331. return Sprite;
  12332. })();
  12333. BABYLON.Sprite = Sprite;
  12334. })(BABYLON || (BABYLON = {}));
  12335. var BABYLON;
  12336. (function (BABYLON) {
  12337. var Layer = (function () {
  12338. function Layer(name, imgUrl, scene, isBackground, color) {
  12339. this.name = name;
  12340. this._vertexDeclaration = [2];
  12341. this._vertexStrideSize = 2 * 4;
  12342. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  12343. this.isBackground = isBackground === undefined ? true : isBackground;
  12344. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  12345. this._scene = scene;
  12346. this._scene.layers.push(this);
  12347. var vertices = [];
  12348. vertices.push(1, 1);
  12349. vertices.push(-1, 1);
  12350. vertices.push(-1, -1);
  12351. vertices.push(1, -1);
  12352. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12353. var indices = [];
  12354. indices.push(0);
  12355. indices.push(1);
  12356. indices.push(2);
  12357. indices.push(0);
  12358. indices.push(2);
  12359. indices.push(3);
  12360. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12361. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  12362. }
  12363. Layer.prototype.render = function () {
  12364. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  12365. return;
  12366. var engine = this._scene.getEngine();
  12367. engine.enableEffect(this._effect);
  12368. engine.setState(false);
  12369. this._effect.setTexture("textureSampler", this.texture);
  12370. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  12371. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  12372. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12373. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12374. engine.draw(true, 0, 6);
  12375. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12376. };
  12377. Layer.prototype.dispose = function () {
  12378. if (this._vertexBuffer) {
  12379. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12380. this._vertexBuffer = null;
  12381. }
  12382. if (this._indexBuffer) {
  12383. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12384. this._indexBuffer = null;
  12385. }
  12386. if (this.texture) {
  12387. this.texture.dispose();
  12388. this.texture = null;
  12389. }
  12390. var index = this._scene.layers.indexOf(this);
  12391. this._scene.layers.splice(index, 1);
  12392. if (this.onDispose) {
  12393. this.onDispose();
  12394. }
  12395. };
  12396. return Layer;
  12397. })();
  12398. BABYLON.Layer = Layer;
  12399. })(BABYLON || (BABYLON = {}));
  12400. var BABYLON;
  12401. (function (BABYLON) {
  12402. var Particle = (function () {
  12403. function Particle() {
  12404. this.position = BABYLON.Vector3.Zero();
  12405. this.direction = BABYLON.Vector3.Zero();
  12406. this.color = new BABYLON.Color4(0, 0, 0, 0);
  12407. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  12408. this.lifeTime = 1.0;
  12409. this.age = 0;
  12410. this.size = 0;
  12411. this.angle = 0;
  12412. this.angularSpeed = 0;
  12413. }
  12414. return Particle;
  12415. })();
  12416. BABYLON.Particle = Particle;
  12417. })(BABYLON || (BABYLON = {}));
  12418. var BABYLON;
  12419. (function (BABYLON) {
  12420. var randomNumber = function (min, max) {
  12421. if (min == max) {
  12422. return (min);
  12423. }
  12424. var random = Math.random();
  12425. return ((random * (max - min)) + min);
  12426. };
  12427. var ParticleSystem = (function () {
  12428. function ParticleSystem(name, capacity, scene, customEffect) {
  12429. var _this = this;
  12430. this.name = name;
  12431. this.renderingGroupId = 0;
  12432. this.emitter = null;
  12433. this.emitRate = 10;
  12434. this.manualEmitCount = -1;
  12435. this.updateSpeed = 0.01;
  12436. this.targetStopDuration = 0;
  12437. this.disposeOnStop = false;
  12438. this.minEmitPower = 1;
  12439. this.maxEmitPower = 1;
  12440. this.minLifeTime = 1;
  12441. this.maxLifeTime = 1;
  12442. this.minSize = 1;
  12443. this.maxSize = 1;
  12444. this.minAngularSpeed = 0;
  12445. this.maxAngularSpeed = 0;
  12446. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  12447. this.forceDepthWrite = false;
  12448. this.gravity = BABYLON.Vector3.Zero();
  12449. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  12450. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  12451. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  12452. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  12453. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12454. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12455. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  12456. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12457. this.particles = new Array();
  12458. this._vertexDeclaration = [3, 4, 4];
  12459. this._vertexStrideSize = 11 * 4;
  12460. this._stockParticles = new Array();
  12461. this._newPartsExcess = 0;
  12462. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  12463. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  12464. this._scaledDirection = BABYLON.Vector3.Zero();
  12465. this._scaledGravity = BABYLON.Vector3.Zero();
  12466. this._currentRenderId = -1;
  12467. this._started = false;
  12468. this._stopped = false;
  12469. this._actualFrame = 0;
  12470. this.id = name;
  12471. this._capacity = capacity;
  12472. this._scene = scene;
  12473. this._customEffect = customEffect;
  12474. scene.particleSystems.push(this);
  12475. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  12476. var indices = [];
  12477. var index = 0;
  12478. for (var count = 0; count < capacity; count++) {
  12479. indices.push(index);
  12480. indices.push(index + 1);
  12481. indices.push(index + 2);
  12482. indices.push(index);
  12483. indices.push(index + 2);
  12484. indices.push(index + 3);
  12485. index += 4;
  12486. }
  12487. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12488. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  12489. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  12490. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  12491. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  12492. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  12493. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  12494. };
  12495. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  12496. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  12497. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  12498. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  12499. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  12500. };
  12501. }
  12502. ParticleSystem.prototype.getCapacity = function () {
  12503. return this._capacity;
  12504. };
  12505. ParticleSystem.prototype.isAlive = function () {
  12506. return this._alive;
  12507. };
  12508. ParticleSystem.prototype.isStarted = function () {
  12509. return this._started;
  12510. };
  12511. ParticleSystem.prototype.start = function () {
  12512. this._started = true;
  12513. this._stopped = false;
  12514. this._actualFrame = 0;
  12515. };
  12516. ParticleSystem.prototype.stop = function () {
  12517. this._stopped = true;
  12518. };
  12519. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  12520. var offset = index * 11;
  12521. this._vertices[offset] = particle.position.x;
  12522. this._vertices[offset + 1] = particle.position.y;
  12523. this._vertices[offset + 2] = particle.position.z;
  12524. this._vertices[offset + 3] = particle.color.r;
  12525. this._vertices[offset + 4] = particle.color.g;
  12526. this._vertices[offset + 5] = particle.color.b;
  12527. this._vertices[offset + 6] = particle.color.a;
  12528. this._vertices[offset + 7] = particle.angle;
  12529. this._vertices[offset + 8] = particle.size;
  12530. this._vertices[offset + 9] = offsetX;
  12531. this._vertices[offset + 10] = offsetY;
  12532. };
  12533. ParticleSystem.prototype._update = function (newParticles) {
  12534. this._alive = this.particles.length > 0;
  12535. for (var index = 0; index < this.particles.length; index++) {
  12536. var particle = this.particles[index];
  12537. particle.age += this._scaledUpdateSpeed;
  12538. if (particle.age >= particle.lifeTime) {
  12539. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  12540. index--;
  12541. continue;
  12542. } else {
  12543. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  12544. particle.color.addInPlace(this._scaledColorStep);
  12545. if (particle.color.a < 0)
  12546. particle.color.a = 0;
  12547. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  12548. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  12549. particle.position.addInPlace(this._scaledDirection);
  12550. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  12551. particle.direction.addInPlace(this._scaledGravity);
  12552. }
  12553. }
  12554. var worldMatrix;
  12555. if (this.emitter.position) {
  12556. worldMatrix = this.emitter.getWorldMatrix();
  12557. } else {
  12558. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  12559. }
  12560. for (index = 0; index < newParticles; index++) {
  12561. if (this.particles.length == this._capacity) {
  12562. break;
  12563. }
  12564. if (this._stockParticles.length !== 0) {
  12565. particle = this._stockParticles.pop();
  12566. particle.age = 0;
  12567. } else {
  12568. particle = new BABYLON.Particle();
  12569. }
  12570. this.particles.push(particle);
  12571. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  12572. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  12573. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  12574. particle.size = randomNumber(this.minSize, this.maxSize);
  12575. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  12576. this.startPositionFunction(worldMatrix, particle.position);
  12577. var step = randomNumber(0, 1.0);
  12578. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  12579. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  12580. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  12581. }
  12582. };
  12583. ParticleSystem.prototype._getEffect = function () {
  12584. if (this._customEffect) {
  12585. return this._customEffect;
  12586. }
  12587. ;
  12588. var defines = [];
  12589. if (this._scene.clipPlane) {
  12590. defines.push("#define CLIPPLANE");
  12591. }
  12592. var join = defines.join("\n");
  12593. if (this._cachedDefines != join) {
  12594. this._cachedDefines = join;
  12595. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  12596. }
  12597. return this._effect;
  12598. };
  12599. ParticleSystem.prototype.animate = function () {
  12600. if (!this._started)
  12601. return;
  12602. var effect = this._getEffect();
  12603. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  12604. return;
  12605. if (this._currentRenderId === this._scene.getRenderId()) {
  12606. return;
  12607. }
  12608. this._currentRenderId = this._scene.getRenderId();
  12609. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  12610. var emitCout;
  12611. if (this.manualEmitCount > -1) {
  12612. emitCout = this.manualEmitCount;
  12613. this.manualEmitCount = 0;
  12614. } else {
  12615. emitCout = this.emitRate;
  12616. }
  12617. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  12618. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  12619. if (this._newPartsExcess > 1.0) {
  12620. newParticles += this._newPartsExcess >> 0;
  12621. this._newPartsExcess -= this._newPartsExcess >> 0;
  12622. }
  12623. this._alive = false;
  12624. if (!this._stopped) {
  12625. this._actualFrame += this._scaledUpdateSpeed;
  12626. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  12627. this.stop();
  12628. } else {
  12629. newParticles = 0;
  12630. }
  12631. this._update(newParticles);
  12632. if (this._stopped) {
  12633. if (!this._alive) {
  12634. this._started = false;
  12635. if (this.disposeOnStop) {
  12636. this._scene._toBeDisposed.push(this);
  12637. }
  12638. }
  12639. }
  12640. var offset = 0;
  12641. for (var index = 0; index < this.particles.length; index++) {
  12642. var particle = this.particles[index];
  12643. this._appendParticleVertex(offset++, particle, 0, 0);
  12644. this._appendParticleVertex(offset++, particle, 1, 0);
  12645. this._appendParticleVertex(offset++, particle, 1, 1);
  12646. this._appendParticleVertex(offset++, particle, 0, 1);
  12647. }
  12648. var engine = this._scene.getEngine();
  12649. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  12650. };
  12651. ParticleSystem.prototype.render = function () {
  12652. var effect = this._getEffect();
  12653. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  12654. return 0;
  12655. var engine = this._scene.getEngine();
  12656. engine.enableEffect(effect);
  12657. var viewMatrix = this._scene.getViewMatrix();
  12658. effect.setTexture("diffuseSampler", this.particleTexture);
  12659. effect.setMatrix("view", viewMatrix);
  12660. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  12661. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  12662. if (this._scene.clipPlane) {
  12663. var clipPlane = this._scene.clipPlane;
  12664. var invView = viewMatrix.clone();
  12665. invView.invert();
  12666. effect.setMatrix("invView", invView);
  12667. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  12668. }
  12669. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12670. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  12671. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  12672. } else {
  12673. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12674. }
  12675. if (this.forceDepthWrite) {
  12676. engine.setDepthWrite(true);
  12677. }
  12678. engine.draw(true, 0, this.particles.length * 6);
  12679. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12680. return this.particles.length;
  12681. };
  12682. ParticleSystem.prototype.dispose = function () {
  12683. if (this._vertexBuffer) {
  12684. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12685. this._vertexBuffer = null;
  12686. }
  12687. if (this._indexBuffer) {
  12688. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12689. this._indexBuffer = null;
  12690. }
  12691. if (this.particleTexture) {
  12692. this.particleTexture.dispose();
  12693. this.particleTexture = null;
  12694. }
  12695. var index = this._scene.particleSystems.indexOf(this);
  12696. this._scene.particleSystems.splice(index, 1);
  12697. if (this.onDispose) {
  12698. this.onDispose();
  12699. }
  12700. };
  12701. ParticleSystem.prototype.clone = function (name, newEmitter) {
  12702. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  12703. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  12704. if (newEmitter === undefined) {
  12705. newEmitter = this.emitter;
  12706. }
  12707. result.emitter = newEmitter;
  12708. if (this.particleTexture) {
  12709. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  12710. }
  12711. result.start();
  12712. return result;
  12713. };
  12714. ParticleSystem.BLENDMODE_ONEONE = 0;
  12715. ParticleSystem.BLENDMODE_STANDARD = 1;
  12716. return ParticleSystem;
  12717. })();
  12718. BABYLON.ParticleSystem = ParticleSystem;
  12719. })(BABYLON || (BABYLON = {}));
  12720. var BABYLON;
  12721. (function (BABYLON) {
  12722. var Animation = (function () {
  12723. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  12724. this.name = name;
  12725. this.targetProperty = targetProperty;
  12726. this.framePerSecond = framePerSecond;
  12727. this.dataType = dataType;
  12728. this.loopMode = loopMode;
  12729. this._offsetsCache = {};
  12730. this._highLimitsCache = {};
  12731. this._stopped = false;
  12732. this.targetPropertyPath = targetProperty.split(".");
  12733. this.dataType = dataType;
  12734. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  12735. }
  12736. Animation.prototype.isStopped = function () {
  12737. return this._stopped;
  12738. };
  12739. Animation.prototype.getKeys = function () {
  12740. return this._keys;
  12741. };
  12742. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  12743. return startValue + (endValue - startValue) * gradient;
  12744. };
  12745. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  12746. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  12747. };
  12748. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  12749. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  12750. };
  12751. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  12752. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  12753. };
  12754. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  12755. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  12756. };
  12757. Animation.prototype.clone = function () {
  12758. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  12759. clone.setKeys(this._keys);
  12760. return clone;
  12761. };
  12762. Animation.prototype.setKeys = function (values) {
  12763. this._keys = values.slice(0);
  12764. this._offsetsCache = {};
  12765. this._highLimitsCache = {};
  12766. };
  12767. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  12768. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  12769. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  12770. }
  12771. this.currentFrame = currentFrame;
  12772. for (var key = 0; key < this._keys.length; key++) {
  12773. if (this._keys[key + 1].frame >= currentFrame) {
  12774. var startValue = this._keys[key].value;
  12775. var endValue = this._keys[key + 1].value;
  12776. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  12777. switch (this.dataType) {
  12778. case Animation.ANIMATIONTYPE_FLOAT:
  12779. switch (loopMode) {
  12780. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12781. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12782. return this.floatInterpolateFunction(startValue, endValue, gradient);
  12783. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12784. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  12785. }
  12786. break;
  12787. case Animation.ANIMATIONTYPE_QUATERNION:
  12788. var quaternion = null;
  12789. switch (loopMode) {
  12790. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12791. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12792. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  12793. break;
  12794. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12795. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12796. break;
  12797. }
  12798. return quaternion;
  12799. case Animation.ANIMATIONTYPE_VECTOR3:
  12800. switch (loopMode) {
  12801. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12802. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12803. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  12804. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12805. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12806. }
  12807. case Animation.ANIMATIONTYPE_VECTOR2:
  12808. switch (loopMode) {
  12809. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12810. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12811. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  12812. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12813. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12814. }
  12815. case Animation.ANIMATIONTYPE_COLOR3:
  12816. switch (loopMode) {
  12817. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12818. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12819. return this.color3InterpolateFunction(startValue, endValue, gradient);
  12820. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12821. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12822. }
  12823. case Animation.ANIMATIONTYPE_MATRIX:
  12824. switch (loopMode) {
  12825. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12826. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12827. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12828. return startValue;
  12829. }
  12830. default:
  12831. break;
  12832. }
  12833. break;
  12834. }
  12835. }
  12836. return this._keys[this._keys.length - 1].value;
  12837. };
  12838. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  12839. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  12840. this._stopped = true;
  12841. return false;
  12842. }
  12843. var returnValue = true;
  12844. if (this._keys[0].frame != 0) {
  12845. var newKey = {
  12846. frame: 0,
  12847. value: this._keys[0].value
  12848. };
  12849. this._keys.splice(0, 0, newKey);
  12850. }
  12851. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  12852. from = this._keys[0].frame;
  12853. }
  12854. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  12855. to = this._keys[this._keys.length - 1].frame;
  12856. }
  12857. var range = to - from;
  12858. var offsetValue;
  12859. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  12860. if (ratio > range && !loop) {
  12861. returnValue = false;
  12862. highLimitValue = this._keys[this._keys.length - 1].value;
  12863. } else {
  12864. var highLimitValue = 0;
  12865. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  12866. var keyOffset = to.toString() + from.toString();
  12867. if (!this._offsetsCache[keyOffset]) {
  12868. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  12869. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  12870. switch (this.dataType) {
  12871. case Animation.ANIMATIONTYPE_FLOAT:
  12872. this._offsetsCache[keyOffset] = toValue - fromValue;
  12873. break;
  12874. case Animation.ANIMATIONTYPE_QUATERNION:
  12875. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12876. break;
  12877. case Animation.ANIMATIONTYPE_VECTOR3:
  12878. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12879. case Animation.ANIMATIONTYPE_VECTOR2:
  12880. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12881. case Animation.ANIMATIONTYPE_COLOR3:
  12882. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12883. default:
  12884. break;
  12885. }
  12886. this._highLimitsCache[keyOffset] = toValue;
  12887. }
  12888. highLimitValue = this._highLimitsCache[keyOffset];
  12889. offsetValue = this._offsetsCache[keyOffset];
  12890. }
  12891. }
  12892. if (offsetValue === undefined) {
  12893. switch (this.dataType) {
  12894. case Animation.ANIMATIONTYPE_FLOAT:
  12895. offsetValue = 0;
  12896. break;
  12897. case Animation.ANIMATIONTYPE_QUATERNION:
  12898. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  12899. break;
  12900. case Animation.ANIMATIONTYPE_VECTOR3:
  12901. offsetValue = BABYLON.Vector3.Zero();
  12902. break;
  12903. case Animation.ANIMATIONTYPE_VECTOR2:
  12904. offsetValue = BABYLON.Vector2.Zero();
  12905. break;
  12906. case Animation.ANIMATIONTYPE_COLOR3:
  12907. offsetValue = BABYLON.Color3.Black();
  12908. }
  12909. }
  12910. var repeatCount = (ratio / range) >> 0;
  12911. var currentFrame = returnValue ? from + ratio % range : to;
  12912. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  12913. if (this.targetPropertyPath.length > 1) {
  12914. var property = this._target[this.targetPropertyPath[0]];
  12915. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  12916. property = property[this.targetPropertyPath[index]];
  12917. }
  12918. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  12919. } else {
  12920. this._target[this.targetPropertyPath[0]] = currentValue;
  12921. }
  12922. if (this._target.markAsDirty) {
  12923. this._target.markAsDirty(this.targetProperty);
  12924. }
  12925. if (!returnValue) {
  12926. this._stopped = true;
  12927. }
  12928. return returnValue;
  12929. };
  12930. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  12931. get: function () {
  12932. return Animation._ANIMATIONTYPE_FLOAT;
  12933. },
  12934. enumerable: true,
  12935. configurable: true
  12936. });
  12937. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  12938. get: function () {
  12939. return Animation._ANIMATIONTYPE_VECTOR3;
  12940. },
  12941. enumerable: true,
  12942. configurable: true
  12943. });
  12944. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  12945. get: function () {
  12946. return Animation._ANIMATIONTYPE_VECTOR2;
  12947. },
  12948. enumerable: true,
  12949. configurable: true
  12950. });
  12951. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  12952. get: function () {
  12953. return Animation._ANIMATIONTYPE_QUATERNION;
  12954. },
  12955. enumerable: true,
  12956. configurable: true
  12957. });
  12958. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  12959. get: function () {
  12960. return Animation._ANIMATIONTYPE_MATRIX;
  12961. },
  12962. enumerable: true,
  12963. configurable: true
  12964. });
  12965. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  12966. get: function () {
  12967. return Animation._ANIMATIONTYPE_COLOR3;
  12968. },
  12969. enumerable: true,
  12970. configurable: true
  12971. });
  12972. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  12973. get: function () {
  12974. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  12975. },
  12976. enumerable: true,
  12977. configurable: true
  12978. });
  12979. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  12980. get: function () {
  12981. return Animation._ANIMATIONLOOPMODE_CYCLE;
  12982. },
  12983. enumerable: true,
  12984. configurable: true
  12985. });
  12986. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  12987. get: function () {
  12988. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  12989. },
  12990. enumerable: true,
  12991. configurable: true
  12992. });
  12993. Animation._ANIMATIONTYPE_FLOAT = 0;
  12994. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  12995. Animation._ANIMATIONTYPE_QUATERNION = 2;
  12996. Animation._ANIMATIONTYPE_MATRIX = 3;
  12997. Animation._ANIMATIONTYPE_COLOR3 = 4;
  12998. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  12999. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  13000. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  13001. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  13002. return Animation;
  13003. })();
  13004. BABYLON.Animation = Animation;
  13005. })(BABYLON || (BABYLON = {}));
  13006. var BABYLON;
  13007. (function (BABYLON) {
  13008. var Animatable = (function () {
  13009. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  13010. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  13011. if (typeof toFrame === "undefined") { toFrame = 100; }
  13012. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  13013. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  13014. this.target = target;
  13015. this.fromFrame = fromFrame;
  13016. this.toFrame = toFrame;
  13017. this.loopAnimation = loopAnimation;
  13018. this.speedRatio = speedRatio;
  13019. this.onAnimationEnd = onAnimationEnd;
  13020. this._animations = new Array();
  13021. this._paused = false;
  13022. this.animationStarted = false;
  13023. if (animations) {
  13024. this.appendAnimations(target, animations);
  13025. }
  13026. this._scene = scene;
  13027. scene._activeAnimatables.push(this);
  13028. }
  13029. Animatable.prototype.appendAnimations = function (target, animations) {
  13030. for (var index = 0; index < animations.length; index++) {
  13031. var animation = animations[index];
  13032. animation._target = target;
  13033. this._animations.push(animation);
  13034. }
  13035. };
  13036. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  13037. var animations = this._animations;
  13038. for (var index = 0; index < animations.length; index++) {
  13039. if (animations[index].targetProperty === property) {
  13040. return animations[index];
  13041. }
  13042. }
  13043. return null;
  13044. };
  13045. Animatable.prototype.pause = function () {
  13046. if (this._paused) {
  13047. return;
  13048. }
  13049. this._paused = true;
  13050. };
  13051. Animatable.prototype.restart = function () {
  13052. this._paused = false;
  13053. };
  13054. Animatable.prototype.stop = function () {
  13055. var index = this._scene._activeAnimatables.indexOf(this);
  13056. if (index > -1) {
  13057. this._scene._activeAnimatables.splice(index, 1);
  13058. }
  13059. if (this.onAnimationEnd) {
  13060. this.onAnimationEnd();
  13061. }
  13062. };
  13063. Animatable.prototype._animate = function (delay) {
  13064. if (this._paused) {
  13065. if (!this._pausedDelay) {
  13066. this._pausedDelay = delay;
  13067. }
  13068. return true;
  13069. }
  13070. if (!this._localDelayOffset) {
  13071. this._localDelayOffset = delay;
  13072. } else if (this._pausedDelay) {
  13073. this._localDelayOffset += delay - this._pausedDelay;
  13074. this._pausedDelay = null;
  13075. }
  13076. var running = false;
  13077. var animations = this._animations;
  13078. for (var index = 0; index < animations.length; index++) {
  13079. var animation = animations[index];
  13080. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  13081. running = running || isRunning;
  13082. }
  13083. if (!running && this.onAnimationEnd) {
  13084. this.onAnimationEnd();
  13085. }
  13086. return running;
  13087. };
  13088. return Animatable;
  13089. })();
  13090. BABYLON.Animatable = Animatable;
  13091. })(BABYLON || (BABYLON = {}));
  13092. var BABYLON;
  13093. (function (BABYLON) {
  13094. var Octree = (function () {
  13095. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  13096. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  13097. this.maxDepth = maxDepth;
  13098. this.dynamicContent = new Array();
  13099. this._maxBlockCapacity = maxBlockCapacity || 64;
  13100. this._selectionContent = new BABYLON.SmartArray(1024);
  13101. this._creationFunc = creationFunc;
  13102. }
  13103. Octree.prototype.update = function (worldMin, worldMax, entries) {
  13104. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  13105. };
  13106. Octree.prototype.addMesh = function (entry) {
  13107. for (var index = 0; index < this.blocks.length; index++) {
  13108. var block = this.blocks[index];
  13109. block.addEntry(entry);
  13110. }
  13111. };
  13112. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  13113. this._selectionContent.reset();
  13114. for (var index = 0; index < this.blocks.length; index++) {
  13115. var block = this.blocks[index];
  13116. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  13117. }
  13118. if (allowDuplicate) {
  13119. this._selectionContent.concat(this.dynamicContent);
  13120. } else {
  13121. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  13122. }
  13123. return this._selectionContent;
  13124. };
  13125. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  13126. this._selectionContent.reset();
  13127. for (var index = 0; index < this.blocks.length; index++) {
  13128. var block = this.blocks[index];
  13129. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  13130. }
  13131. if (allowDuplicate) {
  13132. this._selectionContent.concat(this.dynamicContent);
  13133. } else {
  13134. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  13135. }
  13136. return this._selectionContent;
  13137. };
  13138. Octree.prototype.intersectsRay = function (ray) {
  13139. this._selectionContent.reset();
  13140. for (var index = 0; index < this.blocks.length; index++) {
  13141. var block = this.blocks[index];
  13142. block.intersectsRay(ray, this._selectionContent);
  13143. }
  13144. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  13145. return this._selectionContent;
  13146. };
  13147. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  13148. target.blocks = new Array();
  13149. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  13150. for (var x = 0; x < 2; x++) {
  13151. for (var y = 0; y < 2; y++) {
  13152. for (var z = 0; z < 2; z++) {
  13153. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  13154. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  13155. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  13156. block.addEntries(entries);
  13157. target.blocks.push(block);
  13158. }
  13159. }
  13160. }
  13161. };
  13162. Octree.CreationFuncForMeshes = function (entry, block) {
  13163. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  13164. block.entries.push(entry);
  13165. }
  13166. };
  13167. Octree.CreationFuncForSubMeshes = function (entry, block) {
  13168. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  13169. block.entries.push(entry);
  13170. }
  13171. };
  13172. return Octree;
  13173. })();
  13174. BABYLON.Octree = Octree;
  13175. })(BABYLON || (BABYLON = {}));
  13176. var BABYLON;
  13177. (function (BABYLON) {
  13178. var OctreeBlock = (function () {
  13179. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  13180. this.entries = new Array();
  13181. this._boundingVectors = new Array();
  13182. this._capacity = capacity;
  13183. this._depth = depth;
  13184. this._maxDepth = maxDepth;
  13185. this._creationFunc = creationFunc;
  13186. this._minPoint = minPoint;
  13187. this._maxPoint = maxPoint;
  13188. this._boundingVectors.push(minPoint.clone());
  13189. this._boundingVectors.push(maxPoint.clone());
  13190. this._boundingVectors.push(minPoint.clone());
  13191. this._boundingVectors[2].x = maxPoint.x;
  13192. this._boundingVectors.push(minPoint.clone());
  13193. this._boundingVectors[3].y = maxPoint.y;
  13194. this._boundingVectors.push(minPoint.clone());
  13195. this._boundingVectors[4].z = maxPoint.z;
  13196. this._boundingVectors.push(maxPoint.clone());
  13197. this._boundingVectors[5].z = minPoint.z;
  13198. this._boundingVectors.push(maxPoint.clone());
  13199. this._boundingVectors[6].x = minPoint.x;
  13200. this._boundingVectors.push(maxPoint.clone());
  13201. this._boundingVectors[7].y = minPoint.y;
  13202. }
  13203. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  13204. get: function () {
  13205. return this._capacity;
  13206. },
  13207. enumerable: true,
  13208. configurable: true
  13209. });
  13210. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  13211. get: function () {
  13212. return this._minPoint;
  13213. },
  13214. enumerable: true,
  13215. configurable: true
  13216. });
  13217. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  13218. get: function () {
  13219. return this._maxPoint;
  13220. },
  13221. enumerable: true,
  13222. configurable: true
  13223. });
  13224. OctreeBlock.prototype.addEntry = function (entry) {
  13225. if (this.blocks) {
  13226. for (var index = 0; index < this.blocks.length; index++) {
  13227. var block = this.blocks[index];
  13228. block.addEntry(entry);
  13229. }
  13230. return;
  13231. }
  13232. this._creationFunc(entry, this);
  13233. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  13234. this.createInnerBlocks();
  13235. }
  13236. };
  13237. OctreeBlock.prototype.addEntries = function (entries) {
  13238. for (var index = 0; index < entries.length; index++) {
  13239. var mesh = entries[index];
  13240. this.addEntry(mesh);
  13241. }
  13242. };
  13243. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  13244. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  13245. if (this.blocks) {
  13246. for (var index = 0; index < this.blocks.length; index++) {
  13247. var block = this.blocks[index];
  13248. block.select(frustumPlanes, selection, allowDuplicate);
  13249. }
  13250. return;
  13251. }
  13252. if (allowDuplicate) {
  13253. selection.concat(this.entries);
  13254. } else {
  13255. selection.concatWithNoDuplicate(this.entries);
  13256. }
  13257. }
  13258. };
  13259. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  13260. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  13261. if (this.blocks) {
  13262. for (var index = 0; index < this.blocks.length; index++) {
  13263. var block = this.blocks[index];
  13264. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  13265. }
  13266. return;
  13267. }
  13268. if (allowDuplicate) {
  13269. selection.concat(this.entries);
  13270. } else {
  13271. selection.concatWithNoDuplicate(this.entries);
  13272. }
  13273. }
  13274. };
  13275. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  13276. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  13277. if (this.blocks) {
  13278. for (var index = 0; index < this.blocks.length; index++) {
  13279. var block = this.blocks[index];
  13280. block.intersectsRay(ray, selection);
  13281. }
  13282. return;
  13283. }
  13284. selection.concatWithNoDuplicate(this.entries);
  13285. }
  13286. };
  13287. OctreeBlock.prototype.createInnerBlocks = function () {
  13288. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  13289. };
  13290. return OctreeBlock;
  13291. })();
  13292. BABYLON.OctreeBlock = OctreeBlock;
  13293. })(BABYLON || (BABYLON = {}));
  13294. var BABYLON;
  13295. (function (BABYLON) {
  13296. var Bone = (function () {
  13297. function Bone(name, skeleton, parentBone, matrix) {
  13298. this.name = name;
  13299. this.children = new Array();
  13300. this.animations = new Array();
  13301. this._worldTransform = new BABYLON.Matrix();
  13302. this._absoluteTransform = new BABYLON.Matrix();
  13303. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  13304. this._skeleton = skeleton;
  13305. this._matrix = matrix;
  13306. this._baseMatrix = matrix;
  13307. skeleton.bones.push(this);
  13308. if (parentBone) {
  13309. this._parent = parentBone;
  13310. parentBone.children.push(this);
  13311. } else {
  13312. this._parent = null;
  13313. }
  13314. this._updateDifferenceMatrix();
  13315. }
  13316. Bone.prototype.getParent = function () {
  13317. return this._parent;
  13318. };
  13319. Bone.prototype.getLocalMatrix = function () {
  13320. return this._matrix;
  13321. };
  13322. Bone.prototype.getBaseMatrix = function () {
  13323. return this._baseMatrix;
  13324. };
  13325. Bone.prototype.getWorldMatrix = function () {
  13326. return this._worldTransform;
  13327. };
  13328. Bone.prototype.getInvertedAbsoluteTransform = function () {
  13329. return this._invertedAbsoluteTransform;
  13330. };
  13331. Bone.prototype.getAbsoluteMatrix = function () {
  13332. var matrix = this._matrix.clone();
  13333. var parent = this._parent;
  13334. while (parent) {
  13335. matrix = matrix.multiply(parent.getLocalMatrix());
  13336. parent = parent.getParent();
  13337. }
  13338. return matrix;
  13339. };
  13340. Bone.prototype.updateMatrix = function (matrix) {
  13341. this._matrix = matrix;
  13342. this._skeleton._markAsDirty();
  13343. this._updateDifferenceMatrix();
  13344. };
  13345. Bone.prototype._updateDifferenceMatrix = function () {
  13346. if (this._parent) {
  13347. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  13348. } else {
  13349. this._absoluteTransform.copyFrom(this._matrix);
  13350. }
  13351. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  13352. for (var index = 0; index < this.children.length; index++) {
  13353. this.children[index]._updateDifferenceMatrix();
  13354. }
  13355. };
  13356. Bone.prototype.markAsDirty = function () {
  13357. this._skeleton._markAsDirty();
  13358. };
  13359. return Bone;
  13360. })();
  13361. BABYLON.Bone = Bone;
  13362. })(BABYLON || (BABYLON = {}));
  13363. var BABYLON;
  13364. (function (BABYLON) {
  13365. var Skeleton = (function () {
  13366. function Skeleton(name, id, scene) {
  13367. this.name = name;
  13368. this.id = id;
  13369. this.bones = new Array();
  13370. this._isDirty = true;
  13371. this._identity = BABYLON.Matrix.Identity();
  13372. this.bones = [];
  13373. this._scene = scene;
  13374. scene.skeletons.push(this);
  13375. }
  13376. Skeleton.prototype.getTransformMatrices = function () {
  13377. return this._transformMatrices;
  13378. };
  13379. Skeleton.prototype._markAsDirty = function () {
  13380. this._isDirty = true;
  13381. };
  13382. Skeleton.prototype.prepare = function () {
  13383. if (!this._isDirty) {
  13384. return;
  13385. }
  13386. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  13387. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  13388. }
  13389. for (var index = 0; index < this.bones.length; index++) {
  13390. var bone = this.bones[index];
  13391. var parentBone = bone.getParent();
  13392. if (parentBone) {
  13393. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  13394. } else {
  13395. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  13396. }
  13397. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  13398. }
  13399. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  13400. this._isDirty = false;
  13401. };
  13402. Skeleton.prototype.getAnimatables = function () {
  13403. if (!this._animatables || this._animatables.length != this.bones.length) {
  13404. this._animatables = [];
  13405. for (var index = 0; index < this.bones.length; index++) {
  13406. this._animatables.push(this.bones[index]);
  13407. }
  13408. }
  13409. return this._animatables;
  13410. };
  13411. Skeleton.prototype.clone = function (name, id) {
  13412. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  13413. for (var index = 0; index < this.bones.length; index++) {
  13414. var source = this.bones[index];
  13415. var parentBone = null;
  13416. if (source.getParent()) {
  13417. var parentIndex = this.bones.indexOf(source.getParent());
  13418. parentBone = result.bones[parentIndex];
  13419. }
  13420. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  13421. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  13422. }
  13423. return result;
  13424. };
  13425. return Skeleton;
  13426. })();
  13427. BABYLON.Skeleton = Skeleton;
  13428. })(BABYLON || (BABYLON = {}));
  13429. var BABYLON;
  13430. (function (BABYLON) {
  13431. var PostProcess = (function () {
  13432. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  13433. this.name = name;
  13434. this.width = -1;
  13435. this.height = -1;
  13436. this._reusable = false;
  13437. this._textures = new BABYLON.SmartArray(2);
  13438. this._currentRenderTextureInd = 0;
  13439. if (camera != null) {
  13440. this._camera = camera;
  13441. this._scene = camera.getScene();
  13442. camera.attachPostProcess(this);
  13443. this._engine = this._scene.getEngine();
  13444. } else {
  13445. this._engine = engine;
  13446. }
  13447. this._renderRatio = ratio;
  13448. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13449. this._reusable = reusable || false;
  13450. samplers = samplers || [];
  13451. samplers.push("textureSampler");
  13452. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  13453. }
  13454. PostProcess.prototype.isReusable = function () {
  13455. return this._reusable;
  13456. };
  13457. PostProcess.prototype.activate = function (camera, sourceTexture) {
  13458. camera = camera || this._camera;
  13459. var scene = camera.getScene();
  13460. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  13461. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  13462. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  13463. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  13464. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  13465. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  13466. if (this._textures.length > 0) {
  13467. for (var i = 0; i < this._textures.length; i++) {
  13468. this._engine._releaseTexture(this._textures.data[i]);
  13469. }
  13470. this._textures.reset();
  13471. }
  13472. this.width = desiredWidth;
  13473. this.height = desiredHeight;
  13474. 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 }));
  13475. if (this._reusable) {
  13476. 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 }));
  13477. }
  13478. if (this.onSizeChanged) {
  13479. this.onSizeChanged();
  13480. }
  13481. }
  13482. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  13483. if (this.onActivate) {
  13484. this.onActivate(camera);
  13485. }
  13486. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  13487. if (this._reusable) {
  13488. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  13489. }
  13490. };
  13491. PostProcess.prototype.apply = function () {
  13492. if (!this._effect.isReady())
  13493. return null;
  13494. this._engine.enableEffect(this._effect);
  13495. this._engine.setState(false);
  13496. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13497. this._engine.setDepthBuffer(false);
  13498. this._engine.setDepthWrite(false);
  13499. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  13500. if (this.onApply) {
  13501. this.onApply(this._effect);
  13502. }
  13503. return this._effect;
  13504. };
  13505. PostProcess.prototype.dispose = function (camera) {
  13506. camera = camera || this._camera;
  13507. if (this._textures.length > 0) {
  13508. for (var i = 0; i < this._textures.length; i++) {
  13509. this._engine._releaseTexture(this._textures.data[i]);
  13510. }
  13511. this._textures.reset();
  13512. }
  13513. camera.detachPostProcess(this);
  13514. var index = camera._postProcesses.indexOf(this);
  13515. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  13516. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  13517. }
  13518. };
  13519. return PostProcess;
  13520. })();
  13521. BABYLON.PostProcess = PostProcess;
  13522. })(BABYLON || (BABYLON = {}));
  13523. var BABYLON;
  13524. (function (BABYLON) {
  13525. var PostProcessManager = (function () {
  13526. function PostProcessManager(scene) {
  13527. this._vertexDeclaration = [2];
  13528. this._vertexStrideSize = 2 * 4;
  13529. this._scene = scene;
  13530. var vertices = [];
  13531. vertices.push(1, 1);
  13532. vertices.push(-1, 1);
  13533. vertices.push(-1, -1);
  13534. vertices.push(1, -1);
  13535. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13536. var indices = [];
  13537. indices.push(0);
  13538. indices.push(1);
  13539. indices.push(2);
  13540. indices.push(0);
  13541. indices.push(2);
  13542. indices.push(3);
  13543. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13544. }
  13545. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  13546. var postProcesses = this._scene.activeCamera._postProcesses;
  13547. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  13548. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  13549. return false;
  13550. }
  13551. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  13552. return true;
  13553. };
  13554. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  13555. var postProcesses = this._scene.activeCamera._postProcesses;
  13556. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  13557. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  13558. return;
  13559. }
  13560. var engine = this._scene.getEngine();
  13561. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  13562. if (index < postProcessesTakenIndices.length - 1) {
  13563. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  13564. } else {
  13565. if (targetTexture) {
  13566. engine.bindFramebuffer(targetTexture);
  13567. } else {
  13568. engine.restoreDefaultFramebuffer();
  13569. }
  13570. }
  13571. if (doNotPresent) {
  13572. break;
  13573. }
  13574. var pp = postProcesses[postProcessesTakenIndices[index]];
  13575. var effect = pp.apply();
  13576. if (effect) {
  13577. if (pp.onBeforeRender) {
  13578. pp.onBeforeRender(effect);
  13579. }
  13580. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13581. engine.draw(true, 0, 6);
  13582. }
  13583. }
  13584. engine.setDepthBuffer(true);
  13585. engine.setDepthWrite(true);
  13586. };
  13587. PostProcessManager.prototype.dispose = function () {
  13588. if (this._vertexBuffer) {
  13589. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13590. this._vertexBuffer = null;
  13591. }
  13592. if (this._indexBuffer) {
  13593. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13594. this._indexBuffer = null;
  13595. }
  13596. };
  13597. return PostProcessManager;
  13598. })();
  13599. BABYLON.PostProcessManager = PostProcessManager;
  13600. })(BABYLON || (BABYLON = {}));
  13601. var __extends = this.__extends || function (d, b) {
  13602. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13603. function __() { this.constructor = d; }
  13604. __.prototype = b.prototype;
  13605. d.prototype = new __();
  13606. };
  13607. var BABYLON;
  13608. (function (BABYLON) {
  13609. var PassPostProcess = (function (_super) {
  13610. __extends(PassPostProcess, _super);
  13611. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  13612. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  13613. }
  13614. return PassPostProcess;
  13615. })(BABYLON.PostProcess);
  13616. BABYLON.PassPostProcess = PassPostProcess;
  13617. })(BABYLON || (BABYLON = {}));
  13618. var __extends = this.__extends || function (d, b) {
  13619. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13620. function __() { this.constructor = d; }
  13621. __.prototype = b.prototype;
  13622. d.prototype = new __();
  13623. };
  13624. var BABYLON;
  13625. (function (BABYLON) {
  13626. var BlurPostProcess = (function (_super) {
  13627. __extends(BlurPostProcess, _super);
  13628. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  13629. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  13630. var _this = this;
  13631. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  13632. this.direction = direction;
  13633. this.blurWidth = blurWidth;
  13634. this.onApply = function (effect) {
  13635. effect.setFloat2("screenSize", _this.width, _this.height);
  13636. effect.setVector2("direction", _this.direction);
  13637. effect.setFloat("blurWidth", _this.blurWidth);
  13638. };
  13639. }
  13640. return BlurPostProcess;
  13641. })(BABYLON.PostProcess);
  13642. BABYLON.BlurPostProcess = BlurPostProcess;
  13643. })(BABYLON || (BABYLON = {}));
  13644. var __extends = this.__extends || function (d, b) {
  13645. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13646. function __() { this.constructor = d; }
  13647. __.prototype = b.prototype;
  13648. d.prototype = new __();
  13649. };
  13650. var BABYLON;
  13651. (function (BABYLON) {
  13652. var FilterPostProcess = (function (_super) {
  13653. __extends(FilterPostProcess, _super);
  13654. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  13655. var _this = this;
  13656. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  13657. this.kernelMatrix = kernelMatrix;
  13658. this.onApply = function (effect) {
  13659. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  13660. };
  13661. }
  13662. return FilterPostProcess;
  13663. })(BABYLON.PostProcess);
  13664. BABYLON.FilterPostProcess = FilterPostProcess;
  13665. })(BABYLON || (BABYLON = {}));
  13666. var __extends = this.__extends || function (d, b) {
  13667. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13668. function __() { this.constructor = d; }
  13669. __.prototype = b.prototype;
  13670. d.prototype = new __();
  13671. };
  13672. var BABYLON;
  13673. (function (BABYLON) {
  13674. var RefractionPostProcess = (function (_super) {
  13675. __extends(RefractionPostProcess, _super);
  13676. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  13677. var _this = this;
  13678. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  13679. this.color = color;
  13680. this.depth = depth;
  13681. this.colorLevel = colorLevel;
  13682. this.onActivate = function (cam) {
  13683. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  13684. };
  13685. this.onApply = function (effect) {
  13686. effect.setColor3("baseColor", _this.color);
  13687. effect.setFloat("depth", _this.depth);
  13688. effect.setFloat("colorLevel", _this.colorLevel);
  13689. effect.setTexture("refractionSampler", _this._refRexture);
  13690. };
  13691. }
  13692. RefractionPostProcess.prototype.dispose = function (camera) {
  13693. if (this._refRexture) {
  13694. this._refRexture.dispose();
  13695. }
  13696. _super.prototype.dispose.call(this, camera);
  13697. };
  13698. return RefractionPostProcess;
  13699. })(BABYLON.PostProcess);
  13700. BABYLON.RefractionPostProcess = RefractionPostProcess;
  13701. })(BABYLON || (BABYLON = {}));
  13702. var __extends = this.__extends || function (d, b) {
  13703. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13704. function __() { this.constructor = d; }
  13705. __.prototype = b.prototype;
  13706. d.prototype = new __();
  13707. };
  13708. var BABYLON;
  13709. (function (BABYLON) {
  13710. var BlackAndWhitePostProcess = (function (_super) {
  13711. __extends(BlackAndWhitePostProcess, _super);
  13712. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  13713. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  13714. }
  13715. return BlackAndWhitePostProcess;
  13716. })(BABYLON.PostProcess);
  13717. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  13718. })(BABYLON || (BABYLON = {}));
  13719. var __extends = this.__extends || function (d, b) {
  13720. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13721. function __() { this.constructor = d; }
  13722. __.prototype = b.prototype;
  13723. d.prototype = new __();
  13724. };
  13725. var BABYLON;
  13726. (function (BABYLON) {
  13727. var ConvolutionPostProcess = (function (_super) {
  13728. __extends(ConvolutionPostProcess, _super);
  13729. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  13730. var _this = this;
  13731. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  13732. this.kernel = kernel;
  13733. this.onApply = function (effect) {
  13734. effect.setFloat2("screenSize", _this.width, _this.height);
  13735. effect.setArray("kernel", _this.kernel);
  13736. };
  13737. }
  13738. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  13739. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  13740. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  13741. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  13742. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  13743. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  13744. return ConvolutionPostProcess;
  13745. })(BABYLON.PostProcess);
  13746. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  13747. })(BABYLON || (BABYLON = {}));
  13748. var __extends = this.__extends || function (d, b) {
  13749. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13750. function __() { this.constructor = d; }
  13751. __.prototype = b.prototype;
  13752. d.prototype = new __();
  13753. };
  13754. var BABYLON;
  13755. (function (BABYLON) {
  13756. var FxaaPostProcess = (function (_super) {
  13757. __extends(FxaaPostProcess, _super);
  13758. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  13759. var _this = this;
  13760. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  13761. this.onSizeChanged = function () {
  13762. _this.texelWidth = 1.0 / _this.width;
  13763. _this.texelHeight = 1.0 / _this.height;
  13764. };
  13765. this.onApply = function (effect) {
  13766. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  13767. };
  13768. }
  13769. return FxaaPostProcess;
  13770. })(BABYLON.PostProcess);
  13771. BABYLON.FxaaPostProcess = FxaaPostProcess;
  13772. })(BABYLON || (BABYLON = {}));
  13773. var BABYLON;
  13774. (function (BABYLON) {
  13775. var LensFlare = (function () {
  13776. function LensFlare(size, position, color, imgUrl, system) {
  13777. this.size = size;
  13778. this.position = position;
  13779. this.dispose = function () {
  13780. if (this.texture) {
  13781. this.texture.dispose();
  13782. }
  13783. var index = this._system.lensFlares.indexOf(this);
  13784. this._system.lensFlares.splice(index, 1);
  13785. };
  13786. this.color = color || new BABYLON.Color3(1, 1, 1);
  13787. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  13788. this._system = system;
  13789. system.lensFlares.push(this);
  13790. }
  13791. return LensFlare;
  13792. })();
  13793. BABYLON.LensFlare = LensFlare;
  13794. })(BABYLON || (BABYLON = {}));
  13795. var BABYLON;
  13796. (function (BABYLON) {
  13797. var LensFlareSystem = (function () {
  13798. function LensFlareSystem(name, emitter, scene) {
  13799. this.name = name;
  13800. this.lensFlares = new Array();
  13801. this.borderLimit = 300;
  13802. this._vertexDeclaration = [2];
  13803. this._vertexStrideSize = 2 * 4;
  13804. this._isEnabled = true;
  13805. this._scene = scene;
  13806. this._emitter = emitter;
  13807. scene.lensFlareSystems.push(this);
  13808. this.meshesSelectionPredicate = function (m) {
  13809. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  13810. };
  13811. var vertices = [];
  13812. vertices.push(1, 1);
  13813. vertices.push(-1, 1);
  13814. vertices.push(-1, -1);
  13815. vertices.push(1, -1);
  13816. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13817. var indices = [];
  13818. indices.push(0);
  13819. indices.push(1);
  13820. indices.push(2);
  13821. indices.push(0);
  13822. indices.push(2);
  13823. indices.push(3);
  13824. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13825. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  13826. }
  13827. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  13828. get: function () {
  13829. return this._isEnabled;
  13830. },
  13831. set: function (value) {
  13832. this._isEnabled = value;
  13833. },
  13834. enumerable: true,
  13835. configurable: true
  13836. });
  13837. LensFlareSystem.prototype.getScene = function () {
  13838. return this._scene;
  13839. };
  13840. LensFlareSystem.prototype.getEmitter = function () {
  13841. return this._emitter;
  13842. };
  13843. LensFlareSystem.prototype.getEmitterPosition = function () {
  13844. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  13845. };
  13846. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  13847. var position = this.getEmitterPosition();
  13848. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  13849. this._positionX = position.x;
  13850. this._positionY = position.y;
  13851. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  13852. if (position.z > 0) {
  13853. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  13854. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  13855. return true;
  13856. }
  13857. }
  13858. return false;
  13859. };
  13860. LensFlareSystem.prototype._isVisible = function () {
  13861. if (!this._isEnabled) {
  13862. return false;
  13863. }
  13864. var emitterPosition = this.getEmitterPosition();
  13865. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  13866. var distance = direction.length();
  13867. direction.normalize();
  13868. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  13869. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  13870. return !pickInfo.hit || pickInfo.distance > distance;
  13871. };
  13872. LensFlareSystem.prototype.render = function () {
  13873. if (!this._effect.isReady())
  13874. return false;
  13875. var engine = this._scene.getEngine();
  13876. var viewport = this._scene.activeCamera.viewport;
  13877. var globalViewport = viewport.toGlobal(engine);
  13878. if (!this.computeEffectivePosition(globalViewport)) {
  13879. return false;
  13880. }
  13881. if (!this._isVisible()) {
  13882. return false;
  13883. }
  13884. var awayX;
  13885. var awayY;
  13886. if (this._positionX < this.borderLimit + globalViewport.x) {
  13887. awayX = this.borderLimit + globalViewport.x - this._positionX;
  13888. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  13889. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  13890. } else {
  13891. awayX = 0;
  13892. }
  13893. if (this._positionY < this.borderLimit + globalViewport.y) {
  13894. awayY = this.borderLimit + globalViewport.y - this._positionY;
  13895. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  13896. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  13897. } else {
  13898. awayY = 0;
  13899. }
  13900. var away = (awayX > awayY) ? awayX : awayY;
  13901. if (away > this.borderLimit) {
  13902. away = this.borderLimit;
  13903. }
  13904. var intensity = 1.0 - (away / this.borderLimit);
  13905. if (intensity < 0) {
  13906. return false;
  13907. }
  13908. if (intensity > 1.0) {
  13909. intensity = 1.0;
  13910. }
  13911. var centerX = globalViewport.x + globalViewport.width / 2;
  13912. var centerY = globalViewport.y + globalViewport.height / 2;
  13913. var distX = centerX - this._positionX;
  13914. var distY = centerY - this._positionY;
  13915. engine.enableEffect(this._effect);
  13916. engine.setState(false);
  13917. engine.setDepthBuffer(false);
  13918. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  13919. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13920. for (var index = 0; index < this.lensFlares.length; index++) {
  13921. var flare = this.lensFlares[index];
  13922. var x = centerX - (distX * flare.position);
  13923. var y = centerY - (distY * flare.position);
  13924. var cw = flare.size;
  13925. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  13926. var cx = 2 * (x / globalViewport.width) - 1.0;
  13927. var cy = 1.0 - 2 * (y / globalViewport.height);
  13928. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  13929. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  13930. this._effect.setTexture("textureSampler", flare.texture);
  13931. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  13932. engine.draw(true, 0, 6);
  13933. }
  13934. engine.setDepthBuffer(true);
  13935. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13936. return true;
  13937. };
  13938. LensFlareSystem.prototype.dispose = function () {
  13939. if (this._vertexBuffer) {
  13940. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13941. this._vertexBuffer = null;
  13942. }
  13943. if (this._indexBuffer) {
  13944. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13945. this._indexBuffer = null;
  13946. }
  13947. while (this.lensFlares.length) {
  13948. this.lensFlares[0].dispose();
  13949. }
  13950. var index = this._scene.lensFlareSystems.indexOf(this);
  13951. this._scene.lensFlareSystems.splice(index, 1);
  13952. };
  13953. return LensFlareSystem;
  13954. })();
  13955. BABYLON.LensFlareSystem = LensFlareSystem;
  13956. })(BABYLON || (BABYLON = {}));
  13957. var BABYLON;
  13958. (function (BABYLON) {
  13959. var IntersectionInfo = (function () {
  13960. function IntersectionInfo(bu, bv, distance) {
  13961. this.bu = bu;
  13962. this.bv = bv;
  13963. this.distance = distance;
  13964. this.faceId = 0;
  13965. }
  13966. return IntersectionInfo;
  13967. })();
  13968. BABYLON.IntersectionInfo = IntersectionInfo;
  13969. var PickingInfo = (function () {
  13970. function PickingInfo() {
  13971. this.hit = false;
  13972. this.distance = 0;
  13973. this.pickedPoint = null;
  13974. this.pickedMesh = null;
  13975. this.bu = 0;
  13976. this.bv = 0;
  13977. this.faceId = -1;
  13978. }
  13979. PickingInfo.prototype.getNormal = function () {
  13980. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13981. return null;
  13982. }
  13983. var indices = this.pickedMesh.getIndices();
  13984. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13985. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  13986. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  13987. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  13988. normal0 = normal0.scale(this.bu);
  13989. normal1 = normal1.scale(this.bv);
  13990. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  13991. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  13992. };
  13993. PickingInfo.prototype.getTextureCoordinates = function () {
  13994. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13995. return null;
  13996. }
  13997. var indices = this.pickedMesh.getIndices();
  13998. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  13999. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  14000. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  14001. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  14002. uv0 = uv0.scale(this.bu);
  14003. uv1 = uv1.scale(this.bv);
  14004. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  14005. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  14006. };
  14007. return PickingInfo;
  14008. })();
  14009. BABYLON.PickingInfo = PickingInfo;
  14010. })(BABYLON || (BABYLON = {}));
  14011. var BABYLON;
  14012. (function (BABYLON) {
  14013. var FilesInput = (function () {
  14014. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  14015. this.engine = p_engine;
  14016. this.canvas = p_canvas;
  14017. this.currentScene = p_scene;
  14018. this.sceneLoadedCallback = p_sceneLoadedCallback;
  14019. this.progressCallback = p_progressCallback;
  14020. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  14021. this.textureLoadingCallback = p_textureLoadingCallback;
  14022. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  14023. }
  14024. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  14025. var _this = this;
  14026. if (p_elementToMonitor) {
  14027. this.elementToMonitor = p_elementToMonitor;
  14028. this.elementToMonitor.addEventListener("dragenter", function (e) {
  14029. _this.drag(e);
  14030. }, false);
  14031. this.elementToMonitor.addEventListener("dragover", function (e) {
  14032. _this.drag(e);
  14033. }, false);
  14034. this.elementToMonitor.addEventListener("drop", function (e) {
  14035. _this.drop(e);
  14036. }, false);
  14037. }
  14038. };
  14039. FilesInput.prototype.renderFunction = function () {
  14040. if (this.additionnalRenderLoopLogicCallback) {
  14041. this.additionnalRenderLoopLogicCallback();
  14042. }
  14043. if (this.currentScene) {
  14044. if (this.textureLoadingCallback) {
  14045. var remaining = this.currentScene.getWaitingItemsCount();
  14046. if (remaining > 0) {
  14047. this.textureLoadingCallback(remaining);
  14048. }
  14049. }
  14050. this.currentScene.render();
  14051. }
  14052. };
  14053. FilesInput.prototype.drag = function (e) {
  14054. e.stopPropagation();
  14055. e.preventDefault();
  14056. };
  14057. FilesInput.prototype.drop = function (eventDrop) {
  14058. eventDrop.stopPropagation();
  14059. eventDrop.preventDefault();
  14060. this.loadFiles(eventDrop);
  14061. };
  14062. FilesInput.prototype.loadFiles = function (event) {
  14063. var _this = this;
  14064. var that = this;
  14065. if (this.startingProcessingFilesCallback)
  14066. this.startingProcessingFilesCallback();
  14067. var sceneFileToLoad;
  14068. var filesToLoad;
  14069. if (event && event.dataTransfer && event.dataTransfer.files) {
  14070. filesToLoad = event.dataTransfer.files;
  14071. }
  14072. if (event && event.target && event.target.files) {
  14073. filesToLoad = event.target.files;
  14074. }
  14075. if (filesToLoad && filesToLoad.length > 0) {
  14076. for (var i = 0; i < filesToLoad.length; i++) {
  14077. switch (filesToLoad[i].type) {
  14078. case "image/jpeg":
  14079. case "image/png":
  14080. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  14081. break;
  14082. case "image/targa":
  14083. case "image/vnd.ms-dds":
  14084. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  14085. break;
  14086. default:
  14087. 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) {
  14088. sceneFileToLoad = filesToLoad[i];
  14089. }
  14090. break;
  14091. }
  14092. }
  14093. if (sceneFileToLoad) {
  14094. if (this.currentScene) {
  14095. this.engine.stopRenderLoop();
  14096. this.currentScene.dispose();
  14097. }
  14098. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  14099. that.currentScene = newScene;
  14100. that.currentScene.executeWhenReady(function () {
  14101. if (that.currentScene.activeCamera) {
  14102. that.currentScene.activeCamera.attachControl(that.canvas);
  14103. }
  14104. if (that.sceneLoadedCallback) {
  14105. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  14106. }
  14107. that.engine.runRenderLoop(function () {
  14108. that.renderFunction();
  14109. });
  14110. });
  14111. }, function (progress) {
  14112. if (_this.progressCallback) {
  14113. _this.progressCallback(progress);
  14114. }
  14115. });
  14116. } else {
  14117. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  14118. }
  14119. }
  14120. };
  14121. FilesInput.FilesTextures = new Array();
  14122. FilesInput.FilesToLoad = new Array();
  14123. return FilesInput;
  14124. })();
  14125. BABYLON.FilesInput = FilesInput;
  14126. })(BABYLON || (BABYLON = {}));
  14127. var BABYLON;
  14128. (function (BABYLON) {
  14129. var OimoJSPlugin = (function () {
  14130. function OimoJSPlugin() {
  14131. this._registeredMeshes = [];
  14132. /**
  14133. * Update the body position according to the mesh position
  14134. * @param mesh
  14135. */
  14136. this.updateBodyPosition = function (mesh) {
  14137. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14138. var registeredMesh = this._registeredMeshes[index];
  14139. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  14140. var body = registeredMesh.body.body;
  14141. mesh.computeWorldMatrix(true);
  14142. var center = mesh.getBoundingInfo().boundingBox.center;
  14143. body.setPosition(center.x, center.y, center.z);
  14144. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  14145. return;
  14146. }
  14147. if (registeredMesh.mesh.parent === mesh) {
  14148. mesh.computeWorldMatrix(true);
  14149. registeredMesh.mesh.computeWorldMatrix(true);
  14150. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  14151. var absoluteRotation = mesh.rotation;
  14152. body = registeredMesh.body.body;
  14153. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  14154. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  14155. return;
  14156. }
  14157. }
  14158. };
  14159. }
  14160. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  14161. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  14162. };
  14163. OimoJSPlugin.prototype.initialize = function (iterations) {
  14164. this._world = new OIMO.World();
  14165. this._world.clear();
  14166. };
  14167. OimoJSPlugin.prototype.setGravity = function (gravity) {
  14168. this._world.gravity = gravity;
  14169. };
  14170. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  14171. var body = null;
  14172. this.unregisterMesh(mesh);
  14173. mesh.computeWorldMatrix(true);
  14174. switch (impostor) {
  14175. case BABYLON.PhysicsEngine.SphereImpostor:
  14176. var bbox = mesh.getBoundingInfo().boundingBox;
  14177. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  14178. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  14179. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  14180. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  14181. var deltaPosition = mesh.position.subtract(bbox.center);
  14182. body = new OIMO.Body({
  14183. type: 'sphere',
  14184. size: [size],
  14185. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  14186. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  14187. move: options.mass != 0,
  14188. config: [options.mass, options.friction, options.restitution],
  14189. world: this._world
  14190. });
  14191. this._registeredMeshes.push({
  14192. mesh: mesh,
  14193. body: body,
  14194. delta: deltaPosition
  14195. });
  14196. break;
  14197. case BABYLON.PhysicsEngine.PlaneImpostor:
  14198. case BABYLON.PhysicsEngine.BoxImpostor:
  14199. bbox = mesh.getBoundingInfo().boundingBox;
  14200. var min = bbox.minimumWorld;
  14201. var max = bbox.maximumWorld;
  14202. var box = max.subtract(min);
  14203. var sizeX = this._checkWithEpsilon(box.x);
  14204. var sizeY = this._checkWithEpsilon(box.y);
  14205. var sizeZ = this._checkWithEpsilon(box.z);
  14206. var deltaPosition = mesh.position.subtract(bbox.center);
  14207. body = new OIMO.Body({
  14208. type: 'box',
  14209. size: [sizeX, sizeY, sizeZ],
  14210. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  14211. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  14212. move: options.mass != 0,
  14213. config: [options.mass, options.friction, options.restitution],
  14214. world: this._world
  14215. });
  14216. this._registeredMeshes.push({
  14217. mesh: mesh,
  14218. body: body,
  14219. delta: deltaPosition
  14220. });
  14221. break;
  14222. }
  14223. return body;
  14224. };
  14225. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  14226. var types = [], sizes = [], positions = [], rotations = [];
  14227. var initialMesh = parts[0].mesh;
  14228. for (var index = 0; index < parts.length; index++) {
  14229. var part = parts[index];
  14230. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  14231. types.push(bodyParameters.type);
  14232. sizes.push.apply(sizes, bodyParameters.size);
  14233. positions.push.apply(positions, bodyParameters.pos);
  14234. rotations.push.apply(rotations, bodyParameters.rot);
  14235. }
  14236. var body = new OIMO.Body({
  14237. type: types,
  14238. size: sizes,
  14239. pos: positions,
  14240. rot: rotations,
  14241. move: options.mass != 0,
  14242. config: [options.mass, options.friction, options.restitution],
  14243. world: this._world
  14244. });
  14245. this._registeredMeshes.push({
  14246. mesh: initialMesh,
  14247. body: body
  14248. });
  14249. return body;
  14250. };
  14251. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  14252. var bodyParameters = null;
  14253. var mesh = part.mesh;
  14254. switch (part.impostor) {
  14255. case BABYLON.PhysicsEngine.SphereImpostor:
  14256. var bbox = mesh.getBoundingInfo().boundingBox;
  14257. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  14258. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  14259. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  14260. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  14261. bodyParameters = {
  14262. type: 'sphere',
  14263. /* bug with oimo : sphere needs 3 sizes in this case */
  14264. size: [size, -1, -1],
  14265. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  14266. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  14267. };
  14268. break;
  14269. case BABYLON.PhysicsEngine.PlaneImpostor:
  14270. case BABYLON.PhysicsEngine.BoxImpostor:
  14271. bbox = mesh.getBoundingInfo().boundingBox;
  14272. var min = bbox.minimumWorld;
  14273. var max = bbox.maximumWorld;
  14274. var box = max.subtract(min);
  14275. var sizeX = this._checkWithEpsilon(box.x);
  14276. var sizeY = this._checkWithEpsilon(box.y);
  14277. var sizeZ = this._checkWithEpsilon(box.z);
  14278. var relativePosition = mesh.position;
  14279. bodyParameters = {
  14280. type: 'box',
  14281. size: [sizeX, sizeY, sizeZ],
  14282. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  14283. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  14284. };
  14285. break;
  14286. }
  14287. return bodyParameters;
  14288. };
  14289. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  14290. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14291. var registeredMesh = this._registeredMeshes[index];
  14292. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  14293. if (registeredMesh.body) {
  14294. this._world.removeRigidBody(registeredMesh.body.body);
  14295. this._unbindBody(registeredMesh.body);
  14296. }
  14297. this._registeredMeshes.splice(index, 1);
  14298. return;
  14299. }
  14300. }
  14301. };
  14302. OimoJSPlugin.prototype._unbindBody = function (body) {
  14303. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14304. var registeredMesh = this._registeredMeshes[index];
  14305. if (registeredMesh.body === body) {
  14306. registeredMesh.body = null;
  14307. }
  14308. }
  14309. };
  14310. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  14311. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14312. var registeredMesh = this._registeredMeshes[index];
  14313. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  14314. var mass = registeredMesh.body.body.massInfo.mass;
  14315. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  14316. return;
  14317. }
  14318. }
  14319. };
  14320. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  14321. var body1 = null, body2 = null;
  14322. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14323. var registeredMesh = this._registeredMeshes[index];
  14324. if (registeredMesh.mesh === mesh1) {
  14325. body1 = registeredMesh.body.body;
  14326. } else if (registeredMesh.mesh === mesh2) {
  14327. body2 = registeredMesh.body.body;
  14328. }
  14329. }
  14330. if (!body1 || !body2) {
  14331. return false;
  14332. }
  14333. if (!options) {
  14334. options = {};
  14335. }
  14336. new OIMO.Link({
  14337. type: options.type,
  14338. body1: body1,
  14339. body2: body2,
  14340. min: options.min,
  14341. max: options.max,
  14342. axe1: options.axe1,
  14343. axe2: options.axe2,
  14344. pos1: [pivot1.x, pivot1.y, pivot1.z],
  14345. pos2: [pivot2.x, pivot2.y, pivot2.z],
  14346. collision: options.collision,
  14347. spring: options.spring,
  14348. world: this._world
  14349. });
  14350. return true;
  14351. };
  14352. OimoJSPlugin.prototype.dispose = function () {
  14353. this._world.clear();
  14354. while (this._registeredMeshes.length) {
  14355. this.unregisterMesh(this._registeredMeshes[0].mesh);
  14356. }
  14357. };
  14358. OimoJSPlugin.prototype.isSupported = function () {
  14359. return OIMO !== undefined;
  14360. };
  14361. OimoJSPlugin.prototype._getLastShape = function (body) {
  14362. var lastShape = body.shapes;
  14363. while (lastShape.next) {
  14364. lastShape = lastShape.next;
  14365. }
  14366. return lastShape;
  14367. };
  14368. OimoJSPlugin.prototype.runOneStep = function (time) {
  14369. this._world.step();
  14370. var i = this._registeredMeshes.length;
  14371. var m;
  14372. while (i--) {
  14373. var body = this._registeredMeshes[i].body.body;
  14374. var mesh = this._registeredMeshes[i].mesh;
  14375. var delta = this._registeredMeshes[i].delta;
  14376. if (!body.sleeping) {
  14377. if (body.shapes.next) {
  14378. var parentShape = this._getLastShape(body);
  14379. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  14380. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  14381. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  14382. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  14383. if (!mesh.rotationQuaternion) {
  14384. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  14385. }
  14386. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  14387. } else {
  14388. m = body.getMatrix();
  14389. mtx = BABYLON.Matrix.FromArray(m);
  14390. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  14391. if (!delta) {
  14392. mesh.position.x = bodyX;
  14393. mesh.position.y = bodyY;
  14394. mesh.position.z = bodyZ;
  14395. } else {
  14396. mesh.position.x = bodyX + delta.x;
  14397. mesh.position.y = bodyY + delta.y;
  14398. mesh.position.z = bodyZ + delta.z;
  14399. }
  14400. if (!mesh.rotationQuaternion) {
  14401. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  14402. }
  14403. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  14404. }
  14405. }
  14406. }
  14407. };
  14408. return OimoJSPlugin;
  14409. })();
  14410. BABYLON.OimoJSPlugin = OimoJSPlugin;
  14411. })(BABYLON || (BABYLON = {}));
  14412. var BABYLON;
  14413. (function (BABYLON) {
  14414. var PhysicsEngine = (function () {
  14415. function PhysicsEngine(plugin) {
  14416. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  14417. }
  14418. PhysicsEngine.prototype._initialize = function (gravity) {
  14419. this._currentPlugin.initialize();
  14420. this._setGravity(gravity);
  14421. };
  14422. PhysicsEngine.prototype._runOneStep = function (delta) {
  14423. if (delta > 0.1) {
  14424. delta = 0.1;
  14425. } else if (delta <= 0) {
  14426. delta = 1.0 / 60.0;
  14427. }
  14428. this._currentPlugin.runOneStep(delta);
  14429. };
  14430. PhysicsEngine.prototype._setGravity = function (gravity) {
  14431. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  14432. this._currentPlugin.setGravity(this.gravity);
  14433. };
  14434. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  14435. return this._currentPlugin.registerMesh(mesh, impostor, options);
  14436. };
  14437. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  14438. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  14439. };
  14440. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  14441. this._currentPlugin.unregisterMesh(mesh);
  14442. };
  14443. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  14444. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  14445. };
  14446. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  14447. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  14448. };
  14449. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  14450. this._currentPlugin.updateBodyPosition(mesh);
  14451. };
  14452. PhysicsEngine.prototype.dispose = function () {
  14453. this._currentPlugin.dispose();
  14454. };
  14455. PhysicsEngine.prototype.isSupported = function () {
  14456. return this._currentPlugin.isSupported();
  14457. };
  14458. PhysicsEngine.NoImpostor = 0;
  14459. PhysicsEngine.SphereImpostor = 1;
  14460. PhysicsEngine.BoxImpostor = 2;
  14461. PhysicsEngine.PlaneImpostor = 3;
  14462. PhysicsEngine.MeshImpostor = 4;
  14463. PhysicsEngine.CapsuleImpostor = 5;
  14464. PhysicsEngine.ConeImpostor = 6;
  14465. PhysicsEngine.CylinderImpostor = 7;
  14466. PhysicsEngine.ConvexHullImpostor = 8;
  14467. PhysicsEngine.Epsilon = 0.001;
  14468. return PhysicsEngine;
  14469. })();
  14470. BABYLON.PhysicsEngine = PhysicsEngine;
  14471. })(BABYLON || (BABYLON = {}));
  14472. var BABYLON;
  14473. (function (BABYLON) {
  14474. var serializeLight = function (light) {
  14475. var serializationObject = {};
  14476. serializationObject.name = light.name;
  14477. serializationObject.id = light.id;
  14478. serializationObject.tags = BABYLON.Tags.GetTags(light);
  14479. if (light instanceof BABYLON.PointLight) {
  14480. serializationObject.type = 0;
  14481. serializationObject.position = light.position.asArray();
  14482. } else if (light instanceof BABYLON.DirectionalLight) {
  14483. serializationObject.type = 1;
  14484. var directionalLight = light;
  14485. serializationObject.position = directionalLight.position.asArray();
  14486. serializationObject.direction = directionalLight.direction.asArray();
  14487. } else if (light instanceof BABYLON.SpotLight) {
  14488. serializationObject.type = 2;
  14489. var spotLight = light;
  14490. serializationObject.position = spotLight.position.asArray();
  14491. serializationObject.direction = spotLight.position.asArray();
  14492. serializationObject.angle = spotLight.angle;
  14493. serializationObject.exponent = spotLight.exponent;
  14494. } else if (light instanceof BABYLON.HemisphericLight) {
  14495. serializationObject.type = 3;
  14496. var hemisphericLight = light;
  14497. serializationObject.direction = hemisphericLight.direction.asArray();
  14498. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  14499. }
  14500. if (light.intensity) {
  14501. serializationObject.intensity = light.intensity;
  14502. }
  14503. serializationObject.range = light.range;
  14504. serializationObject.diffuse = light.diffuse.asArray();
  14505. serializationObject.specular = light.specular.asArray();
  14506. return serializationObject;
  14507. };
  14508. var serializeFresnelParameter = function (fresnelParameter) {
  14509. var serializationObject = {};
  14510. serializationObject.isEnabled = fresnelParameter.isEnabled;
  14511. serializationObject.leftColor = fresnelParameter.leftColor;
  14512. serializationObject.rightColor = fresnelParameter.rightColor;
  14513. serializationObject.bias = fresnelParameter.bias;
  14514. serializationObject.power = fresnelParameter.power;
  14515. return serializationObject;
  14516. };
  14517. var serializeCamera = function (camera) {
  14518. var serializationObject = {};
  14519. serializationObject.name = camera.name;
  14520. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  14521. serializationObject.id = camera.id;
  14522. serializationObject.position = camera.position.asArray();
  14523. if (camera.parent) {
  14524. serializationObject.parentId = camera.parent.id;
  14525. }
  14526. serializationObject.rotation = camera.rotation.asArray();
  14527. if (camera.lockedTarget && camera.lockedTarget.id) {
  14528. serializationObject.lockedTargetId = camera.lockedTarget.id;
  14529. }
  14530. serializationObject.fov = camera.fov;
  14531. serializationObject.minZ = camera.minZ;
  14532. serializationObject.maxZ = camera.maxZ;
  14533. serializationObject.speed = camera.speed;
  14534. serializationObject.inertia = camera.inertia;
  14535. serializationObject.checkCollisions = camera.checkCollisions;
  14536. serializationObject.applyGravity = camera.applyGravity;
  14537. if (camera.ellipsoid) {
  14538. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  14539. }
  14540. appendAnimations(camera, serializationObject);
  14541. serializationObject.layerMask = camera.layerMask;
  14542. return serializationObject;
  14543. };
  14544. var appendAnimations = function (source, destination) {
  14545. if (source.animations) {
  14546. destination.animations = [];
  14547. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  14548. var animation = source.animations[animationIndex];
  14549. destination.animations.push(serializeAnimation(animation));
  14550. }
  14551. }
  14552. };
  14553. var serializeAnimation = function (animation) {
  14554. var serializationObject = {};
  14555. serializationObject.name = animation.name;
  14556. serializationObject.property = animation.targetProperty;
  14557. serializationObject.framePerSecond = animation.framePerSecond;
  14558. serializationObject.dataType = animation.dataType;
  14559. serializationObject.loopBehavior = animation.loopMode;
  14560. var dataType = animation.dataType;
  14561. serializationObject.keys = [];
  14562. var keys = animation.getKeys();
  14563. for (var index = 0; index < keys.length; index++) {
  14564. var animationKey = keys[index];
  14565. var key = {};
  14566. key.frame = animationKey.frame;
  14567. switch (dataType) {
  14568. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  14569. key.values = [animationKey.value];
  14570. break;
  14571. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  14572. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  14573. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  14574. key.values = animationKey.value.asArray();
  14575. break;
  14576. }
  14577. serializationObject.keys.push(key);
  14578. }
  14579. return serializationObject;
  14580. };
  14581. var serializeMultiMaterial = function (material) {
  14582. var serializationObject = {};
  14583. serializationObject.name = material.name;
  14584. serializationObject.id = material.id;
  14585. serializationObject.tags = BABYLON.Tags.GetTags(material);
  14586. serializationObject.materials = [];
  14587. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  14588. var subMat = material.subMaterials[matIndex];
  14589. if (subMat) {
  14590. serializationObject.materials.push(subMat.id);
  14591. } else {
  14592. serializationObject.materials.push(null);
  14593. }
  14594. }
  14595. return serializationObject;
  14596. };
  14597. var serializeMaterial = function (material) {
  14598. var serializationObject = {};
  14599. serializationObject.name = material.name;
  14600. serializationObject.ambient = material.ambientColor.asArray();
  14601. serializationObject.diffuse = material.diffuseColor.asArray();
  14602. serializationObject.specular = material.specularColor.asArray();
  14603. serializationObject.specularPower = material.specularPower;
  14604. serializationObject.emissive = material.emissiveColor.asArray();
  14605. serializationObject.alpha = material.alpha;
  14606. serializationObject.id = material.id;
  14607. serializationObject.tags = BABYLON.Tags.GetTags(material);
  14608. serializationObject.backFaceCulling = material.backFaceCulling;
  14609. if (material.diffuseTexture) {
  14610. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  14611. }
  14612. if (material.diffuseFresnelParameters) {
  14613. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  14614. }
  14615. if (material.ambientTexture) {
  14616. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  14617. }
  14618. if (material.opacityTexture) {
  14619. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  14620. }
  14621. if (material.opacityFresnelParameters) {
  14622. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  14623. }
  14624. if (material.reflectionTexture) {
  14625. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  14626. }
  14627. if (material.reflectionFresnelParameters) {
  14628. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  14629. }
  14630. if (material.emissiveTexture) {
  14631. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  14632. }
  14633. if (material.emissiveFresnelParameters) {
  14634. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  14635. }
  14636. if (material.specularTexture) {
  14637. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  14638. }
  14639. if (material.bumpTexture) {
  14640. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  14641. }
  14642. return serializationObject;
  14643. };
  14644. var serializeTexture = function (texture) {
  14645. var serializationObject = {};
  14646. if (!texture.name) {
  14647. return null;
  14648. }
  14649. if (texture instanceof BABYLON.CubeTexture) {
  14650. serializationObject.name = texture.name;
  14651. serializationObject.hasAlpha = texture.hasAlpha;
  14652. serializationObject.level = texture.level;
  14653. serializationObject.coordinatesMode = texture.coordinatesMode;
  14654. return serializationObject;
  14655. }
  14656. if (texture instanceof BABYLON.MirrorTexture) {
  14657. var mirrorTexture = texture;
  14658. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  14659. serializationObject.renderList = [];
  14660. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  14661. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  14662. }
  14663. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  14664. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  14665. var renderTargetTexture = texture;
  14666. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  14667. serializationObject.renderList = [];
  14668. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  14669. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  14670. }
  14671. }
  14672. var regularTexture = texture;
  14673. serializationObject.name = texture.name;
  14674. serializationObject.hasAlpha = texture.hasAlpha;
  14675. serializationObject.level = texture.level;
  14676. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  14677. serializationObject.coordinatesMode = texture.coordinatesMode;
  14678. serializationObject.uOffset = regularTexture.uOffset;
  14679. serializationObject.vOffset = regularTexture.vOffset;
  14680. serializationObject.uScale = regularTexture.uScale;
  14681. serializationObject.vScale = regularTexture.vScale;
  14682. serializationObject.uAng = regularTexture.uAng;
  14683. serializationObject.vAng = regularTexture.vAng;
  14684. serializationObject.wAng = regularTexture.wAng;
  14685. serializationObject.wrapU = texture.wrapU;
  14686. serializationObject.wrapV = texture.wrapV;
  14687. appendAnimations(texture, serializationObject);
  14688. return serializationObject;
  14689. };
  14690. var serializeSkeleton = function (skeleton) {
  14691. var serializationObject = {};
  14692. serializationObject.name = skeleton.name;
  14693. serializationObject.id = skeleton.id;
  14694. serializationObject.bones = [];
  14695. for (var index = 0; index < skeleton.bones.length; index++) {
  14696. var bone = skeleton.bones[index];
  14697. var serializedBone = {
  14698. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  14699. name: bone.name,
  14700. matrix: bone.getLocalMatrix().toArray()
  14701. };
  14702. serializationObject.bones.push(serializedBone);
  14703. if (bone.animations && bone.animations.length > 0) {
  14704. serializedBone.animation = serializeAnimation(bone.animations[0]);
  14705. }
  14706. }
  14707. return serializationObject;
  14708. };
  14709. var serializeParticleSystem = function (particleSystem) {
  14710. var serializationObject = {};
  14711. serializationObject.emitterId = particleSystem.emitter.id;
  14712. serializationObject.capacity = particleSystem.getCapacity();
  14713. if (particleSystem.particleTexture) {
  14714. serializationObject.textureName = particleSystem.particleTexture.name;
  14715. }
  14716. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  14717. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  14718. serializationObject.minSize = particleSystem.minSize;
  14719. serializationObject.maxSize = particleSystem.maxSize;
  14720. serializationObject.minLifeTime = particleSystem.minLifeTime;
  14721. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  14722. serializationObject.emitRate = particleSystem.emitRate;
  14723. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  14724. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  14725. serializationObject.gravity = particleSystem.gravity.asArray();
  14726. serializationObject.direction1 = particleSystem.direction1.asArray();
  14727. serializationObject.direction2 = particleSystem.direction2.asArray();
  14728. serializationObject.color1 = particleSystem.color1.asArray();
  14729. serializationObject.color2 = particleSystem.color2.asArray();
  14730. serializationObject.colorDead = particleSystem.colorDead.asArray();
  14731. serializationObject.updateSpeed = particleSystem.updateSpeed;
  14732. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  14733. serializationObject.textureMask = particleSystem.textureMask.asArray();
  14734. serializationObject.blendMode = particleSystem.blendMode;
  14735. return serializationObject;
  14736. };
  14737. var serializeLensFlareSystem = function (lensFlareSystem) {
  14738. var serializationObject = {};
  14739. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  14740. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  14741. serializationObject.flares = [];
  14742. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  14743. var flare = lensFlareSystem.lensFlares[index];
  14744. serializationObject.flares.push({
  14745. size: flare.size,
  14746. position: flare.position,
  14747. color: flare.color.asArray(),
  14748. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  14749. });
  14750. }
  14751. return serializationObject;
  14752. };
  14753. var serializeShadowGenerator = function (light) {
  14754. var serializationObject = {};
  14755. var shadowGenerator = light.getShadowGenerator();
  14756. serializationObject.lightId = light.id;
  14757. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  14758. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  14759. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  14760. serializationObject.renderList = [];
  14761. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  14762. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  14763. serializationObject.renderList.push(mesh.id);
  14764. }
  14765. return serializationObject;
  14766. };
  14767. var serializedGeometries = [];
  14768. var serializeGeometry = function (geometry, serializationGeometries) {
  14769. if (serializedGeometries[geometry.id]) {
  14770. return;
  14771. }
  14772. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  14773. serializationGeometries.boxes.push(serializeBox(geometry));
  14774. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  14775. serializationGeometries.spheres.push(serializeSphere(geometry));
  14776. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  14777. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  14778. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  14779. serializationGeometries.toruses.push(serializeTorus(geometry));
  14780. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  14781. serializationGeometries.grounds.push(serializeGround(geometry));
  14782. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  14783. serializationGeometries.planes.push(serializePlane(geometry));
  14784. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  14785. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  14786. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  14787. throw new Error("Unknow primitive type");
  14788. } else {
  14789. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  14790. }
  14791. serializedGeometries[geometry.id] = true;
  14792. };
  14793. var serializeGeometryBase = function (geometry) {
  14794. var serializationObject = {};
  14795. serializationObject.id = geometry.id;
  14796. if (BABYLON.Tags.HasTags(geometry)) {
  14797. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  14798. }
  14799. return serializationObject;
  14800. };
  14801. var serializeVertexData = function (vertexData) {
  14802. var serializationObject = serializeGeometryBase(vertexData);
  14803. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14804. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14805. }
  14806. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14807. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14808. }
  14809. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14810. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14811. }
  14812. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14813. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  14814. }
  14815. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14816. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  14817. }
  14818. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  14819. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  14820. serializationObject.matricesIndices._isExpanded = true;
  14821. }
  14822. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  14823. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  14824. }
  14825. serializationObject.indices = vertexData.getIndices();
  14826. return serializationObject;
  14827. };
  14828. var serializePrimitive = function (primitive) {
  14829. var serializationObject = serializeGeometryBase(primitive);
  14830. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  14831. return serializationObject;
  14832. };
  14833. var serializeBox = function (box) {
  14834. var serializationObject = serializePrimitive(box);
  14835. serializationObject.size = box.size;
  14836. return serializationObject;
  14837. };
  14838. var serializeSphere = function (sphere) {
  14839. var serializationObject = serializePrimitive(sphere);
  14840. serializationObject.segments = sphere.segments;
  14841. serializationObject.diameter = sphere.diameter;
  14842. return serializationObject;
  14843. };
  14844. var serializeCylinder = function (cylinder) {
  14845. var serializationObject = serializePrimitive(cylinder);
  14846. serializationObject.height = cylinder.height;
  14847. serializationObject.diameterTop = cylinder.diameterTop;
  14848. serializationObject.diameterBottom = cylinder.diameterBottom;
  14849. serializationObject.tessellation = cylinder.tessellation;
  14850. return serializationObject;
  14851. };
  14852. var serializeTorus = function (torus) {
  14853. var serializationObject = serializePrimitive(torus);
  14854. serializationObject.diameter = torus.diameter;
  14855. serializationObject.thickness = torus.thickness;
  14856. serializationObject.tessellation = torus.tessellation;
  14857. return serializationObject;
  14858. };
  14859. var serializeGround = function (ground) {
  14860. var serializationObject = serializePrimitive(ground);
  14861. serializationObject.width = ground.width;
  14862. serializationObject.height = ground.height;
  14863. serializationObject.subdivisions = ground.subdivisions;
  14864. return serializationObject;
  14865. };
  14866. var serializePlane = function (plane) {
  14867. var serializationObject = serializePrimitive(plane);
  14868. serializationObject.size = plane.size;
  14869. return serializationObject;
  14870. };
  14871. var serializeTorusKnot = function (torusKnot) {
  14872. var serializationObject = serializePrimitive(torusKnot);
  14873. serializationObject.radius = torusKnot.radius;
  14874. serializationObject.tube = torusKnot.tube;
  14875. serializationObject.radialSegments = torusKnot.radialSegments;
  14876. serializationObject.tubularSegments = torusKnot.tubularSegments;
  14877. serializationObject.p = torusKnot.p;
  14878. serializationObject.q = torusKnot.q;
  14879. return serializationObject;
  14880. };
  14881. var serializeMesh = function (mesh, serializationScene) {
  14882. var serializationObject = {};
  14883. serializationObject.name = mesh.name;
  14884. serializationObject.id = mesh.id;
  14885. if (BABYLON.Tags.HasTags(mesh)) {
  14886. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  14887. }
  14888. serializationObject.position = mesh.position.asArray();
  14889. if (mesh.rotationQuaternion) {
  14890. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  14891. } else if (mesh.rotation) {
  14892. serializationObject.rotation = mesh.rotation.asArray();
  14893. }
  14894. serializationObject.scaling = mesh.scaling.asArray();
  14895. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  14896. serializationObject.isEnabled = mesh.isEnabled();
  14897. serializationObject.isVisible = mesh.isVisible;
  14898. serializationObject.infiniteDistance = mesh.infiniteDistance;
  14899. serializationObject.pickable = mesh.isPickable;
  14900. serializationObject.receiveShadows = mesh.receiveShadows;
  14901. serializationObject.billboardMode = mesh.billboardMode;
  14902. serializationObject.visibility = mesh.visibility;
  14903. serializationObject.checkCollisions = mesh.checkCollisions;
  14904. if (mesh.parent) {
  14905. serializationObject.parentId = mesh.parent.id;
  14906. }
  14907. var geometry = mesh._geometry;
  14908. if (geometry) {
  14909. var geometryId = geometry.id;
  14910. serializationObject.geometryId = geometryId;
  14911. if (!mesh.getScene().getGeometryByID(geometryId)) {
  14912. serializeGeometry(geometry, serializationScene.geometries);
  14913. }
  14914. serializationObject.subMeshes = [];
  14915. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  14916. var subMesh = mesh.subMeshes[subIndex];
  14917. serializationObject.subMeshes.push({
  14918. materialIndex: subMesh.materialIndex,
  14919. verticesStart: subMesh.verticesStart,
  14920. verticesCount: subMesh.verticesCount,
  14921. indexStart: subMesh.indexStart,
  14922. indexCount: subMesh.indexCount
  14923. });
  14924. }
  14925. }
  14926. if (mesh.material) {
  14927. serializationObject.materialId = mesh.material.id;
  14928. } else {
  14929. mesh.material = null;
  14930. }
  14931. if (mesh.skeleton) {
  14932. serializationObject.skeletonId = mesh.skeleton.id;
  14933. }
  14934. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  14935. serializationObject.physicsMass = mesh.getPhysicsMass();
  14936. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  14937. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  14938. switch (mesh.getPhysicsImpostor()) {
  14939. case BABYLON.PhysicsEngine.BoxImpostor:
  14940. serializationObject.physicsImpostor = 1;
  14941. break;
  14942. case BABYLON.PhysicsEngine.SphereImpostor:
  14943. serializationObject.physicsImpostor = 2;
  14944. break;
  14945. }
  14946. }
  14947. serializationObject.instances = [];
  14948. for (var index = 0; index < mesh.instances.length; index++) {
  14949. var instance = mesh.instances[index];
  14950. var serializationInstance = {
  14951. name: instance.name,
  14952. position: instance.position,
  14953. rotation: instance.rotation,
  14954. rotationQuaternion: instance.rotationQuaternion,
  14955. scaling: instance.scaling
  14956. };
  14957. serializationObject.instances.push(serializationInstance);
  14958. appendAnimations(instance, serializationInstance);
  14959. }
  14960. appendAnimations(mesh, serializationObject);
  14961. serializationObject.layerMask = mesh.layerMask;
  14962. return serializationObject;
  14963. };
  14964. var SceneSerializer = (function () {
  14965. function SceneSerializer() {
  14966. }
  14967. SceneSerializer.Serialize = function (scene) {
  14968. var serializationObject = {};
  14969. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  14970. serializationObject.autoClear = scene.autoClear;
  14971. serializationObject.clearColor = scene.clearColor.asArray();
  14972. serializationObject.ambientColor = scene.ambientColor.asArray();
  14973. serializationObject.gravity = scene.gravity.asArray();
  14974. if (scene.fogMode && scene.fogMode !== 0) {
  14975. serializationObject.fogMode = scene.fogMode;
  14976. serializationObject.fogColor = scene.fogColor.asArray();
  14977. serializationObject.fogStart = scene.fogStart;
  14978. serializationObject.fogEnd = scene.fogEnd;
  14979. serializationObject.fogDensity = scene.fogDensity;
  14980. }
  14981. serializationObject.lights = [];
  14982. for (var index = 0; index < scene.lights.length; index++) {
  14983. var light = scene.lights[index];
  14984. serializationObject.lights.push(serializeLight(light));
  14985. }
  14986. serializationObject.cameras = [];
  14987. for (index = 0; index < scene.cameras.length; index++) {
  14988. var camera = scene.cameras[index];
  14989. if (camera instanceof BABYLON.FreeCamera) {
  14990. serializationObject.cameras.push(serializeCamera(camera));
  14991. }
  14992. }
  14993. if (scene.activeCamera) {
  14994. serializationObject.activeCameraID = scene.activeCamera.id;
  14995. }
  14996. serializationObject.materials = [];
  14997. serializationObject.multiMaterials = [];
  14998. for (index = 0; index < scene.materials.length; index++) {
  14999. var material = scene.materials[index];
  15000. if (material instanceof BABYLON.StandardMaterial) {
  15001. serializationObject.materials.push(serializeMaterial(material));
  15002. } else if (material instanceof BABYLON.MultiMaterial) {
  15003. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  15004. }
  15005. }
  15006. serializationObject.skeletons = [];
  15007. for (index = 0; index < scene.skeletons.length; index++) {
  15008. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  15009. }
  15010. serializationObject.geometries = {};
  15011. serializationObject.geometries.boxes = [];
  15012. serializationObject.geometries.spheres = [];
  15013. serializationObject.geometries.cylinders = [];
  15014. serializationObject.geometries.toruses = [];
  15015. serializationObject.geometries.grounds = [];
  15016. serializationObject.geometries.planes = [];
  15017. serializationObject.geometries.torusKnots = [];
  15018. serializationObject.geometries.vertexData = [];
  15019. serializedGeometries = [];
  15020. var geometries = scene.getGeometries();
  15021. for (var index = 0; index < geometries.length; index++) {
  15022. var geometry = geometries[index];
  15023. if (geometry.isReady()) {
  15024. serializeGeometry(geometry, serializationObject.geometries);
  15025. }
  15026. }
  15027. serializationObject.meshes = [];
  15028. for (index = 0; index < scene.meshes.length; index++) {
  15029. var abstractMesh = scene.meshes[index];
  15030. if (abstractMesh instanceof BABYLON.Mesh) {
  15031. var mesh = abstractMesh;
  15032. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  15033. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  15034. }
  15035. }
  15036. }
  15037. serializationObject.particleSystems = [];
  15038. for (index = 0; index < scene.particleSystems.length; index++) {
  15039. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  15040. }
  15041. serializationObject.lensFlareSystems = [];
  15042. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  15043. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  15044. }
  15045. serializationObject.shadowGenerators = [];
  15046. for (index = 0; index < scene.lights.length; index++) {
  15047. light = scene.lights[index];
  15048. if (light.getShadowGenerator()) {
  15049. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  15050. }
  15051. }
  15052. return serializationObject;
  15053. };
  15054. return SceneSerializer;
  15055. })();
  15056. BABYLON.SceneSerializer = SceneSerializer;
  15057. })(BABYLON || (BABYLON = {}));
  15058. var BABYLON;
  15059. (function (BABYLON) {
  15060. var SceneLoader = (function () {
  15061. function SceneLoader() {
  15062. }
  15063. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  15064. get: function () {
  15065. return SceneLoader._ForceFullSceneLoadingForIncremental;
  15066. },
  15067. set: function (value) {
  15068. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  15069. },
  15070. enumerable: true,
  15071. configurable: true
  15072. });
  15073. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  15074. get: function () {
  15075. return SceneLoader._ShowLoadingScreen;
  15076. },
  15077. set: function (value) {
  15078. SceneLoader._ShowLoadingScreen = value;
  15079. },
  15080. enumerable: true,
  15081. configurable: true
  15082. });
  15083. SceneLoader._getPluginForFilename = function (sceneFilename) {
  15084. var dotPosition = sceneFilename.lastIndexOf(".");
  15085. var queryStringPosition = sceneFilename.indexOf("?");
  15086. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  15087. for (var index = 0; index < this._registeredPlugins.length; index++) {
  15088. var plugin = this._registeredPlugins[index];
  15089. if (plugin.extensions.indexOf(extension) !== -1) {
  15090. return plugin;
  15091. }
  15092. }
  15093. return this._registeredPlugins[this._registeredPlugins.length - 1];
  15094. };
  15095. SceneLoader.RegisterPlugin = function (plugin) {
  15096. plugin.extensions = plugin.extensions.toLowerCase();
  15097. SceneLoader._registeredPlugins.push(plugin);
  15098. };
  15099. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  15100. var manifestChecked = function (success) {
  15101. scene.database = database;
  15102. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  15103. var importMeshFromData = function (data) {
  15104. var meshes = [];
  15105. var particleSystems = [];
  15106. var skeletons = [];
  15107. try {
  15108. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  15109. if (onerror) {
  15110. onerror(scene);
  15111. }
  15112. return;
  15113. }
  15114. } catch (e) {
  15115. if (onerror) {
  15116. onerror(scene);
  15117. }
  15118. return;
  15119. }
  15120. if (onsuccess) {
  15121. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  15122. onsuccess(meshes, particleSystems, skeletons);
  15123. }
  15124. };
  15125. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  15126. importMeshFromData(sceneFilename.substr(5));
  15127. return;
  15128. }
  15129. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  15130. importMeshFromData(data);
  15131. }, progressCallBack, database);
  15132. };
  15133. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  15134. };
  15135. /**
  15136. * Load a scene
  15137. * @param rootUrl a string that defines the root url for scene and resources
  15138. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  15139. * @param engine is the instance of BABYLON.Engine to use to create the scene
  15140. */
  15141. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  15142. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  15143. };
  15144. /**
  15145. * Append a scene
  15146. * @param rootUrl a string that defines the root url for scene and resources
  15147. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  15148. * @param scene is the instance of BABYLON.Scene to append to
  15149. */
  15150. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  15151. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  15152. var database;
  15153. if (SceneLoader.ShowLoadingScreen) {
  15154. scene.getEngine().displayLoadingUI();
  15155. }
  15156. var loadSceneFromData = function (data) {
  15157. scene.database = database;
  15158. if (!plugin.load(scene, data, rootUrl)) {
  15159. if (onerror) {
  15160. onerror(scene);
  15161. }
  15162. scene.getEngine().hideLoadingUI();
  15163. return;
  15164. }
  15165. if (onsuccess) {
  15166. onsuccess(scene);
  15167. }
  15168. if (SceneLoader.ShowLoadingScreen) {
  15169. scene.executeWhenReady(function () {
  15170. scene.getEngine().hideLoadingUI();
  15171. });
  15172. }
  15173. };
  15174. var manifestChecked = function (success) {
  15175. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  15176. };
  15177. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  15178. loadSceneFromData(sceneFilename.substr(5));
  15179. return;
  15180. }
  15181. if (rootUrl.indexOf("file:") === -1) {
  15182. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  15183. } else {
  15184. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  15185. }
  15186. };
  15187. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  15188. SceneLoader._ShowLoadingScreen = true;
  15189. SceneLoader._registeredPlugins = new Array();
  15190. return SceneLoader;
  15191. })();
  15192. BABYLON.SceneLoader = SceneLoader;
  15193. ;
  15194. })(BABYLON || (BABYLON = {}));
  15195. var BABYLON;
  15196. (function (BABYLON) {
  15197. (function (Internals) {
  15198. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  15199. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  15200. texture.name = parsedTexture.name;
  15201. texture.hasAlpha = parsedTexture.hasAlpha;
  15202. texture.level = parsedTexture.level;
  15203. texture.coordinatesMode = parsedTexture.coordinatesMode;
  15204. return texture;
  15205. };
  15206. var loadTexture = function (rootUrl, parsedTexture, scene) {
  15207. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  15208. return null;
  15209. }
  15210. if (parsedTexture.isCube) {
  15211. return loadCubeTexture(rootUrl, parsedTexture, scene);
  15212. }
  15213. var texture;
  15214. if (parsedTexture.mirrorPlane) {
  15215. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  15216. texture._waitingRenderList = parsedTexture.renderList;
  15217. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  15218. } else if (parsedTexture.isRenderTarget) {
  15219. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  15220. texture._waitingRenderList = parsedTexture.renderList;
  15221. } else {
  15222. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  15223. }
  15224. texture.name = parsedTexture.name;
  15225. texture.hasAlpha = parsedTexture.hasAlpha;
  15226. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  15227. texture.level = parsedTexture.level;
  15228. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  15229. texture.coordinatesMode = parsedTexture.coordinatesMode;
  15230. texture.uOffset = parsedTexture.uOffset;
  15231. texture.vOffset = parsedTexture.vOffset;
  15232. texture.uScale = parsedTexture.uScale;
  15233. texture.vScale = parsedTexture.vScale;
  15234. texture.uAng = parsedTexture.uAng;
  15235. texture.vAng = parsedTexture.vAng;
  15236. texture.wAng = parsedTexture.wAng;
  15237. texture.wrapU = parsedTexture.wrapU;
  15238. texture.wrapV = parsedTexture.wrapV;
  15239. if (parsedTexture.animations) {
  15240. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  15241. var parsedAnimation = parsedTexture.animations[animationIndex];
  15242. texture.animations.push(parseAnimation(parsedAnimation));
  15243. }
  15244. }
  15245. return texture;
  15246. };
  15247. var parseSkeleton = function (parsedSkeleton, scene) {
  15248. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  15249. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  15250. var parsedBone = parsedSkeleton.bones[index];
  15251. var parentBone = null;
  15252. if (parsedBone.parentBoneIndex > -1) {
  15253. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  15254. }
  15255. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  15256. if (parsedBone.animation) {
  15257. bone.animations.push(parseAnimation(parsedBone.animation));
  15258. }
  15259. }
  15260. return skeleton;
  15261. };
  15262. var parseFresnelParameters = function (parsedFresnelParameters) {
  15263. var fresnelParameters = new BABYLON.FresnelParameters();
  15264. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  15265. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  15266. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  15267. fresnelParameters.bias = parsedFresnelParameters.bias;
  15268. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  15269. return fresnelParameters;
  15270. };
  15271. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  15272. var material;
  15273. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  15274. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  15275. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  15276. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  15277. material.specularPower = parsedMaterial.specularPower;
  15278. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  15279. material.alpha = parsedMaterial.alpha;
  15280. material.id = parsedMaterial.id;
  15281. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  15282. material.backFaceCulling = parsedMaterial.backFaceCulling;
  15283. material.wireframe = parsedMaterial.wireframe;
  15284. if (parsedMaterial.diffuseTexture) {
  15285. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  15286. }
  15287. if (parsedMaterial.diffuseFresnelParameters) {
  15288. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  15289. }
  15290. if (parsedMaterial.ambientTexture) {
  15291. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  15292. }
  15293. if (parsedMaterial.opacityTexture) {
  15294. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  15295. }
  15296. if (parsedMaterial.opacityFresnelParameters) {
  15297. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  15298. }
  15299. if (parsedMaterial.reflectionTexture) {
  15300. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  15301. }
  15302. if (parsedMaterial.reflectionFresnelParameters) {
  15303. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  15304. }
  15305. if (parsedMaterial.emissiveTexture) {
  15306. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  15307. }
  15308. if (parsedMaterial.emissiveFresnelParameters) {
  15309. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  15310. }
  15311. if (parsedMaterial.specularTexture) {
  15312. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  15313. }
  15314. if (parsedMaterial.bumpTexture) {
  15315. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  15316. }
  15317. return material;
  15318. };
  15319. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  15320. for (var index = 0; index < parsedData.materials.length; index++) {
  15321. var parsedMaterial = parsedData.materials[index];
  15322. if (parsedMaterial.id === id) {
  15323. return parseMaterial(parsedMaterial, scene, rootUrl);
  15324. }
  15325. }
  15326. return null;
  15327. };
  15328. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  15329. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  15330. multiMaterial.id = parsedMultiMaterial.id;
  15331. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  15332. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  15333. var subMatId = parsedMultiMaterial.materials[matIndex];
  15334. if (subMatId) {
  15335. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  15336. } else {
  15337. multiMaterial.subMaterials.push(null);
  15338. }
  15339. }
  15340. return multiMaterial;
  15341. };
  15342. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  15343. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  15344. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  15345. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  15346. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  15347. var parsedFlare = parsedLensFlareSystem.flares[index];
  15348. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  15349. }
  15350. return lensFlareSystem;
  15351. };
  15352. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  15353. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  15354. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  15355. if (parsedParticleSystem.textureName) {
  15356. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  15357. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  15358. }
  15359. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  15360. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  15361. particleSystem.minSize = parsedParticleSystem.minSize;
  15362. particleSystem.maxSize = parsedParticleSystem.maxSize;
  15363. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  15364. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  15365. particleSystem.emitter = emitter;
  15366. particleSystem.emitRate = parsedParticleSystem.emitRate;
  15367. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  15368. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  15369. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  15370. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  15371. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  15372. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  15373. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  15374. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  15375. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  15376. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  15377. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  15378. particleSystem.blendMode = parsedParticleSystem.blendMode;
  15379. particleSystem.start();
  15380. return particleSystem;
  15381. };
  15382. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  15383. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  15384. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  15385. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  15386. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  15387. shadowGenerator.getShadowMap().renderList.push(mesh);
  15388. }
  15389. if (parsedShadowGenerator.usePoissonSampling) {
  15390. shadowGenerator.usePoissonSampling = true;
  15391. } else {
  15392. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  15393. }
  15394. return shadowGenerator;
  15395. };
  15396. var parseAnimation = function (parsedAnimation) {
  15397. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  15398. var dataType = parsedAnimation.dataType;
  15399. var keys = [];
  15400. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  15401. var key = parsedAnimation.keys[index];
  15402. var data;
  15403. switch (dataType) {
  15404. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  15405. data = key.values[0];
  15406. break;
  15407. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  15408. data = BABYLON.Quaternion.FromArray(key.values);
  15409. break;
  15410. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  15411. data = BABYLON.Matrix.FromArray(key.values);
  15412. break;
  15413. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  15414. default:
  15415. data = BABYLON.Vector3.FromArray(key.values);
  15416. break;
  15417. }
  15418. keys.push({
  15419. frame: key.frame,
  15420. value: data
  15421. });
  15422. }
  15423. animation.setKeys(keys);
  15424. return animation;
  15425. };
  15426. var parseLight = function (parsedLight, scene) {
  15427. var light;
  15428. switch (parsedLight.type) {
  15429. case 0:
  15430. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  15431. break;
  15432. case 1:
  15433. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  15434. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  15435. break;
  15436. case 2:
  15437. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  15438. break;
  15439. case 3:
  15440. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  15441. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  15442. break;
  15443. }
  15444. light.id = parsedLight.id;
  15445. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  15446. if (parsedLight.intensity !== undefined) {
  15447. light.intensity = parsedLight.intensity;
  15448. }
  15449. if (parsedLight.range) {
  15450. light.range = parsedLight.range;
  15451. }
  15452. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  15453. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  15454. if (parsedLight.excludedMeshesIds) {
  15455. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  15456. }
  15457. if (parsedLight.includedOnlyMeshesIds) {
  15458. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  15459. }
  15460. if (parsedLight.animations) {
  15461. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  15462. var parsedAnimation = parsedLight.animations[animationIndex];
  15463. light.animations.push(parseAnimation(parsedAnimation));
  15464. }
  15465. }
  15466. if (parsedLight.autoAnimate) {
  15467. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  15468. }
  15469. };
  15470. var parseCamera = function (parsedCamera, scene) {
  15471. var camera;
  15472. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  15473. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  15474. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  15475. var alpha = parsedCamera.alpha;
  15476. var beta = parsedCamera.beta;
  15477. var radius = parsedCamera.radius;
  15478. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  15479. var eye_space = parsedCamera.eye_space;
  15480. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  15481. } else {
  15482. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  15483. }
  15484. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  15485. var eye_space = parsedCamera.eye_space;
  15486. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  15487. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  15488. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  15489. } else if (parsedCamera.type === "FollowCamera") {
  15490. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  15491. camera.heightOffset = parsedCamera.heightOffset;
  15492. camera.radius = parsedCamera.radius;
  15493. camera.rotationOffset = parsedCamera.rotationOffset;
  15494. if (lockedTargetMesh)
  15495. camera.target = lockedTargetMesh;
  15496. } else if (parsedCamera.type === "GamepadCamera") {
  15497. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  15498. } else if (parsedCamera.type === "OculusCamera") {
  15499. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  15500. } else if (parsedCamera.type === "TouchCamera") {
  15501. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  15502. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  15503. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  15504. } else if (parsedCamera.type === "WebVRCamera") {
  15505. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  15506. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  15507. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  15508. } else {
  15509. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  15510. }
  15511. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  15512. camera.lockedTarget = lockedTargetMesh;
  15513. }
  15514. camera.id = parsedCamera.id;
  15515. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  15516. if (parsedCamera.parentId) {
  15517. camera._waitingParentId = parsedCamera.parentId;
  15518. }
  15519. if (parsedCamera.target) {
  15520. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15521. } else {
  15522. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  15523. }
  15524. camera.fov = parsedCamera.fov;
  15525. camera.minZ = parsedCamera.minZ;
  15526. camera.maxZ = parsedCamera.maxZ;
  15527. camera.speed = parsedCamera.speed;
  15528. camera.inertia = parsedCamera.inertia;
  15529. camera.checkCollisions = parsedCamera.checkCollisions;
  15530. camera.applyGravity = parsedCamera.applyGravity;
  15531. if (parsedCamera.ellipsoid) {
  15532. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  15533. }
  15534. if (parsedCamera.animations) {
  15535. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15536. var parsedAnimation = parsedCamera.animations[animationIndex];
  15537. camera.animations.push(parseAnimation(parsedAnimation));
  15538. }
  15539. }
  15540. if (parsedCamera.autoAnimate) {
  15541. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  15542. }
  15543. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  15544. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  15545. } else {
  15546. camera.layerMask = 0xFFFFFFFF;
  15547. }
  15548. return camera;
  15549. };
  15550. var parseGeometry = function (parsedGeometry, scene) {
  15551. var id = parsedGeometry.id;
  15552. return scene.getGeometryByID(id);
  15553. };
  15554. var parseBox = function (parsedBox, scene) {
  15555. if (parseGeometry(parsedBox, scene)) {
  15556. return null;
  15557. }
  15558. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  15559. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  15560. scene.pushGeometry(box, true);
  15561. return box;
  15562. };
  15563. var parseSphere = function (parsedSphere, scene) {
  15564. if (parseGeometry(parsedSphere, scene)) {
  15565. return null;
  15566. }
  15567. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  15568. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  15569. scene.pushGeometry(sphere, true);
  15570. return sphere;
  15571. };
  15572. var parseCylinder = function (parsedCylinder, scene) {
  15573. if (parseGeometry(parsedCylinder, scene)) {
  15574. return null;
  15575. }
  15576. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  15577. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  15578. scene.pushGeometry(cylinder, true);
  15579. return cylinder;
  15580. };
  15581. var parseTorus = function (parsedTorus, scene) {
  15582. if (parseGeometry(parsedTorus, scene)) {
  15583. return null;
  15584. }
  15585. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  15586. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  15587. scene.pushGeometry(torus, true);
  15588. return torus;
  15589. };
  15590. var parseGround = function (parsedGround, scene) {
  15591. if (parseGeometry(parsedGround, scene)) {
  15592. return null;
  15593. }
  15594. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  15595. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  15596. scene.pushGeometry(ground, true);
  15597. return ground;
  15598. };
  15599. var parsePlane = function (parsedPlane, scene) {
  15600. if (parseGeometry(parsedPlane, scene)) {
  15601. return null;
  15602. }
  15603. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  15604. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  15605. scene.pushGeometry(plane, true);
  15606. return plane;
  15607. };
  15608. var parseTorusKnot = function (parsedTorusKnot, scene) {
  15609. if (parseGeometry(parsedTorusKnot, scene)) {
  15610. return null;
  15611. }
  15612. 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);
  15613. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  15614. scene.pushGeometry(torusKnot, true);
  15615. return torusKnot;
  15616. };
  15617. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  15618. if (parseGeometry(parsedVertexData, scene)) {
  15619. return null;
  15620. }
  15621. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  15622. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  15623. if (parsedVertexData.delayLoadingFile) {
  15624. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15625. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  15626. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  15627. geometry._delayInfo = [];
  15628. if (parsedVertexData.hasUVs) {
  15629. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15630. }
  15631. if (parsedVertexData.hasUVs2) {
  15632. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15633. }
  15634. if (parsedVertexData.hasColors) {
  15635. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15636. }
  15637. if (parsedVertexData.hasMatricesIndices) {
  15638. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15639. }
  15640. if (parsedVertexData.hasMatricesWeights) {
  15641. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15642. }
  15643. geometry._delayLoadingFunction = importVertexData;
  15644. } else {
  15645. importVertexData(parsedVertexData, geometry);
  15646. }
  15647. scene.pushGeometry(geometry, true);
  15648. return geometry;
  15649. };
  15650. var parseMesh = function (parsedMesh, scene, rootUrl) {
  15651. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  15652. mesh.id = parsedMesh.id;
  15653. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15654. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15655. if (parsedMesh.rotationQuaternion) {
  15656. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15657. } else if (parsedMesh.rotation) {
  15658. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15659. }
  15660. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15661. if (parsedMesh.localMatrix) {
  15662. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15663. } else if (parsedMesh.pivotMatrix) {
  15664. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15665. }
  15666. mesh.setEnabled(parsedMesh.isEnabled);
  15667. mesh.isVisible = parsedMesh.isVisible;
  15668. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15669. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15670. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15671. if (parsedMesh.pickable !== undefined) {
  15672. mesh.isPickable = parsedMesh.pickable;
  15673. }
  15674. mesh.receiveShadows = parsedMesh.receiveShadows;
  15675. mesh.billboardMode = parsedMesh.billboardMode;
  15676. if (parsedMesh.visibility !== undefined) {
  15677. mesh.visibility = parsedMesh.visibility;
  15678. }
  15679. mesh.checkCollisions = parsedMesh.checkCollisions;
  15680. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15681. if (parsedMesh.parentId) {
  15682. mesh._waitingParentId = parsedMesh.parentId;
  15683. }
  15684. if (parsedMesh.delayLoadingFile) {
  15685. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15686. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15687. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15688. if (parsedMesh._binaryInfo) {
  15689. mesh._binaryInfo = parsedMesh._binaryInfo;
  15690. }
  15691. mesh._delayInfo = [];
  15692. if (parsedMesh.hasUVs) {
  15693. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15694. }
  15695. if (parsedMesh.hasUVs2) {
  15696. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15697. }
  15698. if (parsedMesh.hasColors) {
  15699. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15700. }
  15701. if (parsedMesh.hasMatricesIndices) {
  15702. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15703. }
  15704. if (parsedMesh.hasMatricesWeights) {
  15705. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15706. }
  15707. mesh._delayLoadingFunction = importGeometry;
  15708. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15709. mesh._checkDelayState();
  15710. }
  15711. } else {
  15712. importGeometry(parsedMesh, mesh);
  15713. }
  15714. if (parsedMesh.materialId) {
  15715. mesh.setMaterialByID(parsedMesh.materialId);
  15716. } else {
  15717. mesh.material = null;
  15718. }
  15719. if (parsedMesh.skeletonId > -1) {
  15720. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15721. }
  15722. if (parsedMesh.physicsImpostor) {
  15723. if (!scene.isPhysicsEnabled()) {
  15724. scene.enablePhysics();
  15725. }
  15726. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15727. }
  15728. if (parsedMesh.animations) {
  15729. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15730. var parsedAnimation = parsedMesh.animations[animationIndex];
  15731. mesh.animations.push(parseAnimation(parsedAnimation));
  15732. }
  15733. }
  15734. if (parsedMesh.autoAnimate) {
  15735. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15736. }
  15737. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15738. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15739. } else {
  15740. mesh.layerMask = 0xFFFFFFFF;
  15741. }
  15742. if (parsedMesh.instances) {
  15743. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15744. var parsedInstance = parsedMesh.instances[index];
  15745. var instance = mesh.createInstance(parsedInstance.name);
  15746. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  15747. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  15748. if (parsedInstance.rotationQuaternion) {
  15749. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  15750. } else if (parsedInstance.rotation) {
  15751. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  15752. }
  15753. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  15754. instance.checkCollisions = mesh.checkCollisions;
  15755. if (parsedMesh.animations) {
  15756. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15757. parsedAnimation = parsedMesh.animations[animationIndex];
  15758. instance.animations.push(parseAnimation(parsedAnimation));
  15759. }
  15760. }
  15761. }
  15762. }
  15763. return mesh;
  15764. };
  15765. var isDescendantOf = function (mesh, names, hierarchyIds) {
  15766. names = (names instanceof Array) ? names : [names];
  15767. for (var i in names) {
  15768. if (mesh.name === names[i]) {
  15769. hierarchyIds.push(mesh.id);
  15770. return true;
  15771. }
  15772. }
  15773. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  15774. hierarchyIds.push(mesh.id);
  15775. return true;
  15776. }
  15777. return false;
  15778. };
  15779. var importVertexData = function (parsedVertexData, geometry) {
  15780. var vertexData = new BABYLON.VertexData();
  15781. var positions = parsedVertexData.positions;
  15782. if (positions) {
  15783. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  15784. }
  15785. var normals = parsedVertexData.normals;
  15786. if (normals) {
  15787. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  15788. }
  15789. var uvs = parsedVertexData.uvs;
  15790. if (uvs) {
  15791. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  15792. }
  15793. var uv2s = parsedVertexData.uv2s;
  15794. if (uv2s) {
  15795. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  15796. }
  15797. var colors = parsedVertexData.colors;
  15798. if (colors) {
  15799. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  15800. }
  15801. var matricesIndices = parsedVertexData.matricesIndices;
  15802. if (matricesIndices) {
  15803. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  15804. }
  15805. var matricesWeights = parsedVertexData.matricesWeights;
  15806. if (matricesWeights) {
  15807. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  15808. }
  15809. var indices = parsedVertexData.indices;
  15810. if (indices) {
  15811. vertexData.indices = indices;
  15812. }
  15813. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  15814. };
  15815. var importGeometry = function (parsedGeometry, mesh) {
  15816. var scene = mesh.getScene();
  15817. var geometryId = parsedGeometry.geometryId;
  15818. if (geometryId) {
  15819. var geometry = scene.getGeometryByID(geometryId);
  15820. if (geometry) {
  15821. geometry.applyToMesh(mesh);
  15822. }
  15823. } else if (parsedGeometry instanceof ArrayBuffer) {
  15824. var binaryInfo = mesh._binaryInfo;
  15825. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  15826. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  15827. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  15828. }
  15829. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  15830. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  15831. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  15832. }
  15833. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  15834. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  15835. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  15836. }
  15837. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  15838. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  15839. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  15840. }
  15841. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  15842. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  15843. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  15844. }
  15845. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  15846. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  15847. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  15848. }
  15849. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  15850. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  15851. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  15852. }
  15853. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  15854. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  15855. mesh.setIndices(indicesData);
  15856. }
  15857. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  15858. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  15859. mesh.subMeshes = [];
  15860. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  15861. var materialIndex = subMeshesData[(i * 5) + 0];
  15862. var verticesStart = subMeshesData[(i * 5) + 1];
  15863. var verticesCount = subMeshesData[(i * 5) + 2];
  15864. var indexStart = subMeshesData[(i * 5) + 3];
  15865. var indexCount = subMeshesData[(i * 5) + 4];
  15866. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  15867. }
  15868. }
  15869. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  15870. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  15871. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  15872. if (parsedGeometry.uvs) {
  15873. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  15874. }
  15875. if (parsedGeometry.uvs2) {
  15876. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  15877. }
  15878. if (parsedGeometry.colors) {
  15879. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, parsedGeometry.colors, false);
  15880. }
  15881. if (parsedGeometry.matricesIndices) {
  15882. if (!parsedGeometry.matricesIndices._isExpanded) {
  15883. var floatIndices = [];
  15884. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  15885. var matricesIndex = parsedGeometry.matricesIndices[i];
  15886. floatIndices.push(matricesIndex & 0x000000FF);
  15887. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  15888. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  15889. floatIndices.push(matricesIndex >> 24);
  15890. }
  15891. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  15892. } else {
  15893. delete parsedGeometry.matricesIndices._isExpanded;
  15894. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  15895. }
  15896. }
  15897. if (parsedGeometry.matricesWeights) {
  15898. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  15899. }
  15900. mesh.setIndices(parsedGeometry.indices);
  15901. if (parsedGeometry.subMeshes) {
  15902. mesh.subMeshes = [];
  15903. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  15904. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  15905. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  15906. }
  15907. }
  15908. }
  15909. if (mesh._shouldGenerateFlatShading) {
  15910. mesh.convertToFlatShadedMesh();
  15911. delete mesh._shouldGenerateFlatShading;
  15912. }
  15913. mesh.computeWorldMatrix(true);
  15914. if (scene._selectionOctree) {
  15915. scene._selectionOctree.addMesh(mesh);
  15916. }
  15917. };
  15918. BABYLON.SceneLoader.RegisterPlugin({
  15919. extensions: ".babylon",
  15920. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  15921. var parsedData = JSON.parse(data);
  15922. var loadedSkeletonsIds = [];
  15923. var loadedMaterialsIds = [];
  15924. var hierarchyIds = [];
  15925. for (var index = 0; index < parsedData.meshes.length; index++) {
  15926. var parsedMesh = parsedData.meshes[index];
  15927. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  15928. if (meshesNames instanceof Array) {
  15929. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  15930. }
  15931. if (parsedMesh.materialId) {
  15932. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  15933. if (!materialFound) {
  15934. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  15935. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  15936. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  15937. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  15938. var subMatId = parsedMultiMaterial.materials[matIndex];
  15939. loadedMaterialsIds.push(subMatId);
  15940. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  15941. }
  15942. loadedMaterialsIds.push(parsedMultiMaterial.id);
  15943. parseMultiMaterial(parsedMultiMaterial, scene);
  15944. materialFound = true;
  15945. break;
  15946. }
  15947. }
  15948. }
  15949. if (!materialFound) {
  15950. loadedMaterialsIds.push(parsedMesh.materialId);
  15951. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  15952. }
  15953. }
  15954. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  15955. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  15956. if (!skeletonAlreadyLoaded) {
  15957. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  15958. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  15959. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  15960. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  15961. loadedSkeletonsIds.push(parsedSkeleton.id);
  15962. }
  15963. }
  15964. }
  15965. }
  15966. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  15967. meshes.push(mesh);
  15968. }
  15969. }
  15970. for (index = 0; index < scene.meshes.length; index++) {
  15971. var currentMesh = scene.meshes[index];
  15972. if (currentMesh._waitingParentId) {
  15973. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  15974. currentMesh._waitingParentId = undefined;
  15975. }
  15976. }
  15977. if (parsedData.particleSystems) {
  15978. for (index = 0; index < parsedData.particleSystems.length; index++) {
  15979. var parsedParticleSystem = parsedData.particleSystems[index];
  15980. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  15981. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  15982. }
  15983. }
  15984. }
  15985. return true;
  15986. },
  15987. load: function (scene, data, rootUrl) {
  15988. var parsedData = JSON.parse(data);
  15989. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  15990. scene.autoClear = parsedData.autoClear;
  15991. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  15992. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  15993. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  15994. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  15995. scene.fogMode = parsedData.fogMode;
  15996. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  15997. scene.fogStart = parsedData.fogStart;
  15998. scene.fogEnd = parsedData.fogEnd;
  15999. scene.fogDensity = parsedData.fogDensity;
  16000. }
  16001. for (var index = 0; index < parsedData.lights.length; index++) {
  16002. var parsedLight = parsedData.lights[index];
  16003. parseLight(parsedLight, scene);
  16004. }
  16005. if (parsedData.materials) {
  16006. for (index = 0; index < parsedData.materials.length; index++) {
  16007. var parsedMaterial = parsedData.materials[index];
  16008. parseMaterial(parsedMaterial, scene, rootUrl);
  16009. }
  16010. }
  16011. if (parsedData.multiMaterials) {
  16012. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  16013. var parsedMultiMaterial = parsedData.multiMaterials[index];
  16014. parseMultiMaterial(parsedMultiMaterial, scene);
  16015. }
  16016. }
  16017. if (parsedData.skeletons) {
  16018. for (index = 0; index < parsedData.skeletons.length; index++) {
  16019. var parsedSkeleton = parsedData.skeletons[index];
  16020. parseSkeleton(parsedSkeleton, scene);
  16021. }
  16022. }
  16023. var geometries = parsedData.geometries;
  16024. if (geometries) {
  16025. var boxes = geometries.boxes;
  16026. if (boxes) {
  16027. for (index = 0; index < boxes.length; index++) {
  16028. var parsedBox = boxes[index];
  16029. parseBox(parsedBox, scene);
  16030. }
  16031. }
  16032. var spheres = geometries.spheres;
  16033. if (spheres) {
  16034. for (index = 0; index < spheres.length; index++) {
  16035. var parsedSphere = spheres[index];
  16036. parseSphere(parsedSphere, scene);
  16037. }
  16038. }
  16039. var cylinders = geometries.cylinders;
  16040. if (cylinders) {
  16041. for (index = 0; index < cylinders.length; index++) {
  16042. var parsedCylinder = cylinders[index];
  16043. parseCylinder(parsedCylinder, scene);
  16044. }
  16045. }
  16046. var toruses = geometries.toruses;
  16047. if (toruses) {
  16048. for (index = 0; index < toruses.length; index++) {
  16049. var parsedTorus = toruses[index];
  16050. parseTorus(parsedTorus, scene);
  16051. }
  16052. }
  16053. var grounds = geometries.grounds;
  16054. if (grounds) {
  16055. for (index = 0; index < grounds.length; index++) {
  16056. var parsedGround = grounds[index];
  16057. parseGround(parsedGround, scene);
  16058. }
  16059. }
  16060. var planes = geometries.planes;
  16061. if (planes) {
  16062. for (index = 0; index < planes.length; index++) {
  16063. var parsedPlane = planes[index];
  16064. parsePlane(parsedPlane, scene);
  16065. }
  16066. }
  16067. var torusKnots = geometries.torusKnots;
  16068. if (torusKnots) {
  16069. for (index = 0; index < torusKnots.length; index++) {
  16070. var parsedTorusKnot = torusKnots[index];
  16071. parseTorusKnot(parsedTorusKnot, scene);
  16072. }
  16073. }
  16074. var vertexData = geometries.vertexData;
  16075. if (vertexData) {
  16076. for (index = 0; index < vertexData.length; index++) {
  16077. var parsedVertexData = vertexData[index];
  16078. parseVertexData(parsedVertexData, scene, rootUrl);
  16079. }
  16080. }
  16081. }
  16082. for (index = 0; index < parsedData.meshes.length; index++) {
  16083. var parsedMesh = parsedData.meshes[index];
  16084. parseMesh(parsedMesh, scene, rootUrl);
  16085. }
  16086. for (index = 0; index < parsedData.cameras.length; index++) {
  16087. var parsedCamera = parsedData.cameras[index];
  16088. parseCamera(parsedCamera, scene);
  16089. }
  16090. if (parsedData.activeCameraID) {
  16091. scene.setActiveCameraByID(parsedData.activeCameraID);
  16092. }
  16093. for (index = 0; index < scene.cameras.length; index++) {
  16094. var camera = scene.cameras[index];
  16095. if (camera._waitingParentId) {
  16096. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  16097. camera._waitingParentId = undefined;
  16098. }
  16099. }
  16100. for (index = 0; index < scene.meshes.length; index++) {
  16101. var mesh = scene.meshes[index];
  16102. if (mesh._waitingParentId) {
  16103. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  16104. mesh._waitingParentId = undefined;
  16105. }
  16106. }
  16107. if (parsedData.particleSystems) {
  16108. for (index = 0; index < parsedData.particleSystems.length; index++) {
  16109. var parsedParticleSystem = parsedData.particleSystems[index];
  16110. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  16111. }
  16112. }
  16113. if (parsedData.lensFlareSystems) {
  16114. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  16115. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  16116. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  16117. }
  16118. }
  16119. if (parsedData.shadowGenerators) {
  16120. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  16121. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  16122. parseShadowGenerator(parsedShadowGenerator, scene);
  16123. }
  16124. }
  16125. return true;
  16126. }
  16127. });
  16128. })(BABYLON.Internals || (BABYLON.Internals = {}));
  16129. var Internals = BABYLON.Internals;
  16130. })(BABYLON || (BABYLON = {}));
  16131. var BABYLON;
  16132. (function (BABYLON) {
  16133. var currentCSGMeshId = 0;
  16134. var Vertex = (function () {
  16135. function Vertex(pos, normal, uv) {
  16136. this.pos = pos;
  16137. this.normal = normal;
  16138. this.uv = uv;
  16139. }
  16140. Vertex.prototype.clone = function () {
  16141. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  16142. };
  16143. Vertex.prototype.flip = function () {
  16144. this.normal = this.normal.scale(-1);
  16145. };
  16146. Vertex.prototype.interpolate = function (other, t) {
  16147. 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));
  16148. };
  16149. return Vertex;
  16150. })();
  16151. var Plane = (function () {
  16152. function Plane(normal, w) {
  16153. this.normal = normal;
  16154. this.w = w;
  16155. }
  16156. Plane.FromPoints = function (a, b, c) {
  16157. var v0 = c.subtract(a);
  16158. var v1 = b.subtract(a);
  16159. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  16160. return null;
  16161. }
  16162. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  16163. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  16164. };
  16165. Plane.prototype.clone = function () {
  16166. return new Plane(this.normal.clone(), this.w);
  16167. };
  16168. Plane.prototype.flip = function () {
  16169. this.normal.scaleInPlace(-1);
  16170. this.w = -this.w;
  16171. };
  16172. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  16173. var COPLANAR = 0;
  16174. var FRONT = 1;
  16175. var BACK = 2;
  16176. var SPANNING = 3;
  16177. var polygonType = 0;
  16178. var types = [];
  16179. for (var i = 0; i < polygon.vertices.length; i++) {
  16180. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  16181. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  16182. polygonType |= type;
  16183. types.push(type);
  16184. }
  16185. switch (polygonType) {
  16186. case COPLANAR:
  16187. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  16188. break;
  16189. case FRONT:
  16190. front.push(polygon);
  16191. break;
  16192. case BACK:
  16193. back.push(polygon);
  16194. break;
  16195. case SPANNING:
  16196. var f = [], b = [];
  16197. for (i = 0; i < polygon.vertices.length; i++) {
  16198. var j = (i + 1) % polygon.vertices.length;
  16199. var ti = types[i], tj = types[j];
  16200. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  16201. if (ti != BACK)
  16202. f.push(vi);
  16203. if (ti != FRONT)
  16204. b.push(ti != BACK ? vi.clone() : vi);
  16205. if ((ti | tj) == SPANNING) {
  16206. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  16207. var v = vi.interpolate(vj, t);
  16208. f.push(v);
  16209. b.push(v.clone());
  16210. }
  16211. }
  16212. if (f.length >= 3) {
  16213. var poly = new Polygon(f, polygon.shared);
  16214. if (poly.plane)
  16215. front.push(poly);
  16216. }
  16217. if (b.length >= 3) {
  16218. poly = new Polygon(b, polygon.shared);
  16219. if (poly.plane)
  16220. back.push(poly);
  16221. }
  16222. break;
  16223. }
  16224. };
  16225. Plane.EPSILON = 1e-5;
  16226. return Plane;
  16227. })();
  16228. var Polygon = (function () {
  16229. function Polygon(vertices, shared) {
  16230. this.vertices = vertices;
  16231. this.shared = shared;
  16232. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  16233. }
  16234. Polygon.prototype.clone = function () {
  16235. var vertices = this.vertices.map(function (v) {
  16236. return v.clone();
  16237. });
  16238. return new Polygon(vertices, this.shared);
  16239. };
  16240. Polygon.prototype.flip = function () {
  16241. this.vertices.reverse().map(function (v) {
  16242. v.flip();
  16243. });
  16244. this.plane.flip();
  16245. };
  16246. return Polygon;
  16247. })();
  16248. var Node = (function () {
  16249. function Node(polygons) {
  16250. this.plane = null;
  16251. this.front = null;
  16252. this.back = null;
  16253. this.polygons = [];
  16254. if (polygons) {
  16255. this.build(polygons);
  16256. }
  16257. }
  16258. Node.prototype.clone = function () {
  16259. var node = new Node();
  16260. node.plane = this.plane && this.plane.clone();
  16261. node.front = this.front && this.front.clone();
  16262. node.back = this.back && this.back.clone();
  16263. node.polygons = this.polygons.map(function (p) {
  16264. return p.clone();
  16265. });
  16266. return node;
  16267. };
  16268. Node.prototype.invert = function () {
  16269. for (var i = 0; i < this.polygons.length; i++) {
  16270. this.polygons[i].flip();
  16271. }
  16272. if (this.plane) {
  16273. this.plane.flip();
  16274. }
  16275. if (this.front) {
  16276. this.front.invert();
  16277. }
  16278. if (this.back) {
  16279. this.back.invert();
  16280. }
  16281. var temp = this.front;
  16282. this.front = this.back;
  16283. this.back = temp;
  16284. };
  16285. Node.prototype.clipPolygons = function (polygons) {
  16286. if (!this.plane)
  16287. return polygons.slice();
  16288. var front = [], back = [];
  16289. for (var i = 0; i < polygons.length; i++) {
  16290. this.plane.splitPolygon(polygons[i], front, back, front, back);
  16291. }
  16292. if (this.front) {
  16293. front = this.front.clipPolygons(front);
  16294. }
  16295. if (this.back) {
  16296. back = this.back.clipPolygons(back);
  16297. } else {
  16298. back = [];
  16299. }
  16300. return front.concat(back);
  16301. };
  16302. Node.prototype.clipTo = function (bsp) {
  16303. this.polygons = bsp.clipPolygons(this.polygons);
  16304. if (this.front)
  16305. this.front.clipTo(bsp);
  16306. if (this.back)
  16307. this.back.clipTo(bsp);
  16308. };
  16309. Node.prototype.allPolygons = function () {
  16310. var polygons = this.polygons.slice();
  16311. if (this.front)
  16312. polygons = polygons.concat(this.front.allPolygons());
  16313. if (this.back)
  16314. polygons = polygons.concat(this.back.allPolygons());
  16315. return polygons;
  16316. };
  16317. Node.prototype.build = function (polygons) {
  16318. if (!polygons.length)
  16319. return;
  16320. if (!this.plane)
  16321. this.plane = polygons[0].plane.clone();
  16322. var front = [], back = [];
  16323. for (var i = 0; i < polygons.length; i++) {
  16324. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  16325. }
  16326. if (front.length) {
  16327. if (!this.front)
  16328. this.front = new Node();
  16329. this.front.build(front);
  16330. }
  16331. if (back.length) {
  16332. if (!this.back)
  16333. this.back = new Node();
  16334. this.back.build(back);
  16335. }
  16336. };
  16337. return Node;
  16338. })();
  16339. var CSG = (function () {
  16340. function CSG() {
  16341. this.polygons = new Array();
  16342. }
  16343. CSG.FromMesh = function (mesh) {
  16344. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  16345. if (mesh instanceof BABYLON.Mesh) {
  16346. mesh.computeWorldMatrix(true);
  16347. var matrix = mesh.getWorldMatrix();
  16348. var meshPosition = mesh.position.clone();
  16349. var meshRotation = mesh.rotation.clone();
  16350. var meshScaling = mesh.scaling.clone();
  16351. } else {
  16352. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  16353. }
  16354. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16355. var subMeshes = mesh.subMeshes;
  16356. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  16357. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  16358. vertices = [];
  16359. for (var j = 0; j < 3; j++) {
  16360. normal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  16361. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  16362. position = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  16363. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, position);
  16364. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  16365. vertex = new Vertex(position, normal, uv);
  16366. vertices.push(vertex);
  16367. }
  16368. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  16369. if (polygon.plane)
  16370. polygons.push(polygon);
  16371. }
  16372. }
  16373. var csg = CSG.FromPolygons(polygons);
  16374. csg.matrix = matrix;
  16375. csg.position = meshPosition;
  16376. csg.rotation = meshRotation;
  16377. csg.scaling = meshScaling;
  16378. currentCSGMeshId++;
  16379. return csg;
  16380. };
  16381. CSG.FromPolygons = function (polygons) {
  16382. var csg = new BABYLON.CSG();
  16383. csg.polygons = polygons;
  16384. return csg;
  16385. };
  16386. CSG.prototype.clone = function () {
  16387. var csg = new BABYLON.CSG();
  16388. csg.polygons = this.polygons.map(function (p) {
  16389. return p.clone();
  16390. });
  16391. csg.copyTransformAttributes(this);
  16392. return csg;
  16393. };
  16394. CSG.prototype.toPolygons = function () {
  16395. return this.polygons;
  16396. };
  16397. CSG.prototype.union = function (csg) {
  16398. var a = new Node(this.clone().polygons);
  16399. var b = new Node(csg.clone().polygons);
  16400. a.clipTo(b);
  16401. b.clipTo(a);
  16402. b.invert();
  16403. b.clipTo(a);
  16404. b.invert();
  16405. a.build(b.allPolygons());
  16406. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  16407. };
  16408. CSG.prototype.unionInPlace = function (csg) {
  16409. var a = new Node(this.polygons);
  16410. var b = new Node(csg.polygons);
  16411. a.clipTo(b);
  16412. b.clipTo(a);
  16413. b.invert();
  16414. b.clipTo(a);
  16415. b.invert();
  16416. a.build(b.allPolygons());
  16417. this.polygons = a.allPolygons();
  16418. };
  16419. CSG.prototype.subtract = function (csg) {
  16420. var a = new Node(this.clone().polygons);
  16421. var b = new Node(csg.clone().polygons);
  16422. a.invert();
  16423. a.clipTo(b);
  16424. b.clipTo(a);
  16425. b.invert();
  16426. b.clipTo(a);
  16427. b.invert();
  16428. a.build(b.allPolygons());
  16429. a.invert();
  16430. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  16431. };
  16432. CSG.prototype.subtractInPlace = function (csg) {
  16433. var a = new Node(this.polygons);
  16434. var b = new Node(csg.polygons);
  16435. a.invert();
  16436. a.clipTo(b);
  16437. b.clipTo(a);
  16438. b.invert();
  16439. b.clipTo(a);
  16440. b.invert();
  16441. a.build(b.allPolygons());
  16442. a.invert();
  16443. this.polygons = a.allPolygons();
  16444. };
  16445. CSG.prototype.intersect = function (csg) {
  16446. var a = new Node(this.clone().polygons);
  16447. var b = new Node(csg.clone().polygons);
  16448. a.invert();
  16449. b.clipTo(a);
  16450. b.invert();
  16451. a.clipTo(b);
  16452. b.clipTo(a);
  16453. a.build(b.allPolygons());
  16454. a.invert();
  16455. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  16456. };
  16457. CSG.prototype.intersectInPlace = function (csg) {
  16458. var a = new Node(this.polygons);
  16459. var b = new Node(csg.polygons);
  16460. a.invert();
  16461. b.clipTo(a);
  16462. b.invert();
  16463. a.clipTo(b);
  16464. b.clipTo(a);
  16465. a.build(b.allPolygons());
  16466. a.invert();
  16467. this.polygons = a.allPolygons();
  16468. };
  16469. CSG.prototype.inverse = function () {
  16470. var csg = this.clone();
  16471. csg.inverseInPlace();
  16472. return csg;
  16473. };
  16474. CSG.prototype.inverseInPlace = function () {
  16475. this.polygons.map(function (p) {
  16476. p.flip();
  16477. });
  16478. };
  16479. CSG.prototype.copyTransformAttributes = function (csg) {
  16480. this.matrix = csg.matrix;
  16481. this.position = csg.position;
  16482. this.rotation = csg.rotation;
  16483. this.scaling = csg.scaling;
  16484. return this;
  16485. };
  16486. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  16487. var matrix = this.matrix.clone();
  16488. matrix.invert();
  16489. 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;
  16490. if (keepSubMeshes) {
  16491. polygons.sort(function (a, b) {
  16492. if (a.shared.meshId === b.shared.meshId) {
  16493. return a.shared.subMeshId - b.shared.subMeshId;
  16494. } else {
  16495. return a.shared.meshId - b.shared.meshId;
  16496. }
  16497. });
  16498. }
  16499. for (var i = 0, il = polygons.length; i < il; i++) {
  16500. polygon = polygons[i];
  16501. if (!subMesh_dict[polygon.shared.meshId]) {
  16502. subMesh_dict[polygon.shared.meshId] = {};
  16503. }
  16504. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  16505. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  16506. indexStart: +Infinity,
  16507. indexEnd: -Infinity,
  16508. materialIndex: polygon.shared.materialIndex
  16509. };
  16510. }
  16511. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  16512. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  16513. polygonIndices[0] = 0;
  16514. polygonIndices[1] = j - 1;
  16515. polygonIndices[2] = j;
  16516. for (var k = 0; k < 3; k++) {
  16517. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  16518. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  16519. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  16520. BABYLON.Vector3.TransformCoordinatesToRef(vertex, matrix, vertex);
  16521. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  16522. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z];
  16523. if (!(typeof vertex_idx !== 'undefined' && normals[vertex_idx * 3] === normal.x && normals[vertex_idx * 3 + 1] === normal.y && normals[vertex_idx * 3 + 2] === normal.z && uvs[vertex_idx * 2] === uv.x && uvs[vertex_idx * 2 + 1] === uv.y)) {
  16524. vertices.push(vertex.x, vertex.y, vertex.z);
  16525. uvs.push(uv.x, uv.y);
  16526. normals.push(normal.x, normal.y, normal.z);
  16527. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z] = (vertices.length / 3) - 1;
  16528. }
  16529. indices.push(vertex_idx);
  16530. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  16531. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  16532. currentIndex++;
  16533. }
  16534. }
  16535. }
  16536. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  16537. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  16538. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  16539. mesh.setIndices(indices);
  16540. if (keepSubMeshes) {
  16541. var materialIndexOffset = 0, materialMaxIndex;
  16542. mesh.subMeshes.length = 0;
  16543. for (var m in subMesh_dict) {
  16544. materialMaxIndex = -1;
  16545. for (var sm in subMesh_dict[m]) {
  16546. subMesh_obj = subMesh_dict[m][sm];
  16547. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  16548. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  16549. }
  16550. materialIndexOffset += ++materialMaxIndex;
  16551. }
  16552. }
  16553. return mesh;
  16554. };
  16555. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  16556. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  16557. mesh.material = material;
  16558. mesh.position.copyFrom(this.position);
  16559. mesh.rotation.copyFrom(this.rotation);
  16560. mesh.scaling.copyFrom(this.scaling);
  16561. mesh.computeWorldMatrix(true);
  16562. return mesh;
  16563. };
  16564. return CSG;
  16565. })();
  16566. BABYLON.CSG = CSG;
  16567. })(BABYLON || (BABYLON = {}));
  16568. var __extends = this.__extends || function (d, b) {
  16569. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16570. function __() { this.constructor = d; }
  16571. __.prototype = b.prototype;
  16572. d.prototype = new __();
  16573. };
  16574. var BABYLON;
  16575. (function (BABYLON) {
  16576. var OculusDistortionCorrectionPostProcess = (function (_super) {
  16577. __extends(OculusDistortionCorrectionPostProcess, _super);
  16578. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  16579. var _this = this;
  16580. _super.call(this, name, "oculusDistortionCorrection", [
  16581. 'LensCenter',
  16582. 'Scale',
  16583. 'ScaleIn',
  16584. 'HmdWarpParam'
  16585. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  16586. this._isRightEye = isRightEye;
  16587. this._distortionFactors = cameraSettings.DistortionK;
  16588. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  16589. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  16590. this.onSizeChanged = function () {
  16591. _this.aspectRatio = _this.width * .5 / _this.height;
  16592. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  16593. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  16594. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  16595. };
  16596. this.onApply = function (effect) {
  16597. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  16598. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  16599. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  16600. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  16601. };
  16602. }
  16603. return OculusDistortionCorrectionPostProcess;
  16604. })(BABYLON.PostProcess);
  16605. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  16606. })(BABYLON || (BABYLON = {}));
  16607. var BABYLON;
  16608. (function (BABYLON) {
  16609. (function (JoystickAxis) {
  16610. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  16611. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  16612. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  16613. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  16614. var JoystickAxis = BABYLON.JoystickAxis;
  16615. var VirtualJoystick = (function () {
  16616. function VirtualJoystick(leftJoystick) {
  16617. var _this = this;
  16618. if (leftJoystick) {
  16619. this._leftJoystick = true;
  16620. } else {
  16621. this._leftJoystick = false;
  16622. }
  16623. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  16624. VirtualJoystick._globalJoystickIndex++;
  16625. this._axisTargetedByLeftAndRight = 0 /* X */;
  16626. this._axisTargetedByUpAndDown = 1 /* Y */;
  16627. this.reverseLeftRight = false;
  16628. this.reverseUpDown = false;
  16629. this._touches = new BABYLON.VirtualJoystick.Collection();
  16630. this.deltaPosition = BABYLON.Vector3.Zero();
  16631. this._joystickSensibility = 25;
  16632. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  16633. this._rotationSpeed = 25;
  16634. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  16635. this._rotateOnAxisRelativeToMesh = false;
  16636. if (!VirtualJoystick.vjCanvas) {
  16637. window.addEventListener("resize", function () {
  16638. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  16639. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  16640. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  16641. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  16642. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  16643. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  16644. }, false);
  16645. VirtualJoystick.vjCanvas = document.createElement("canvas");
  16646. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  16647. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  16648. VirtualJoystick.vjCanvas.width = window.innerWidth;
  16649. VirtualJoystick.vjCanvas.height = window.innerHeight;
  16650. VirtualJoystick.vjCanvas.style.width = "100%";
  16651. VirtualJoystick.vjCanvas.style.height = "100%";
  16652. VirtualJoystick.vjCanvas.style.position = "absolute";
  16653. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  16654. VirtualJoystick.vjCanvas.style.top = "0px";
  16655. VirtualJoystick.vjCanvas.style.left = "0px";
  16656. VirtualJoystick.vjCanvas.style.zIndex = "5";
  16657. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  16658. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  16659. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  16660. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  16661. document.body.appendChild(VirtualJoystick.vjCanvas);
  16662. }
  16663. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  16664. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  16665. this.pressed = false;
  16666. this._joystickColor = "cyan";
  16667. this._joystickPointerID = -1;
  16668. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  16669. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  16670. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  16671. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  16672. _this._onPointerDown(evt);
  16673. }, false);
  16674. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  16675. _this._onPointerMove(evt);
  16676. }, false);
  16677. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  16678. _this._onPointerUp(evt);
  16679. }, false);
  16680. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  16681. _this._onPointerUp(evt);
  16682. }, false);
  16683. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  16684. evt.preventDefault();
  16685. }, false);
  16686. requestAnimationFrame(function () {
  16687. _this._drawVirtualJoystick();
  16688. });
  16689. }
  16690. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  16691. this._joystickSensibility = newJoystickSensibility;
  16692. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  16693. };
  16694. VirtualJoystick.prototype._onPointerDown = function (e) {
  16695. var positionOnScreenCondition;
  16696. e.preventDefault();
  16697. if (this._leftJoystick === true) {
  16698. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  16699. } else {
  16700. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  16701. }
  16702. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  16703. this._joystickPointerID = e.pointerId;
  16704. this._joystickPointerStartPos.x = e.clientX;
  16705. this._joystickPointerStartPos.y = e.clientY;
  16706. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  16707. this._deltaJoystickVector.x = 0;
  16708. this._deltaJoystickVector.y = 0;
  16709. this.pressed = true;
  16710. this._touches.add(e.pointerId.toString(), e);
  16711. } else {
  16712. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  16713. this._action();
  16714. this._touches.add(e.pointerId.toString(), e);
  16715. }
  16716. }
  16717. };
  16718. VirtualJoystick.prototype._onPointerMove = function (e) {
  16719. if (this._joystickPointerID == e.pointerId) {
  16720. this._joystickPointerPos.x = e.clientX;
  16721. this._joystickPointerPos.y = e.clientY;
  16722. this._deltaJoystickVector = this._joystickPointerPos.clone();
  16723. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  16724. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  16725. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  16726. switch (this._axisTargetedByLeftAndRight) {
  16727. case 0 /* X */:
  16728. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  16729. break;
  16730. case 1 /* Y */:
  16731. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  16732. break;
  16733. case 2 /* Z */:
  16734. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  16735. break;
  16736. }
  16737. var directionUpDown = this.reverseUpDown ? 1 : -1;
  16738. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  16739. switch (this._axisTargetedByUpAndDown) {
  16740. case 0 /* X */:
  16741. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  16742. break;
  16743. case 1 /* Y */:
  16744. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  16745. break;
  16746. case 2 /* Z */:
  16747. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  16748. break;
  16749. }
  16750. } else {
  16751. if (this._touches.item(e.pointerId.toString())) {
  16752. this._touches.item(e.pointerId.toString()).x = e.clientX;
  16753. this._touches.item(e.pointerId.toString()).y = e.clientY;
  16754. }
  16755. }
  16756. };
  16757. VirtualJoystick.prototype._onPointerUp = function (e) {
  16758. this._clearCanvas();
  16759. if (this._joystickPointerID == e.pointerId) {
  16760. this._joystickPointerID = -1;
  16761. this.pressed = false;
  16762. }
  16763. this._deltaJoystickVector.x = 0;
  16764. this._deltaJoystickVector.y = 0;
  16765. this._touches.remove(e.pointerId.toString());
  16766. };
  16767. /**
  16768. * Change the color of the virtual joystick
  16769. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  16770. */
  16771. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  16772. this._joystickColor = newColor;
  16773. };
  16774. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  16775. this._action = action;
  16776. };
  16777. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  16778. switch (axis) {
  16779. case 0 /* X */:
  16780. case 1 /* Y */:
  16781. case 2 /* Z */:
  16782. this._axisTargetedByLeftAndRight = axis;
  16783. break;
  16784. default:
  16785. this._axisTargetedByLeftAndRight = 0 /* X */;
  16786. break;
  16787. }
  16788. };
  16789. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  16790. switch (axis) {
  16791. case 0 /* X */:
  16792. case 1 /* Y */:
  16793. case 2 /* Z */:
  16794. this._axisTargetedByUpAndDown = axis;
  16795. break;
  16796. default:
  16797. this._axisTargetedByUpAndDown = 1 /* Y */;
  16798. break;
  16799. }
  16800. };
  16801. VirtualJoystick.prototype._clearCanvas = function () {
  16802. if (this._leftJoystick) {
  16803. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  16804. } else {
  16805. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  16806. }
  16807. };
  16808. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  16809. var _this = this;
  16810. if (this.pressed) {
  16811. this._clearCanvas();
  16812. this._touches.forEach(function (touch) {
  16813. if (touch.pointerId === _this._joystickPointerID) {
  16814. VirtualJoystick.vjCanvasContext.beginPath();
  16815. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16816. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  16817. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  16818. VirtualJoystick.vjCanvasContext.stroke();
  16819. VirtualJoystick.vjCanvasContext.beginPath();
  16820. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16821. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  16822. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  16823. VirtualJoystick.vjCanvasContext.stroke();
  16824. VirtualJoystick.vjCanvasContext.beginPath();
  16825. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16826. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  16827. VirtualJoystick.vjCanvasContext.stroke();
  16828. } else {
  16829. VirtualJoystick.vjCanvasContext.beginPath();
  16830. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  16831. VirtualJoystick.vjCanvasContext.beginPath();
  16832. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  16833. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  16834. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  16835. VirtualJoystick.vjCanvasContext.stroke();
  16836. }
  16837. ;
  16838. });
  16839. }
  16840. requestAnimationFrame(function () {
  16841. _this._drawVirtualJoystick();
  16842. });
  16843. };
  16844. VirtualJoystick.prototype.releaseCanvas = function () {
  16845. if (VirtualJoystick.vjCanvas) {
  16846. document.body.removeChild(VirtualJoystick.vjCanvas);
  16847. VirtualJoystick.vjCanvas = null;
  16848. }
  16849. };
  16850. VirtualJoystick._globalJoystickIndex = 0;
  16851. return VirtualJoystick;
  16852. })();
  16853. BABYLON.VirtualJoystick = VirtualJoystick;
  16854. })(BABYLON || (BABYLON = {}));
  16855. var BABYLON;
  16856. (function (BABYLON) {
  16857. (function (VirtualJoystick) {
  16858. var Collection = (function () {
  16859. function Collection() {
  16860. this._count = 0;
  16861. this._collection = new Array();
  16862. }
  16863. Collection.prototype.Count = function () {
  16864. return this._count;
  16865. };
  16866. Collection.prototype.add = function (key, item) {
  16867. if (this._collection[key] != undefined) {
  16868. return undefined;
  16869. }
  16870. this._collection[key] = item;
  16871. return ++this._count;
  16872. };
  16873. Collection.prototype.remove = function (key) {
  16874. if (this._collection[key] == undefined) {
  16875. return undefined;
  16876. }
  16877. delete this._collection[key];
  16878. return --this._count;
  16879. };
  16880. Collection.prototype.item = function (key) {
  16881. return this._collection[key];
  16882. };
  16883. Collection.prototype.forEach = function (block) {
  16884. var key;
  16885. for (key in this._collection) {
  16886. if (this._collection.hasOwnProperty(key)) {
  16887. block(this._collection[key]);
  16888. }
  16889. }
  16890. };
  16891. return Collection;
  16892. })();
  16893. VirtualJoystick.Collection = Collection;
  16894. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  16895. var VirtualJoystick = BABYLON.VirtualJoystick;
  16896. })(BABYLON || (BABYLON = {}));
  16897. var __extends = this.__extends || function (d, b) {
  16898. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16899. function __() { this.constructor = d; }
  16900. __.prototype = b.prototype;
  16901. d.prototype = new __();
  16902. };
  16903. var BABYLON;
  16904. (function (BABYLON) {
  16905. var OculusRiftDevKit2013_Metric = {
  16906. HResolution: 1280,
  16907. VResolution: 800,
  16908. HScreenSize: 0.149759993,
  16909. VScreenSize: 0.0935999975,
  16910. VScreenCenter: 0.0467999987,
  16911. EyeToScreenDistance: 0.0410000011,
  16912. LensSeparationDistance: 0.0635000020,
  16913. InterpupillaryDistance: 0.0640000030,
  16914. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  16915. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  16916. PostProcessScaleFactor: 1.714605507808412,
  16917. LensCenterOffset: 0.151976421
  16918. };
  16919. var _OculusInnerCamera = (function (_super) {
  16920. __extends(_OculusInnerCamera, _super);
  16921. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  16922. _super.call(this, name, position, scene);
  16923. this._workMatrix = new BABYLON.Matrix();
  16924. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  16925. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  16926. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  16927. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  16928. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  16929. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  16930. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  16931. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  16932. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  16933. }
  16934. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  16935. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  16936. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  16937. return this._projectionMatrix;
  16938. };
  16939. _OculusInnerCamera.prototype._getViewMatrix = function () {
  16940. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  16941. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  16942. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  16943. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  16944. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  16945. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  16946. return this._viewMatrix;
  16947. };
  16948. return _OculusInnerCamera;
  16949. })(BABYLON.FreeCamera);
  16950. var OculusCamera = (function (_super) {
  16951. __extends(OculusCamera, _super);
  16952. function OculusCamera(name, position, scene) {
  16953. _super.call(this, name, position, scene);
  16954. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  16955. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  16956. this.subCameras.push(this._leftCamera);
  16957. this.subCameras.push(this._rightCamera);
  16958. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  16959. }
  16960. OculusCamera.prototype._update = function () {
  16961. this._leftCamera.position.copyFrom(this.position);
  16962. this._rightCamera.position.copyFrom(this.position);
  16963. this._updateCamera(this._leftCamera);
  16964. this._updateCamera(this._rightCamera);
  16965. _super.prototype._update.call(this);
  16966. };
  16967. OculusCamera.prototype._updateCamera = function (camera) {
  16968. camera.minZ = this.minZ;
  16969. camera.maxZ = this.maxZ;
  16970. camera.rotation.x = this.rotation.x;
  16971. camera.rotation.y = this.rotation.y;
  16972. camera.rotation.z = this.rotation.z;
  16973. };
  16974. OculusCamera.prototype._onOrientationEvent = function (evt) {
  16975. var yaw = evt.alpha / 180 * Math.PI;
  16976. var pitch = evt.beta / 180 * Math.PI;
  16977. var roll = evt.gamma / 180 * Math.PI;
  16978. if (!this._offsetOrientation) {
  16979. this._offsetOrientation = {
  16980. yaw: yaw,
  16981. pitch: pitch,
  16982. roll: roll
  16983. };
  16984. return;
  16985. } else {
  16986. this.rotation.y += yaw - this._offsetOrientation.yaw;
  16987. this.rotation.x += pitch - this._offsetOrientation.pitch;
  16988. this.rotation.z += this._offsetOrientation.roll - roll;
  16989. this._offsetOrientation.yaw = yaw;
  16990. this._offsetOrientation.pitch = pitch;
  16991. this._offsetOrientation.roll = roll;
  16992. }
  16993. };
  16994. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  16995. _super.prototype.attachControl.call(this, element, noPreventDefault);
  16996. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  16997. };
  16998. OculusCamera.prototype.detachControl = function (element) {
  16999. _super.prototype.detachControl.call(this, element);
  17000. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  17001. };
  17002. return OculusCamera;
  17003. })(BABYLON.FreeCamera);
  17004. BABYLON.OculusCamera = OculusCamera;
  17005. })(BABYLON || (BABYLON = {}));
  17006. var __extends = this.__extends || function (d, b) {
  17007. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17008. function __() { this.constructor = d; }
  17009. __.prototype = b.prototype;
  17010. d.prototype = new __();
  17011. };
  17012. var BABYLON;
  17013. (function (BABYLON) {
  17014. var OculusRiftDevKit2013_Metric = {
  17015. HResolution: 1280,
  17016. VResolution: 800,
  17017. HScreenSize: 0.149759993,
  17018. VScreenSize: 0.0935999975,
  17019. VScreenCenter: 0.0467999987,
  17020. EyeToScreenDistance: 0.0410000011,
  17021. LensSeparationDistance: 0.0635000020,
  17022. InterpupillaryDistance: 0.0640000030,
  17023. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  17024. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  17025. PostProcessScaleFactor: 1.714605507808412,
  17026. LensCenterOffset: 0.151976421
  17027. };
  17028. var _OculusInnerGamepadCamera = (function (_super) {
  17029. __extends(_OculusInnerGamepadCamera, _super);
  17030. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  17031. _super.call(this, name, position, scene);
  17032. this._workMatrix = new BABYLON.Matrix();
  17033. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  17034. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  17035. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  17036. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  17037. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  17038. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  17039. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  17040. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  17041. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  17042. }
  17043. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  17044. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  17045. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  17046. return this._projectionMatrix;
  17047. };
  17048. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  17049. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  17050. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  17051. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  17052. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  17053. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  17054. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  17055. return this._viewMatrix;
  17056. };
  17057. return _OculusInnerGamepadCamera;
  17058. })(BABYLON.FreeCamera);
  17059. var OculusGamepadCamera = (function (_super) {
  17060. __extends(OculusGamepadCamera, _super);
  17061. function OculusGamepadCamera(name, position, scene) {
  17062. var _this = this;
  17063. _super.call(this, name, position, scene);
  17064. this.angularSensibility = 200;
  17065. this.moveSensibility = 75;
  17066. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  17067. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  17068. this.subCameras.push(this._leftCamera);
  17069. this.subCameras.push(this._rightCamera);
  17070. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  17071. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  17072. _this._onNewGameConnected(gamepad);
  17073. });
  17074. }
  17075. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  17076. if (gamepad.index === 0) {
  17077. this._gamepad = gamepad;
  17078. }
  17079. };
  17080. OculusGamepadCamera.prototype._update = function () {
  17081. this._leftCamera.position.copyFrom(this.position);
  17082. this._rightCamera.position.copyFrom(this.position);
  17083. this._updateCamera(this._leftCamera);
  17084. this._updateCamera(this._rightCamera);
  17085. _super.prototype._update.call(this);
  17086. };
  17087. OculusGamepadCamera.prototype._checkInputs = function () {
  17088. if (!this._gamepad) {
  17089. return;
  17090. }
  17091. var LSValues = this._gamepad.leftStick;
  17092. var normalizedLX = LSValues.x / this.moveSensibility;
  17093. var normalizedLY = LSValues.y / this.moveSensibility;
  17094. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  17095. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  17096. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  17097. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  17098. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  17099. };
  17100. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  17101. camera.minZ = this.minZ;
  17102. camera.maxZ = this.maxZ;
  17103. camera.rotation.x = this.rotation.x;
  17104. camera.rotation.y = this.rotation.y;
  17105. camera.rotation.z = this.rotation.z;
  17106. };
  17107. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  17108. var yaw = evt.alpha / 180 * Math.PI;
  17109. var pitch = evt.beta / 180 * Math.PI;
  17110. var roll = evt.gamma / 180 * Math.PI;
  17111. if (!this._offsetOrientation) {
  17112. this._offsetOrientation = {
  17113. yaw: yaw,
  17114. pitch: pitch,
  17115. roll: roll
  17116. };
  17117. return;
  17118. } else {
  17119. this.rotation.y += yaw - this._offsetOrientation.yaw;
  17120. this.rotation.x += pitch - this._offsetOrientation.pitch;
  17121. this.rotation.z += this._offsetOrientation.roll - roll;
  17122. this._offsetOrientation.yaw = yaw;
  17123. this._offsetOrientation.pitch = pitch;
  17124. this._offsetOrientation.roll = roll;
  17125. }
  17126. };
  17127. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  17128. _super.prototype.attachControl.call(this, element, noPreventDefault);
  17129. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  17130. };
  17131. OculusGamepadCamera.prototype.detachControl = function (element) {
  17132. _super.prototype.detachControl.call(this, element);
  17133. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  17134. };
  17135. OculusGamepadCamera.prototype.dispose = function () {
  17136. this._gamepads.dispose();
  17137. _super.prototype.dispose.call(this);
  17138. };
  17139. return OculusGamepadCamera;
  17140. })(BABYLON.FreeCamera);
  17141. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  17142. })(BABYLON || (BABYLON = {}));
  17143. var __extends = this.__extends || function (d, b) {
  17144. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17145. function __() { this.constructor = d; }
  17146. __.prototype = b.prototype;
  17147. d.prototype = new __();
  17148. };
  17149. var BABYLON;
  17150. (function (BABYLON) {
  17151. var VirtualJoysticksCamera = (function (_super) {
  17152. __extends(VirtualJoysticksCamera, _super);
  17153. function VirtualJoysticksCamera(name, position, scene) {
  17154. _super.call(this, name, position, scene);
  17155. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  17156. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  17157. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  17158. this._leftjoystick.setJoystickSensibility(0.15);
  17159. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  17160. this._rightjoystick.setAxisForUpDown(0 /* X */);
  17161. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  17162. this._rightjoystick.reverseUpDown = true;
  17163. this._rightjoystick.setJoystickSensibility(0.05);
  17164. this._rightjoystick.setJoystickColor("yellow");
  17165. }
  17166. VirtualJoysticksCamera.prototype._checkInputs = function () {
  17167. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  17168. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  17169. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  17170. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  17171. if (!this._leftjoystick.pressed) {
  17172. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  17173. }
  17174. if (!this._rightjoystick.pressed) {
  17175. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  17176. }
  17177. };
  17178. VirtualJoysticksCamera.prototype.dispose = function () {
  17179. this._leftjoystick.releaseCanvas();
  17180. _super.prototype.dispose.call(this);
  17181. };
  17182. return VirtualJoysticksCamera;
  17183. })(BABYLON.FreeCamera);
  17184. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  17185. })(BABYLON || (BABYLON = {}));
  17186. var __extends = this.__extends || function (d, b) {
  17187. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17188. function __() { this.constructor = d; }
  17189. __.prototype = b.prototype;
  17190. d.prototype = new __();
  17191. };
  17192. var BABYLON;
  17193. (function (BABYLON) {
  17194. var ShaderMaterial = (function (_super) {
  17195. __extends(ShaderMaterial, _super);
  17196. function ShaderMaterial(name, scene, shaderPath, options) {
  17197. _super.call(this, name, scene);
  17198. this._textures = new Array();
  17199. this._floats = new Array();
  17200. this._floatsArrays = {};
  17201. this._colors3 = new Array();
  17202. this._colors4 = new Array();
  17203. this._vectors2 = new Array();
  17204. this._vectors3 = new Array();
  17205. this._matrices = new Array();
  17206. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  17207. this._shaderPath = shaderPath;
  17208. options.needAlphaBlending = options.needAlphaBlending || false;
  17209. options.needAlphaTesting = options.needAlphaTesting || false;
  17210. options.attributes = options.attributes || ["position", "normal", "uv"];
  17211. options.uniforms = options.uniforms || ["worldViewProjection"];
  17212. options.samplers = options.samplers || [];
  17213. this._options = options;
  17214. }
  17215. ShaderMaterial.prototype.needAlphaBlending = function () {
  17216. return this._options.needAlphaBlending;
  17217. };
  17218. ShaderMaterial.prototype.needAlphaTesting = function () {
  17219. return this._options.needAlphaTesting;
  17220. };
  17221. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  17222. if (this._options.uniforms.indexOf(uniformName) === -1) {
  17223. this._options.uniforms.push(uniformName);
  17224. }
  17225. };
  17226. ShaderMaterial.prototype.setTexture = function (name, texture) {
  17227. if (this._options.samplers.indexOf(name) === -1) {
  17228. this._options.samplers.push(name);
  17229. }
  17230. this._textures[name] = texture;
  17231. return this;
  17232. };
  17233. ShaderMaterial.prototype.setFloat = function (name, value) {
  17234. this._checkUniform(name);
  17235. this._floats[name] = value;
  17236. return this;
  17237. };
  17238. ShaderMaterial.prototype.setFloats = function (name, value) {
  17239. this._checkUniform(name);
  17240. this._floatsArrays[name] = value;
  17241. return this;
  17242. };
  17243. ShaderMaterial.prototype.setColor3 = function (name, value) {
  17244. this._checkUniform(name);
  17245. this._colors3[name] = value;
  17246. return this;
  17247. };
  17248. ShaderMaterial.prototype.setColor4 = function (name, value) {
  17249. this._checkUniform(name);
  17250. this._colors4[name] = value;
  17251. return this;
  17252. };
  17253. ShaderMaterial.prototype.setVector2 = function (name, value) {
  17254. this._checkUniform(name);
  17255. this._vectors2[name] = value;
  17256. return this;
  17257. };
  17258. ShaderMaterial.prototype.setVector3 = function (name, value) {
  17259. this._checkUniform(name);
  17260. this._vectors3[name] = value;
  17261. return this;
  17262. };
  17263. ShaderMaterial.prototype.setMatrix = function (name, value) {
  17264. this._checkUniform(name);
  17265. this._matrices[name] = value;
  17266. return this;
  17267. };
  17268. ShaderMaterial.prototype.isReady = function () {
  17269. var engine = this.getScene().getEngine();
  17270. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  17271. if (!this._effect.isReady()) {
  17272. return false;
  17273. }
  17274. return true;
  17275. };
  17276. ShaderMaterial.prototype.bind = function (world) {
  17277. if (this._options.uniforms.indexOf("world") !== -1) {
  17278. this._effect.setMatrix("world", world);
  17279. }
  17280. if (this._options.uniforms.indexOf("view") !== -1) {
  17281. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  17282. }
  17283. if (this._options.uniforms.indexOf("worldView") !== -1) {
  17284. world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
  17285. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  17286. }
  17287. if (this._options.uniforms.indexOf("projection") !== -1) {
  17288. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  17289. }
  17290. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  17291. this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
  17292. }
  17293. for (var name in this._textures) {
  17294. this._effect.setTexture(name, this._textures[name]);
  17295. }
  17296. for (name in this._floats) {
  17297. this._effect.setFloat(name, this._floats[name]);
  17298. }
  17299. for (name in this._floatsArrays) {
  17300. this._effect.setArray(name, this._floatsArrays[name]);
  17301. }
  17302. for (name in this._colors3) {
  17303. this._effect.setColor3(name, this._colors3[name]);
  17304. }
  17305. for (name in this._colors4) {
  17306. var color = this._colors4[name];
  17307. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17308. }
  17309. for (name in this._vectors2) {
  17310. this._effect.setVector2(name, this._vectors2[name]);
  17311. }
  17312. for (name in this._vectors3) {
  17313. this._effect.setVector3(name, this._vectors3[name]);
  17314. }
  17315. for (name in this._matrices) {
  17316. this._effect.setMatrix(name, this._matrices[name]);
  17317. }
  17318. };
  17319. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  17320. for (var name in this._textures) {
  17321. this._textures[name].dispose();
  17322. }
  17323. this._textures = [];
  17324. _super.prototype.dispose.call(this, forceDisposeEffect);
  17325. };
  17326. return ShaderMaterial;
  17327. })(BABYLON.Material);
  17328. BABYLON.ShaderMaterial = ShaderMaterial;
  17329. })(BABYLON || (BABYLON = {}));
  17330. var BABYLON;
  17331. (function (BABYLON) {
  17332. var VertexData = (function () {
  17333. function VertexData() {
  17334. }
  17335. VertexData.prototype.set = function (data, kind) {
  17336. switch (kind) {
  17337. case BABYLON.VertexBuffer.PositionKind:
  17338. this.positions = data;
  17339. break;
  17340. case BABYLON.VertexBuffer.NormalKind:
  17341. this.normals = data;
  17342. break;
  17343. case BABYLON.VertexBuffer.UVKind:
  17344. this.uvs = data;
  17345. break;
  17346. case BABYLON.VertexBuffer.UV2Kind:
  17347. this.uv2s = data;
  17348. break;
  17349. case BABYLON.VertexBuffer.ColorKind:
  17350. this.colors = data;
  17351. break;
  17352. case BABYLON.VertexBuffer.MatricesIndicesKind:
  17353. this.matricesIndices = data;
  17354. break;
  17355. case BABYLON.VertexBuffer.MatricesWeightsKind:
  17356. this.matricesWeights = data;
  17357. break;
  17358. }
  17359. };
  17360. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  17361. this._applyTo(mesh, updatable);
  17362. };
  17363. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  17364. this._applyTo(geometry, updatable);
  17365. };
  17366. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  17367. this._update(mesh);
  17368. };
  17369. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  17370. this._update(geometry);
  17371. };
  17372. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  17373. if (this.positions) {
  17374. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  17375. }
  17376. if (this.normals) {
  17377. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  17378. }
  17379. if (this.uvs) {
  17380. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  17381. }
  17382. if (this.uv2s) {
  17383. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  17384. }
  17385. if (this.colors) {
  17386. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  17387. }
  17388. if (this.matricesIndices) {
  17389. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  17390. }
  17391. if (this.matricesWeights) {
  17392. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  17393. }
  17394. if (this.indices) {
  17395. meshOrGeometry.setIndices(this.indices);
  17396. }
  17397. };
  17398. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  17399. if (this.positions) {
  17400. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  17401. }
  17402. if (this.normals) {
  17403. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  17404. }
  17405. if (this.uvs) {
  17406. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  17407. }
  17408. if (this.uv2s) {
  17409. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  17410. }
  17411. if (this.colors) {
  17412. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  17413. }
  17414. if (this.matricesIndices) {
  17415. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  17416. }
  17417. if (this.matricesWeights) {
  17418. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  17419. }
  17420. if (this.indices) {
  17421. meshOrGeometry.setIndices(this.indices);
  17422. }
  17423. };
  17424. VertexData.prototype.transform = function (matrix) {
  17425. var transformed = BABYLON.Vector3.Zero();
  17426. if (this.positions) {
  17427. var position = BABYLON.Vector3.Zero();
  17428. for (var index = 0; index < this.positions.length; index += 3) {
  17429. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  17430. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  17431. this.positions[index] = transformed.x;
  17432. this.positions[index + 1] = transformed.y;
  17433. this.positions[index + 2] = transformed.z;
  17434. }
  17435. }
  17436. if (this.normals) {
  17437. var normal = BABYLON.Vector3.Zero();
  17438. for (index = 0; index < this.normals.length; index += 3) {
  17439. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  17440. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  17441. this.normals[index] = transformed.x;
  17442. this.normals[index + 1] = transformed.y;
  17443. this.normals[index + 2] = transformed.z;
  17444. }
  17445. }
  17446. };
  17447. VertexData.prototype.merge = function (other) {
  17448. if (other.indices) {
  17449. if (!this.indices) {
  17450. this.indices = [];
  17451. }
  17452. var offset = this.positions ? this.positions.length / 3 : 0;
  17453. for (var index = 0; index < other.indices.length; index++) {
  17454. this.indices.push(other.indices[index] + offset);
  17455. }
  17456. }
  17457. if (other.positions) {
  17458. if (!this.positions) {
  17459. this.positions = [];
  17460. }
  17461. for (index = 0; index < other.positions.length; index++) {
  17462. this.positions.push(other.positions[index]);
  17463. }
  17464. }
  17465. if (other.normals) {
  17466. if (!this.normals) {
  17467. this.normals = [];
  17468. }
  17469. for (index = 0; index < other.normals.length; index++) {
  17470. this.normals.push(other.normals[index]);
  17471. }
  17472. }
  17473. if (other.uvs) {
  17474. if (!this.uvs) {
  17475. this.uvs = [];
  17476. }
  17477. for (index = 0; index < other.uvs.length; index++) {
  17478. this.uvs.push(other.uvs[index]);
  17479. }
  17480. }
  17481. if (other.uv2s) {
  17482. if (!this.uv2s) {
  17483. this.uv2s = [];
  17484. }
  17485. for (index = 0; index < other.uv2s.length; index++) {
  17486. this.uv2s.push(other.uv2s[index]);
  17487. }
  17488. }
  17489. if (other.matricesIndices) {
  17490. if (!this.matricesIndices) {
  17491. this.matricesIndices = [];
  17492. }
  17493. for (index = 0; index < other.matricesIndices.length; index++) {
  17494. this.matricesIndices.push(other.matricesIndices[index]);
  17495. }
  17496. }
  17497. if (other.matricesWeights) {
  17498. if (!this.matricesWeights) {
  17499. this.matricesWeights = [];
  17500. }
  17501. for (index = 0; index < other.matricesWeights.length; index++) {
  17502. this.matricesWeights.push(other.matricesWeights[index]);
  17503. }
  17504. }
  17505. if (other.colors) {
  17506. if (!this.colors) {
  17507. this.colors = [];
  17508. }
  17509. for (index = 0; index < other.colors.length; index++) {
  17510. this.colors.push(other.colors[index]);
  17511. }
  17512. }
  17513. };
  17514. VertexData.ExtractFromMesh = function (mesh) {
  17515. return VertexData._ExtractFrom(mesh);
  17516. };
  17517. VertexData.ExtractFromGeometry = function (geometry) {
  17518. return VertexData._ExtractFrom(geometry);
  17519. };
  17520. VertexData._ExtractFrom = function (meshOrGeometry) {
  17521. var result = new BABYLON.VertexData();
  17522. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17523. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17524. }
  17525. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17526. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17527. }
  17528. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17529. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17530. }
  17531. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17532. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  17533. }
  17534. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17535. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  17536. }
  17537. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17538. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17539. }
  17540. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17541. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17542. }
  17543. result.indices = meshOrGeometry.getIndices();
  17544. return result;
  17545. };
  17546. VertexData.CreateBox = function (size) {
  17547. var normalsSource = [
  17548. new BABYLON.Vector3(0, 0, 1),
  17549. new BABYLON.Vector3(0, 0, -1),
  17550. new BABYLON.Vector3(1, 0, 0),
  17551. new BABYLON.Vector3(-1, 0, 0),
  17552. new BABYLON.Vector3(0, 1, 0),
  17553. new BABYLON.Vector3(0, -1, 0)
  17554. ];
  17555. var indices = [];
  17556. var positions = [];
  17557. var normals = [];
  17558. var uvs = [];
  17559. size = size || 1;
  17560. for (var index = 0; index < normalsSource.length; index++) {
  17561. var normal = normalsSource[index];
  17562. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  17563. var side2 = BABYLON.Vector3.Cross(normal, side1);
  17564. var verticesLength = positions.length / 3;
  17565. indices.push(verticesLength);
  17566. indices.push(verticesLength + 1);
  17567. indices.push(verticesLength + 2);
  17568. indices.push(verticesLength);
  17569. indices.push(verticesLength + 2);
  17570. indices.push(verticesLength + 3);
  17571. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  17572. positions.push(vertex.x, vertex.y, vertex.z);
  17573. normals.push(normal.x, normal.y, normal.z);
  17574. uvs.push(1.0, 1.0);
  17575. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  17576. positions.push(vertex.x, vertex.y, vertex.z);
  17577. normals.push(normal.x, normal.y, normal.z);
  17578. uvs.push(0.0, 1.0);
  17579. vertex = normal.add(side1).add(side2).scale(size / 2);
  17580. positions.push(vertex.x, vertex.y, vertex.z);
  17581. normals.push(normal.x, normal.y, normal.z);
  17582. uvs.push(0.0, 0.0);
  17583. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  17584. positions.push(vertex.x, vertex.y, vertex.z);
  17585. normals.push(normal.x, normal.y, normal.z);
  17586. uvs.push(1.0, 0.0);
  17587. }
  17588. var vertexData = new BABYLON.VertexData();
  17589. vertexData.indices = indices;
  17590. vertexData.positions = positions;
  17591. vertexData.normals = normals;
  17592. vertexData.uvs = uvs;
  17593. return vertexData;
  17594. };
  17595. VertexData.CreateSphere = function (segments, diameter) {
  17596. segments = segments || 32;
  17597. diameter = diameter || 1;
  17598. var radius = diameter / 2;
  17599. var totalZRotationSteps = 2 + segments;
  17600. var totalYRotationSteps = 2 * totalZRotationSteps;
  17601. var indices = [];
  17602. var positions = [];
  17603. var normals = [];
  17604. var uvs = [];
  17605. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  17606. var normalizedZ = zRotationStep / totalZRotationSteps;
  17607. var angleZ = (normalizedZ * Math.PI);
  17608. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  17609. var normalizedY = yRotationStep / totalYRotationSteps;
  17610. var angleY = normalizedY * Math.PI * 2;
  17611. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  17612. var rotationY = BABYLON.Matrix.RotationY(angleY);
  17613. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  17614. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  17615. var vertex = complete.scale(radius);
  17616. var normal = BABYLON.Vector3.Normalize(vertex);
  17617. positions.push(vertex.x, vertex.y, vertex.z);
  17618. normals.push(normal.x, normal.y, normal.z);
  17619. uvs.push(normalizedZ, normalizedY);
  17620. }
  17621. if (zRotationStep > 0) {
  17622. var verticesCount = positions.length / 3;
  17623. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  17624. indices.push((firstIndex));
  17625. indices.push((firstIndex + 1));
  17626. indices.push(firstIndex + totalYRotationSteps + 1);
  17627. indices.push((firstIndex + totalYRotationSteps + 1));
  17628. indices.push((firstIndex + 1));
  17629. indices.push((firstIndex + totalYRotationSteps + 2));
  17630. }
  17631. }
  17632. }
  17633. var vertexData = new BABYLON.VertexData();
  17634. vertexData.indices = indices;
  17635. vertexData.positions = positions;
  17636. vertexData.normals = normals;
  17637. vertexData.uvs = uvs;
  17638. return vertexData;
  17639. };
  17640. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  17641. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  17642. var radiusTop = diameterTop / 2;
  17643. var radiusBottom = diameterBottom / 2;
  17644. var indices = [];
  17645. var positions = [];
  17646. var normals = [];
  17647. var uvs = [];
  17648. height = height || 1;
  17649. diameterTop = diameterTop || 0.5;
  17650. diameterBottom = diameterBottom || 1;
  17651. tessellation = tessellation || 16;
  17652. subdivisions = subdivisions || 1;
  17653. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  17654. var getCircleVector = function (i) {
  17655. var angle = (i * 2.0 * Math.PI / tessellation);
  17656. var dx = Math.cos(angle);
  17657. var dz = Math.sin(angle);
  17658. return new BABYLON.Vector3(dx, 0, dz);
  17659. };
  17660. var createCylinderCap = function (isTop) {
  17661. var radius = isTop ? radiusTop : radiusBottom;
  17662. if (radius == 0) {
  17663. return;
  17664. }
  17665. var vbase = positions.length / 3;
  17666. var offset = new BABYLON.Vector3(0, height / 2, 0);
  17667. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  17668. if (!isTop) {
  17669. offset.scaleInPlace(-1);
  17670. textureScale.x = -textureScale.x;
  17671. }
  17672. for (i = 0; i < tessellation; i++) {
  17673. var circleVector = getCircleVector(i);
  17674. var position = circleVector.scale(radius).add(offset);
  17675. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  17676. positions.push(position.x, position.y, position.z);
  17677. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17678. }
  17679. for (var i = 0; i < tessellation - 2; i++) {
  17680. if (!isTop) {
  17681. indices.push(vbase);
  17682. indices.push(vbase + (i + 2) % tessellation);
  17683. indices.push(vbase + (i + 1) % tessellation);
  17684. } else {
  17685. indices.push(vbase);
  17686. indices.push(vbase + (i + 1) % tessellation);
  17687. indices.push(vbase + (i + 2) % tessellation);
  17688. }
  17689. }
  17690. };
  17691. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  17692. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  17693. var stride = tessellation + 1;
  17694. for (var i = 0; i <= tessellation; i++) {
  17695. var circleVector = getCircleVector(i);
  17696. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  17697. var position, radius = radiusBottom;
  17698. for (var s = 0; s <= subdivisions; s++) {
  17699. position = circleVector.scale(radius);
  17700. position.addInPlace(base.add(offset.scale(s)));
  17701. textureCoordinate.y += 1 / subdivisions;
  17702. radius += (radiusTop - radiusBottom) / subdivisions;
  17703. positions.push(position.x, position.y, position.z);
  17704. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17705. }
  17706. }
  17707. subdivisions += 1;
  17708. for (var s = 0; s < subdivisions - 1; s++) {
  17709. for (var i = 0; i <= tessellation; i++) {
  17710. indices.push(i * subdivisions + s);
  17711. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  17712. indices.push(i * subdivisions + (s + 1));
  17713. indices.push(i * subdivisions + (s + 1));
  17714. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  17715. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  17716. }
  17717. }
  17718. createCylinderCap(true);
  17719. createCylinderCap(false);
  17720. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17721. var vertexData = new BABYLON.VertexData();
  17722. vertexData.indices = indices;
  17723. vertexData.positions = positions;
  17724. vertexData.normals = normals;
  17725. vertexData.uvs = uvs;
  17726. return vertexData;
  17727. };
  17728. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  17729. var indices = [];
  17730. var positions = [];
  17731. var normals = [];
  17732. var uvs = [];
  17733. diameter = diameter || 1;
  17734. thickness = thickness || 0.5;
  17735. tessellation = tessellation || 16;
  17736. var stride = tessellation + 1;
  17737. for (var i = 0; i <= tessellation; i++) {
  17738. var u = i / tessellation;
  17739. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  17740. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  17741. for (var j = 0; j <= tessellation; j++) {
  17742. var v = 1 - j / tessellation;
  17743. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  17744. var dx = Math.cos(innerAngle);
  17745. var dy = Math.sin(innerAngle);
  17746. var normal = new BABYLON.Vector3(dx, dy, 0);
  17747. var position = normal.scale(thickness / 2);
  17748. var textureCoordinate = new BABYLON.Vector2(u, v);
  17749. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  17750. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  17751. positions.push(position.x, position.y, position.z);
  17752. normals.push(normal.x, normal.y, normal.z);
  17753. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17754. var nextI = (i + 1) % stride;
  17755. var nextJ = (j + 1) % stride;
  17756. indices.push(i * stride + j);
  17757. indices.push(i * stride + nextJ);
  17758. indices.push(nextI * stride + j);
  17759. indices.push(i * stride + nextJ);
  17760. indices.push(nextI * stride + nextJ);
  17761. indices.push(nextI * stride + j);
  17762. }
  17763. }
  17764. var vertexData = new BABYLON.VertexData();
  17765. vertexData.indices = indices;
  17766. vertexData.positions = positions;
  17767. vertexData.normals = normals;
  17768. vertexData.uvs = uvs;
  17769. return vertexData;
  17770. };
  17771. VertexData.CreateLines = function (points) {
  17772. var indices = [];
  17773. var positions = [];
  17774. for (var index = 0; index < points.length; index++) {
  17775. positions.push(points[index].x, points[index].y, points[index].z);
  17776. if (index > 0) {
  17777. indices.push(index - 1);
  17778. indices.push(index);
  17779. }
  17780. }
  17781. var vertexData = new BABYLON.VertexData();
  17782. vertexData.indices = indices;
  17783. vertexData.positions = positions;
  17784. return vertexData;
  17785. };
  17786. VertexData.CreateGround = function (width, height, subdivisions) {
  17787. var indices = [];
  17788. var positions = [];
  17789. var normals = [];
  17790. var uvs = [];
  17791. var row, col;
  17792. width = width || 1;
  17793. height = height || 1;
  17794. subdivisions = subdivisions || 1;
  17795. for (row = 0; row <= subdivisions; row++) {
  17796. for (col = 0; col <= subdivisions; col++) {
  17797. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  17798. var normal = new BABYLON.Vector3(0, 1.0, 0);
  17799. positions.push(position.x, position.y, position.z);
  17800. normals.push(normal.x, normal.y, normal.z);
  17801. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  17802. }
  17803. }
  17804. for (row = 0; row < subdivisions; row++) {
  17805. for (col = 0; col < subdivisions; col++) {
  17806. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17807. indices.push(col + 1 + row * (subdivisions + 1));
  17808. indices.push(col + row * (subdivisions + 1));
  17809. indices.push(col + (row + 1) * (subdivisions + 1));
  17810. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17811. indices.push(col + row * (subdivisions + 1));
  17812. }
  17813. }
  17814. var vertexData = new BABYLON.VertexData();
  17815. vertexData.indices = indices;
  17816. vertexData.positions = positions;
  17817. vertexData.normals = normals;
  17818. vertexData.uvs = uvs;
  17819. return vertexData;
  17820. };
  17821. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  17822. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  17823. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  17824. var indices = [];
  17825. var positions = [];
  17826. var normals = [];
  17827. var uvs = [];
  17828. var row, col, tileRow, tileCol;
  17829. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  17830. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  17831. precision.w = (precision.w < 1) ? 1 : precision.w;
  17832. precision.h = (precision.h < 1) ? 1 : precision.h;
  17833. var tileSize = {
  17834. 'w': (xmax - xmin) / subdivisions.w,
  17835. 'h': (zmax - zmin) / subdivisions.h
  17836. };
  17837. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  17838. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  17839. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  17840. }
  17841. }
  17842. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  17843. var base = positions.length / 3;
  17844. var rowLength = precision.w + 1;
  17845. for (row = 0; row < precision.h; row++) {
  17846. for (col = 0; col < precision.w; col++) {
  17847. var square = [
  17848. base + col + row * rowLength,
  17849. base + (col + 1) + row * rowLength,
  17850. base + (col + 1) + (row + 1) * rowLength,
  17851. base + col + (row + 1) * rowLength
  17852. ];
  17853. indices.push(square[1]);
  17854. indices.push(square[2]);
  17855. indices.push(square[3]);
  17856. indices.push(square[0]);
  17857. indices.push(square[1]);
  17858. indices.push(square[3]);
  17859. }
  17860. }
  17861. var position = BABYLON.Vector3.Zero();
  17862. var normal = new BABYLON.Vector3(0, 1.0, 0);
  17863. for (row = 0; row <= precision.h; row++) {
  17864. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  17865. for (col = 0; col <= precision.w; col++) {
  17866. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  17867. position.y = 0;
  17868. positions.push(position.x, position.y, position.z);
  17869. normals.push(normal.x, normal.y, normal.z);
  17870. uvs.push(col / precision.w, row / precision.h);
  17871. }
  17872. }
  17873. }
  17874. var vertexData = new BABYLON.VertexData();
  17875. vertexData.indices = indices;
  17876. vertexData.positions = positions;
  17877. vertexData.normals = normals;
  17878. vertexData.uvs = uvs;
  17879. return vertexData;
  17880. };
  17881. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  17882. var indices = [];
  17883. var positions = [];
  17884. var normals = [];
  17885. var uvs = [];
  17886. var row, col;
  17887. for (row = 0; row <= subdivisions; row++) {
  17888. for (col = 0; col <= subdivisions; col++) {
  17889. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  17890. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  17891. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  17892. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  17893. var r = buffer[pos] / 255.0;
  17894. var g = buffer[pos + 1] / 255.0;
  17895. var b = buffer[pos + 2] / 255.0;
  17896. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  17897. position.y = minHeight + (maxHeight - minHeight) * gradient;
  17898. positions.push(position.x, position.y, position.z);
  17899. normals.push(0, 0, 0);
  17900. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  17901. }
  17902. }
  17903. for (row = 0; row < subdivisions; row++) {
  17904. for (col = 0; col < subdivisions; col++) {
  17905. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17906. indices.push(col + 1 + row * (subdivisions + 1));
  17907. indices.push(col + row * (subdivisions + 1));
  17908. indices.push(col + (row + 1) * (subdivisions + 1));
  17909. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17910. indices.push(col + row * (subdivisions + 1));
  17911. }
  17912. }
  17913. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17914. var vertexData = new BABYLON.VertexData();
  17915. vertexData.indices = indices;
  17916. vertexData.positions = positions;
  17917. vertexData.normals = normals;
  17918. vertexData.uvs = uvs;
  17919. return vertexData;
  17920. };
  17921. VertexData.CreatePlane = function (size) {
  17922. var indices = [];
  17923. var positions = [];
  17924. var normals = [];
  17925. var uvs = [];
  17926. size = size || 1;
  17927. var halfSize = size / 2.0;
  17928. positions.push(-halfSize, -halfSize, 0);
  17929. normals.push(0, 0, -1.0);
  17930. uvs.push(0.0, 0.0);
  17931. positions.push(halfSize, -halfSize, 0);
  17932. normals.push(0, 0, -1.0);
  17933. uvs.push(1.0, 0.0);
  17934. positions.push(halfSize, halfSize, 0);
  17935. normals.push(0, 0, -1.0);
  17936. uvs.push(1.0, 1.0);
  17937. positions.push(-halfSize, halfSize, 0);
  17938. normals.push(0, 0, -1.0);
  17939. uvs.push(0.0, 1.0);
  17940. indices.push(0);
  17941. indices.push(1);
  17942. indices.push(2);
  17943. indices.push(0);
  17944. indices.push(2);
  17945. indices.push(3);
  17946. var vertexData = new BABYLON.VertexData();
  17947. vertexData.indices = indices;
  17948. vertexData.positions = positions;
  17949. vertexData.normals = normals;
  17950. vertexData.uvs = uvs;
  17951. return vertexData;
  17952. };
  17953. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  17954. var indices = [];
  17955. var positions = [];
  17956. var normals = [];
  17957. var uvs = [];
  17958. radius = radius || 2;
  17959. tube = tube || 0.5;
  17960. radialSegments = radialSegments || 32;
  17961. tubularSegments = tubularSegments || 32;
  17962. p = p || 2;
  17963. q = q || 3;
  17964. var getPos = function (angle) {
  17965. var cu = Math.cos(angle);
  17966. var su = Math.sin(angle);
  17967. var quOverP = q / p * angle;
  17968. var cs = Math.cos(quOverP);
  17969. var tx = radius * (2 + cs) * 0.5 * cu;
  17970. var ty = radius * (2 + cs) * su * 0.5;
  17971. var tz = radius * Math.sin(quOverP) * 0.5;
  17972. return new BABYLON.Vector3(tx, ty, tz);
  17973. };
  17974. for (var i = 0; i <= radialSegments; i++) {
  17975. var modI = i % radialSegments;
  17976. var u = modI / radialSegments * 2 * p * Math.PI;
  17977. var p1 = getPos(u);
  17978. var p2 = getPos(u + 0.01);
  17979. var tang = p2.subtract(p1);
  17980. var n = p2.add(p1);
  17981. var bitan = BABYLON.Vector3.Cross(tang, n);
  17982. n = BABYLON.Vector3.Cross(bitan, tang);
  17983. bitan.normalize();
  17984. n.normalize();
  17985. for (var j = 0; j < tubularSegments; j++) {
  17986. var modJ = j % tubularSegments;
  17987. var v = modJ / tubularSegments * 2 * Math.PI;
  17988. var cx = -tube * Math.cos(v);
  17989. var cy = tube * Math.sin(v);
  17990. positions.push(p1.x + cx * n.x + cy * bitan.x);
  17991. positions.push(p1.y + cx * n.y + cy * bitan.y);
  17992. positions.push(p1.z + cx * n.z + cy * bitan.z);
  17993. uvs.push(i / radialSegments);
  17994. uvs.push(j / tubularSegments);
  17995. }
  17996. }
  17997. for (i = 0; i < radialSegments; i++) {
  17998. for (j = 0; j < tubularSegments; j++) {
  17999. var jNext = (j + 1) % tubularSegments;
  18000. var a = i * tubularSegments + j;
  18001. var b = (i + 1) * tubularSegments + j;
  18002. var c = (i + 1) * tubularSegments + jNext;
  18003. var d = i * tubularSegments + jNext;
  18004. indices.push(d);
  18005. indices.push(b);
  18006. indices.push(a);
  18007. indices.push(d);
  18008. indices.push(c);
  18009. indices.push(b);
  18010. }
  18011. }
  18012. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18013. var vertexData = new BABYLON.VertexData();
  18014. vertexData.indices = indices;
  18015. vertexData.positions = positions;
  18016. vertexData.normals = normals;
  18017. vertexData.uvs = uvs;
  18018. return vertexData;
  18019. };
  18020. VertexData.ComputeNormals = function (positions, indices, normals) {
  18021. var positionVectors = [];
  18022. var facesOfVertices = [];
  18023. var index;
  18024. for (index = 0; index < positions.length; index += 3) {
  18025. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  18026. positionVectors.push(vector3);
  18027. facesOfVertices.push([]);
  18028. }
  18029. var facesNormals = [];
  18030. for (index = 0; index < indices.length / 3; index++) {
  18031. var i1 = indices[index * 3];
  18032. var i2 = indices[index * 3 + 1];
  18033. var i3 = indices[index * 3 + 2];
  18034. var p1 = positionVectors[i1];
  18035. var p2 = positionVectors[i2];
  18036. var p3 = positionVectors[i3];
  18037. var p1p2 = p1.subtract(p2);
  18038. var p3p2 = p3.subtract(p2);
  18039. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  18040. facesOfVertices[i1].push(index);
  18041. facesOfVertices[i2].push(index);
  18042. facesOfVertices[i3].push(index);
  18043. }
  18044. for (index = 0; index < positionVectors.length; index++) {
  18045. var faces = facesOfVertices[index];
  18046. var normal = BABYLON.Vector3.Zero();
  18047. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  18048. normal.addInPlace(facesNormals[faces[faceIndex]]);
  18049. }
  18050. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  18051. normals[index * 3] = normal.x;
  18052. normals[index * 3 + 1] = normal.y;
  18053. normals[index * 3 + 2] = normal.z;
  18054. }
  18055. };
  18056. return VertexData;
  18057. })();
  18058. BABYLON.VertexData = VertexData;
  18059. })(BABYLON || (BABYLON = {}));
  18060. var __extends = this.__extends || function (d, b) {
  18061. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18062. function __() { this.constructor = d; }
  18063. __.prototype = b.prototype;
  18064. d.prototype = new __();
  18065. };
  18066. var BABYLON;
  18067. (function (BABYLON) {
  18068. var buildCamera = function (that, name) {
  18069. that._leftCamera.isIntermediate = true;
  18070. that.subCameras.push(that._leftCamera);
  18071. that.subCameras.push(that._rightCamera);
  18072. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  18073. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  18074. that._anaglyphPostProcess.onApply = function (effect) {
  18075. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  18076. };
  18077. that._update();
  18078. };
  18079. var AnaglyphArcRotateCamera = (function (_super) {
  18080. __extends(AnaglyphArcRotateCamera, _super);
  18081. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  18082. _super.call(this, name, alpha, beta, radius, target, scene);
  18083. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  18084. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  18085. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  18086. buildCamera(this, name);
  18087. }
  18088. AnaglyphArcRotateCamera.prototype._update = function () {
  18089. this._updateCamera(this._leftCamera);
  18090. this._updateCamera(this._rightCamera);
  18091. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  18092. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  18093. _super.prototype._update.call(this);
  18094. };
  18095. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  18096. camera.beta = this.beta;
  18097. camera.radius = this.radius;
  18098. camera.minZ = this.minZ;
  18099. camera.maxZ = this.maxZ;
  18100. camera.fov = this.fov;
  18101. camera.target = this.target;
  18102. };
  18103. return AnaglyphArcRotateCamera;
  18104. })(BABYLON.ArcRotateCamera);
  18105. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  18106. var AnaglyphFreeCamera = (function (_super) {
  18107. __extends(AnaglyphFreeCamera, _super);
  18108. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  18109. _super.call(this, name, position, scene);
  18110. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  18111. this._transformMatrix = new BABYLON.Matrix();
  18112. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  18113. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  18114. buildCamera(this, name);
  18115. }
  18116. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  18117. var target = this.getTarget();
  18118. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  18119. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  18120. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  18121. };
  18122. AnaglyphFreeCamera.prototype._update = function () {
  18123. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  18124. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  18125. this._updateCamera(this._leftCamera);
  18126. this._updateCamera(this._rightCamera);
  18127. _super.prototype._update.call(this);
  18128. };
  18129. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  18130. camera.minZ = this.minZ;
  18131. camera.maxZ = this.maxZ;
  18132. camera.fov = this.fov;
  18133. camera.viewport = this.viewport;
  18134. camera.setTarget(this.getTarget());
  18135. };
  18136. return AnaglyphFreeCamera;
  18137. })(BABYLON.FreeCamera);
  18138. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  18139. })(BABYLON || (BABYLON = {}));
  18140. var __extends = this.__extends || function (d, b) {
  18141. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18142. function __() { this.constructor = d; }
  18143. __.prototype = b.prototype;
  18144. d.prototype = new __();
  18145. };
  18146. var BABYLON;
  18147. (function (BABYLON) {
  18148. var AnaglyphPostProcess = (function (_super) {
  18149. __extends(AnaglyphPostProcess, _super);
  18150. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18151. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  18152. }
  18153. return AnaglyphPostProcess;
  18154. })(BABYLON.PostProcess);
  18155. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  18156. })(BABYLON || (BABYLON = {}));
  18157. var BABYLON;
  18158. (function (BABYLON) {
  18159. var Tags = (function () {
  18160. function Tags() {
  18161. }
  18162. Tags.EnableFor = function (obj) {
  18163. obj._tags = obj._tags || {};
  18164. obj.hasTags = function () {
  18165. return Tags.HasTags(obj);
  18166. };
  18167. obj.addTags = function (tagsString) {
  18168. return Tags.AddTagsTo(obj, tagsString);
  18169. };
  18170. obj.removeTags = function (tagsString) {
  18171. return Tags.RemoveTagsFrom(obj, tagsString);
  18172. };
  18173. obj.matchesTagsQuery = function (tagsQuery) {
  18174. return Tags.MatchesQuery(obj, tagsQuery);
  18175. };
  18176. };
  18177. Tags.DisableFor = function (obj) {
  18178. delete obj._tags;
  18179. delete obj.hasTags;
  18180. delete obj.addTags;
  18181. delete obj.removeTags;
  18182. delete obj.matchesTagsQuery;
  18183. };
  18184. Tags.HasTags = function (obj) {
  18185. if (!obj._tags) {
  18186. return false;
  18187. }
  18188. return !BABYLON.Tools.IsEmpty(obj._tags);
  18189. };
  18190. Tags.GetTags = function (obj) {
  18191. if (!obj._tags) {
  18192. return null;
  18193. }
  18194. return obj._tags;
  18195. };
  18196. Tags.AddTagsTo = function (obj, tagsString) {
  18197. if (!tagsString) {
  18198. return;
  18199. }
  18200. var tags = tagsString.split(" ");
  18201. for (var t in tags) {
  18202. Tags._AddTagTo(obj, tags[t]);
  18203. }
  18204. };
  18205. Tags._AddTagTo = function (obj, tag) {
  18206. tag = tag.trim();
  18207. if (tag === "" || tag === "true" || tag === "false") {
  18208. return;
  18209. }
  18210. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  18211. return;
  18212. }
  18213. Tags.EnableFor(obj);
  18214. obj._tags[tag] = true;
  18215. };
  18216. Tags.RemoveTagsFrom = function (obj, tagsString) {
  18217. if (!Tags.HasTags(obj)) {
  18218. return;
  18219. }
  18220. var tags = tagsString.split(" ");
  18221. for (var t in tags) {
  18222. Tags._RemoveTagFrom(obj, tags[t]);
  18223. }
  18224. };
  18225. Tags._RemoveTagFrom = function (obj, tag) {
  18226. delete obj._tags[tag];
  18227. };
  18228. Tags.MatchesQuery = function (obj, tagsQuery) {
  18229. if (tagsQuery === undefined) {
  18230. return true;
  18231. }
  18232. if (tagsQuery === "") {
  18233. return Tags.HasTags(obj);
  18234. }
  18235. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  18236. return Tags.HasTags(obj) && obj._tags[r];
  18237. });
  18238. };
  18239. return Tags;
  18240. })();
  18241. BABYLON.Tags = Tags;
  18242. })(BABYLON || (BABYLON = {}));
  18243. var BABYLON;
  18244. (function (BABYLON) {
  18245. (function (Internals) {
  18246. var AndOrNotEvaluator = (function () {
  18247. function AndOrNotEvaluator() {
  18248. }
  18249. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  18250. if (!query.match(/\([^\(\)]*\)/g)) {
  18251. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  18252. } else {
  18253. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  18254. r = r.slice(1, r.length - 1);
  18255. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  18256. });
  18257. }
  18258. if (query === "true") {
  18259. return true;
  18260. }
  18261. if (query === "false") {
  18262. return false;
  18263. }
  18264. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  18265. };
  18266. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  18267. evaluateCallback = evaluateCallback || (function (r) {
  18268. return r === "true" ? true : false;
  18269. });
  18270. var result;
  18271. var or = parenthesisContent.split("||");
  18272. for (var i in or) {
  18273. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  18274. var and = ori.split("&&");
  18275. if (and.length > 1) {
  18276. for (var j = 0; j < and.length; ++j) {
  18277. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  18278. if (andj !== "true" && andj !== "false") {
  18279. if (andj[0] === "!") {
  18280. result = !evaluateCallback(andj.substring(1));
  18281. } else {
  18282. result = evaluateCallback(andj);
  18283. }
  18284. } else {
  18285. result = andj === "true" ? true : false;
  18286. }
  18287. if (!result) {
  18288. ori = "false";
  18289. break;
  18290. }
  18291. }
  18292. }
  18293. if (result || ori === "true") {
  18294. result = true;
  18295. break;
  18296. }
  18297. if (ori !== "true" && ori !== "false") {
  18298. if (ori[0] === "!") {
  18299. result = !evaluateCallback(ori.substring(1));
  18300. } else {
  18301. result = evaluateCallback(ori);
  18302. }
  18303. } else {
  18304. result = ori === "true" ? true : false;
  18305. }
  18306. }
  18307. return result ? "true" : "false";
  18308. };
  18309. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  18310. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  18311. r = r.replace(/[\s]/g, function () {
  18312. return "";
  18313. });
  18314. return r.length % 2 ? "!" : "";
  18315. });
  18316. booleanString = booleanString.trim();
  18317. if (booleanString === "!true") {
  18318. booleanString = "false";
  18319. } else if (booleanString === "!false") {
  18320. booleanString = "true";
  18321. }
  18322. return booleanString;
  18323. };
  18324. return AndOrNotEvaluator;
  18325. })();
  18326. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  18327. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18328. var Internals = BABYLON.Internals;
  18329. })(BABYLON || (BABYLON = {}));
  18330. var BABYLON;
  18331. (function (BABYLON) {
  18332. var PostProcessRenderPass = (function () {
  18333. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  18334. this._enabled = true;
  18335. this._refCount = 0;
  18336. this._name = name;
  18337. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  18338. this.setRenderList(renderList);
  18339. this._renderTexture.onBeforeRender = beforeRender;
  18340. this._renderTexture.onAfterRender = afterRender;
  18341. this._scene = scene;
  18342. }
  18343. PostProcessRenderPass.prototype._incRefCount = function () {
  18344. if (this._refCount === 0) {
  18345. this._scene.customRenderTargets.push(this._renderTexture);
  18346. }
  18347. return ++this._refCount;
  18348. };
  18349. PostProcessRenderPass.prototype._decRefCount = function () {
  18350. this._refCount--;
  18351. if (this._refCount <= 0) {
  18352. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  18353. }
  18354. return this._refCount;
  18355. };
  18356. PostProcessRenderPass.prototype._update = function () {
  18357. this.setRenderList(this._renderList);
  18358. };
  18359. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  18360. this._renderTexture.renderList = renderList;
  18361. };
  18362. PostProcessRenderPass.prototype.getRenderTexture = function () {
  18363. return this._renderTexture;
  18364. };
  18365. return PostProcessRenderPass;
  18366. })();
  18367. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  18368. })(BABYLON || (BABYLON = {}));
  18369. var BABYLON;
  18370. (function (BABYLON) {
  18371. var PostProcessRenderEffect = (function () {
  18372. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  18373. this._engine = engine;
  18374. this._name = name;
  18375. this._singleInstance = singleInstance || true;
  18376. this._getPostProcess = getPostProcess;
  18377. this._cameras = [];
  18378. this._postProcesses = [];
  18379. this._indicesForCamera = [];
  18380. this._renderPasses = [];
  18381. this._renderEffectAsPasses = [];
  18382. }
  18383. PostProcessRenderEffect.prototype._update = function () {
  18384. for (var renderPassName in this._renderPasses) {
  18385. this._renderPasses[renderPassName]._update();
  18386. }
  18387. };
  18388. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  18389. this._renderPasses[renderPass._name] = renderPass;
  18390. this._linkParameters();
  18391. };
  18392. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  18393. delete this._renderPasses[renderPass._name];
  18394. this._linkParameters();
  18395. };
  18396. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  18397. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  18398. this._linkParameters();
  18399. };
  18400. PostProcessRenderEffect.prototype.getPass = function (passName) {
  18401. for (var renderPassName in this._renderPasses) {
  18402. if (renderPassName === passName) {
  18403. return this._renderPasses[passName];
  18404. }
  18405. }
  18406. };
  18407. PostProcessRenderEffect.prototype.emptyPasses = function () {
  18408. this._renderPasses.length = 0;
  18409. this._linkParameters();
  18410. };
  18411. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  18412. var cameraKey;
  18413. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18414. for (var i = 0; i < _cam.length; i++) {
  18415. var camera = _cam[i];
  18416. var cameraName = camera.name;
  18417. if (this._singleInstance) {
  18418. cameraKey = 0;
  18419. } else {
  18420. cameraKey = cameraName;
  18421. }
  18422. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  18423. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  18424. if (!this._indicesForCamera[cameraName]) {
  18425. this._indicesForCamera[cameraName] = [];
  18426. }
  18427. this._indicesForCamera[cameraName].push(index);
  18428. if (this._cameras.indexOf(camera) === -1) {
  18429. this._cameras[cameraName] = camera;
  18430. }
  18431. for (var passName in this._renderPasses) {
  18432. this._renderPasses[passName]._incRefCount();
  18433. }
  18434. }
  18435. this._linkParameters();
  18436. };
  18437. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  18438. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18439. for (var i = 0; i < _cam.length; i++) {
  18440. var camera = _cam[i];
  18441. var cameraName = camera.name;
  18442. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  18443. var index = this._cameras.indexOf(cameraName);
  18444. this._indicesForCamera.splice(index, 1);
  18445. this._cameras.splice(index, 1);
  18446. for (var passName in this._renderPasses) {
  18447. this._renderPasses[passName]._decRefCount();
  18448. }
  18449. }
  18450. };
  18451. PostProcessRenderEffect.prototype._enable = function (cameras) {
  18452. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18453. for (var i = 0; i < _cam.length; i++) {
  18454. var camera = _cam[i];
  18455. var cameraName = camera.name;
  18456. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  18457. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  18458. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  18459. }
  18460. }
  18461. for (var passName in this._renderPasses) {
  18462. this._renderPasses[passName]._incRefCount();
  18463. }
  18464. }
  18465. };
  18466. PostProcessRenderEffect.prototype._disable = function (cameras) {
  18467. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18468. for (var i = 0; i < _cam.length; i++) {
  18469. var camera = _cam[i];
  18470. var cameraName = camera.Name;
  18471. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  18472. for (var passName in this._renderPasses) {
  18473. this._renderPasses[passName]._decRefCount();
  18474. }
  18475. }
  18476. };
  18477. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  18478. if (this._singleInstance) {
  18479. return this._postProcesses[0];
  18480. } else {
  18481. return this._postProcesses[camera.name];
  18482. }
  18483. };
  18484. PostProcessRenderEffect.prototype._linkParameters = function () {
  18485. var _this = this;
  18486. for (var index in this._postProcesses) {
  18487. if (this.applyParameters) {
  18488. this.applyParameters(this._postProcesses[index]);
  18489. }
  18490. this._postProcesses[index].onBeforeRender = function (effect) {
  18491. _this._linkTextures(effect);
  18492. };
  18493. }
  18494. };
  18495. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  18496. for (var renderPassName in this._renderPasses) {
  18497. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  18498. }
  18499. for (var renderEffectName in this._renderEffectAsPasses) {
  18500. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  18501. }
  18502. };
  18503. return PostProcessRenderEffect;
  18504. })();
  18505. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  18506. })(BABYLON || (BABYLON = {}));
  18507. var BABYLON;
  18508. (function (BABYLON) {
  18509. var PostProcessRenderPipeline = (function () {
  18510. function PostProcessRenderPipeline(engine, name) {
  18511. this._engine = engine;
  18512. this._name = name;
  18513. this._renderEffects = [];
  18514. this._renderEffectsForIsolatedPass = [];
  18515. this._cameras = [];
  18516. }
  18517. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  18518. this._renderEffects[renderEffect._name] = renderEffect;
  18519. };
  18520. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  18521. var renderEffects = this._renderEffects[renderEffectName];
  18522. if (!renderEffects) {
  18523. return;
  18524. }
  18525. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  18526. };
  18527. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  18528. var renderEffects = this._renderEffects[renderEffectName];
  18529. if (!renderEffects) {
  18530. return;
  18531. }
  18532. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  18533. };
  18534. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  18535. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18536. var indicesToDelete = [];
  18537. for (var i = 0; i < _cam.length; i++) {
  18538. var camera = _cam[i];
  18539. var cameraName = camera.name;
  18540. if (this._cameras.indexOf(camera) === -1) {
  18541. this._cameras[cameraName] = camera;
  18542. } else if (unique) {
  18543. indicesToDelete.push(i);
  18544. }
  18545. }
  18546. for (var i = 0; i < indicesToDelete.length; i++) {
  18547. cameras.splice(indicesToDelete[i], 1);
  18548. }
  18549. for (var renderEffectName in this._renderEffects) {
  18550. this._renderEffects[renderEffectName]._attachCameras(_cam);
  18551. }
  18552. };
  18553. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  18554. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18555. for (var renderEffectName in this._renderEffects) {
  18556. this._renderEffects[renderEffectName]._detachCameras(_cam);
  18557. }
  18558. for (var i = 0; i < _cam.length; i++) {
  18559. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  18560. }
  18561. };
  18562. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  18563. var _this = this;
  18564. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18565. var pass = null;
  18566. for (var renderEffectName in this._renderEffects) {
  18567. pass = this._renderEffects[renderEffectName].getPass(passName);
  18568. if (pass != null) {
  18569. break;
  18570. }
  18571. }
  18572. if (pass === null) {
  18573. return;
  18574. }
  18575. for (var renderEffectName in this._renderEffects) {
  18576. this._renderEffects[renderEffectName]._disable(_cam);
  18577. }
  18578. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  18579. for (var i = 0; i < _cam.length; i++) {
  18580. var camera = _cam[i];
  18581. var cameraName = camera.name;
  18582. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  18583. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  18584. });
  18585. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  18586. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  18587. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  18588. }
  18589. };
  18590. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  18591. var _this = this;
  18592. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18593. for (var i = 0; i < _cam.length; i++) {
  18594. var camera = _cam[i];
  18595. var cameraName = camera.name;
  18596. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  18597. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  18598. });
  18599. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  18600. }
  18601. for (var renderEffectName in this._renderEffects) {
  18602. this._renderEffects[renderEffectName]._enable(_cam);
  18603. }
  18604. };
  18605. PostProcessRenderPipeline.prototype._update = function () {
  18606. for (var renderEffectName in this._renderEffects) {
  18607. this._renderEffects[renderEffectName]._update();
  18608. }
  18609. for (var i = 0; i < this._cameras.length; i++) {
  18610. var cameraName = this._cameras[i].name;
  18611. if (this._renderEffectsForIsolatedPass[cameraName]) {
  18612. this._renderEffectsForIsolatedPass[cameraName]._update();
  18613. }
  18614. }
  18615. };
  18616. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  18617. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  18618. return PostProcessRenderPipeline;
  18619. })();
  18620. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  18621. })(BABYLON || (BABYLON = {}));
  18622. var BABYLON;
  18623. (function (BABYLON) {
  18624. var PostProcessRenderPipelineManager = (function () {
  18625. function PostProcessRenderPipelineManager() {
  18626. this._renderPipelines = new Array();
  18627. }
  18628. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  18629. this._renderPipelines[renderPipeline._name] = renderPipeline;
  18630. };
  18631. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  18632. var renderPipeline = this._renderPipelines[renderPipelineName];
  18633. if (!renderPipeline) {
  18634. return;
  18635. }
  18636. renderPipeline._attachCameras(cameras, unique);
  18637. };
  18638. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  18639. var renderPipeline = this._renderPipelines[renderPipelineName];
  18640. if (!renderPipeline) {
  18641. return;
  18642. }
  18643. renderPipeline._detachCameras(cameras);
  18644. };
  18645. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  18646. var renderPipeline = this._renderPipelines[renderPipelineName];
  18647. if (!renderPipeline) {
  18648. return;
  18649. }
  18650. renderPipeline._enableEffect(renderEffectName, cameras);
  18651. };
  18652. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  18653. var renderPipeline = this._renderPipelines[renderPipelineName];
  18654. if (!renderPipeline) {
  18655. return;
  18656. }
  18657. renderPipeline._disableEffect(renderEffectName, cameras);
  18658. };
  18659. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  18660. var renderPipeline = this._renderPipelines[renderPipelineName];
  18661. if (!renderPipeline) {
  18662. return;
  18663. }
  18664. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  18665. };
  18666. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  18667. var renderPipeline = this._renderPipelines[renderPipelineName];
  18668. if (!renderPipeline) {
  18669. return;
  18670. }
  18671. renderPipeline._disableDisplayOnlyPass(cameras);
  18672. };
  18673. PostProcessRenderPipelineManager.prototype.update = function () {
  18674. for (var renderPipelineName in this._renderPipelines) {
  18675. this._renderPipelines[renderPipelineName]._update();
  18676. }
  18677. };
  18678. return PostProcessRenderPipelineManager;
  18679. })();
  18680. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  18681. })(BABYLON || (BABYLON = {}));
  18682. var __extends = this.__extends || function (d, b) {
  18683. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18684. function __() { this.constructor = d; }
  18685. __.prototype = b.prototype;
  18686. d.prototype = new __();
  18687. };
  18688. var BABYLON;
  18689. (function (BABYLON) {
  18690. var DisplayPassPostProcess = (function (_super) {
  18691. __extends(DisplayPassPostProcess, _super);
  18692. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18693. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  18694. }
  18695. return DisplayPassPostProcess;
  18696. })(BABYLON.PostProcess);
  18697. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  18698. })(BABYLON || (BABYLON = {}));
  18699. var BABYLON;
  18700. (function (BABYLON) {
  18701. var BoundingBoxRenderer = (function () {
  18702. function BoundingBoxRenderer(scene) {
  18703. this.frontColor = new BABYLON.Color3(1, 1, 1);
  18704. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  18705. this.showBackLines = true;
  18706. this.renderList = new BABYLON.SmartArray(32);
  18707. this._scene = scene;
  18708. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  18709. attributes: ["position"],
  18710. uniforms: ["worldViewProjection", "color"]
  18711. });
  18712. var engine = this._scene.getEngine();
  18713. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  18714. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  18715. 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]);
  18716. }
  18717. BoundingBoxRenderer.prototype.reset = function () {
  18718. this.renderList.reset();
  18719. };
  18720. BoundingBoxRenderer.prototype.render = function () {
  18721. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  18722. return;
  18723. }
  18724. var engine = this._scene.getEngine();
  18725. engine.setDepthWrite(false);
  18726. this._colorShader._preBind();
  18727. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  18728. var boundingBox = this.renderList.data[boundingBoxIndex];
  18729. var min = boundingBox.minimum;
  18730. var max = boundingBox.maximum;
  18731. var diff = max.subtract(min);
  18732. var median = min.add(diff.scale(0.5));
  18733. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  18734. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  18735. if (this.showBackLines) {
  18736. engine.setDepthFunctionToGreaterOrEqual();
  18737. this._colorShader.setColor4("color", this.backColor.toColor4());
  18738. this._colorShader.bind(worldMatrix);
  18739. engine.draw(false, 0, 24);
  18740. }
  18741. engine.setDepthFunctionToLess();
  18742. this._colorShader.setColor4("color", this.frontColor.toColor4());
  18743. this._colorShader.bind(worldMatrix);
  18744. engine.draw(false, 0, 24);
  18745. }
  18746. this._colorShader.unbind();
  18747. engine.setDepthFunctionToLessOrEqual();
  18748. engine.setDepthWrite(true);
  18749. };
  18750. BoundingBoxRenderer.prototype.dispose = function () {
  18751. this._colorShader.dispose();
  18752. this._vb.dispose();
  18753. this._scene.getEngine()._releaseBuffer(this._ib);
  18754. };
  18755. return BoundingBoxRenderer;
  18756. })();
  18757. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  18758. })(BABYLON || (BABYLON = {}));
  18759. /**
  18760. * Based on jsTGALoader - Javascript loader for TGA file
  18761. * By Vincent Thibault
  18762. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  18763. */
  18764. var BABYLON;
  18765. (function (BABYLON) {
  18766. (function (Internals) {
  18767. var TGATools = (function () {
  18768. function TGATools() {
  18769. }
  18770. TGATools.GetTGAHeader = function (data) {
  18771. var offset = 0;
  18772. var header = {
  18773. id_length: data[offset++],
  18774. colormap_type: data[offset++],
  18775. image_type: data[offset++],
  18776. colormap_index: data[offset++] | data[offset++] << 8,
  18777. colormap_length: data[offset++] | data[offset++] << 8,
  18778. colormap_size: data[offset++],
  18779. origin: [
  18780. data[offset++] | data[offset++] << 8,
  18781. data[offset++] | data[offset++] << 8
  18782. ],
  18783. width: data[offset++] | data[offset++] << 8,
  18784. height: data[offset++] | data[offset++] << 8,
  18785. pixel_size: data[offset++],
  18786. flags: data[offset++]
  18787. };
  18788. return header;
  18789. };
  18790. TGATools.UploadContent = function (gl, data) {
  18791. if (data.length < 19) {
  18792. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  18793. return;
  18794. }
  18795. var offset = 18;
  18796. var header = TGATools.GetTGAHeader(data);
  18797. if (header.id_length + offset > data.length) {
  18798. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  18799. return;
  18800. }
  18801. offset += header.id_length;
  18802. var use_rle = false;
  18803. var use_pal = false;
  18804. var use_rgb = false;
  18805. var use_grey = false;
  18806. switch (header.image_type) {
  18807. case TGATools._TYPE_RLE_INDEXED:
  18808. use_rle = true;
  18809. case TGATools._TYPE_INDEXED:
  18810. use_pal = true;
  18811. break;
  18812. case TGATools._TYPE_RLE_RGB:
  18813. use_rle = true;
  18814. case TGATools._TYPE_RGB:
  18815. use_rgb = true;
  18816. break;
  18817. case TGATools._TYPE_RLE_GREY:
  18818. use_rle = true;
  18819. case TGATools._TYPE_GREY:
  18820. use_grey = true;
  18821. break;
  18822. }
  18823. var pixel_data;
  18824. var numAlphaBits = header.flags & 0xf;
  18825. var pixel_size = header.pixel_size >> 3;
  18826. var pixel_total = header.width * header.height * pixel_size;
  18827. var palettes;
  18828. if (use_pal) {
  18829. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  18830. }
  18831. if (use_rle) {
  18832. pixel_data = new Uint8Array(pixel_total);
  18833. var c, count, i;
  18834. var localOffset = 0;
  18835. var pixels = new Uint8Array(pixel_size);
  18836. while (offset < pixel_total && localOffset < pixel_total) {
  18837. c = data[offset++];
  18838. count = (c & 0x7f) + 1;
  18839. if (c & 0x80) {
  18840. for (i = 0; i < pixel_size; ++i) {
  18841. pixels[i] = data[offset++];
  18842. }
  18843. for (i = 0; i < count; ++i) {
  18844. pixel_data.set(pixels, localOffset + i * pixel_size);
  18845. }
  18846. localOffset += pixel_size * count;
  18847. } else {
  18848. count *= pixel_size;
  18849. for (i = 0; i < count; ++i) {
  18850. pixel_data[localOffset + i] = data[offset++];
  18851. }
  18852. localOffset += count;
  18853. }
  18854. }
  18855. } else {
  18856. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  18857. }
  18858. var x_start, y_start, x_step, y_step, y_end, x_end;
  18859. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  18860. default:
  18861. case TGATools._ORIGIN_UL:
  18862. x_start = 0;
  18863. x_step = 1;
  18864. x_end = header.width;
  18865. y_start = 0;
  18866. y_step = 1;
  18867. y_end = header.height;
  18868. break;
  18869. case TGATools._ORIGIN_BL:
  18870. x_start = 0;
  18871. x_step = 1;
  18872. x_end = header.width;
  18873. y_start = header.height - 1;
  18874. y_step = -1;
  18875. y_end = -1;
  18876. break;
  18877. case TGATools._ORIGIN_UR:
  18878. x_start = header.width - 1;
  18879. x_step = -1;
  18880. x_end = -1;
  18881. y_start = 0;
  18882. y_step = 1;
  18883. y_end = header.height;
  18884. break;
  18885. case TGATools._ORIGIN_BR:
  18886. x_start = header.width - 1;
  18887. x_step = -1;
  18888. x_end = -1;
  18889. y_start = header.height - 1;
  18890. y_step = -1;
  18891. y_end = -1;
  18892. break;
  18893. }
  18894. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  18895. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  18896. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  18897. };
  18898. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18899. var image = pixel_data, colormap = palettes;
  18900. var width = header.width, height = header.height;
  18901. var color, i = 0, x, y;
  18902. var imageData = new Uint8Array(width * height * 4);
  18903. for (y = y_start; y !== y_end; y += y_step) {
  18904. for (x = x_start; x !== x_end; x += x_step, i++) {
  18905. color = image[i];
  18906. imageData[(x + width * y) * 4 + 3] = 255;
  18907. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  18908. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  18909. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  18910. }
  18911. }
  18912. return imageData;
  18913. };
  18914. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18915. var image = pixel_data;
  18916. var width = header.width, height = header.height;
  18917. var color, i = 0, x, y;
  18918. var imageData = new Uint8Array(width * height * 4);
  18919. for (y = y_start; y !== y_end; y += y_step) {
  18920. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  18921. color = image[i + 0] + (image[i + 1] << 8);
  18922. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  18923. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  18924. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  18925. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  18926. }
  18927. }
  18928. return imageData;
  18929. };
  18930. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18931. var image = pixel_data;
  18932. var width = header.width, height = header.height;
  18933. var i = 0, x, y;
  18934. var imageData = new Uint8Array(width * height * 4);
  18935. for (y = y_start; y !== y_end; y += y_step) {
  18936. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  18937. imageData[(x + width * y) * 4 + 3] = 255;
  18938. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  18939. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  18940. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  18941. }
  18942. }
  18943. return imageData;
  18944. };
  18945. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18946. var image = pixel_data;
  18947. var width = header.width, height = header.height;
  18948. var i = 0, x, y;
  18949. var imageData = new Uint8Array(width * height * 4);
  18950. for (y = y_start; y !== y_end; y += y_step) {
  18951. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  18952. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  18953. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  18954. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  18955. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  18956. }
  18957. }
  18958. return imageData;
  18959. };
  18960. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18961. var image = pixel_data;
  18962. var width = header.width, height = header.height;
  18963. var color, i = 0, x, y;
  18964. var imageData = new Uint8Array(width * height * 4);
  18965. for (y = y_start; y !== y_end; y += y_step) {
  18966. for (x = x_start; x !== x_end; x += x_step, i++) {
  18967. color = image[i];
  18968. imageData[(x + width * y) * 4 + 0] = color;
  18969. imageData[(x + width * y) * 4 + 1] = color;
  18970. imageData[(x + width * y) * 4 + 2] = color;
  18971. imageData[(x + width * y) * 4 + 3] = 255;
  18972. }
  18973. }
  18974. return imageData;
  18975. };
  18976. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18977. var image = pixel_data;
  18978. var width = header.width, height = header.height;
  18979. var i = 0, x, y;
  18980. var imageData = new Uint8Array(width * height * 4);
  18981. for (y = y_start; y !== y_end; y += y_step) {
  18982. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  18983. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  18984. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  18985. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  18986. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  18987. }
  18988. }
  18989. return imageData;
  18990. };
  18991. TGATools._TYPE_NO_DATA = 0;
  18992. TGATools._TYPE_INDEXED = 1;
  18993. TGATools._TYPE_RGB = 2;
  18994. TGATools._TYPE_GREY = 3;
  18995. TGATools._TYPE_RLE_INDEXED = 9;
  18996. TGATools._TYPE_RLE_RGB = 10;
  18997. TGATools._TYPE_RLE_GREY = 11;
  18998. TGATools._ORIGIN_MASK = 0x30;
  18999. TGATools._ORIGIN_SHIFT = 0x04;
  19000. TGATools._ORIGIN_BL = 0x00;
  19001. TGATools._ORIGIN_BR = 0x01;
  19002. TGATools._ORIGIN_UL = 0x02;
  19003. TGATools._ORIGIN_UR = 0x03;
  19004. return TGATools;
  19005. })();
  19006. Internals.TGATools = TGATools;
  19007. })(BABYLON.Internals || (BABYLON.Internals = {}));
  19008. var Internals = BABYLON.Internals;
  19009. })(BABYLON || (BABYLON = {}));
  19010. var BABYLON;
  19011. (function (BABYLON) {
  19012. (function (Internals) {
  19013. var DDS_MAGIC = 0x20534444;
  19014. 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;
  19015. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  19016. 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;
  19017. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  19018. function FourCCToInt32(value) {
  19019. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  19020. }
  19021. function Int32ToFourCC(value) {
  19022. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  19023. }
  19024. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  19025. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  19026. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  19027. var headerLengthInt = 31;
  19028. var off_magic = 0;
  19029. var off_size = 1;
  19030. var off_flags = 2;
  19031. var off_height = 3;
  19032. var off_width = 4;
  19033. var off_mipmapCount = 7;
  19034. var off_pfFlags = 20;
  19035. var off_pfFourCC = 21;
  19036. var off_RGBbpp = 22;
  19037. var off_RMask = 23;
  19038. var off_GMask = 24;
  19039. var off_BMask = 25;
  19040. var off_AMask = 26;
  19041. var off_caps1 = 27;
  19042. var off_caps2 = 28;
  19043. ;
  19044. var DDSTools = (function () {
  19045. function DDSTools() {
  19046. }
  19047. DDSTools.GetDDSInfo = function (arrayBuffer) {
  19048. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  19049. var mipmapCount = 1;
  19050. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  19051. mipmapCount = Math.max(1, header[off_mipmapCount]);
  19052. }
  19053. return {
  19054. width: header[off_width],
  19055. height: header[off_height],
  19056. mipmapCount: mipmapCount,
  19057. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  19058. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  19059. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  19060. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  19061. };
  19062. };
  19063. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  19064. var byteArray = new Uint8Array(dataLength);
  19065. var srcData = new Uint8Array(arrayBuffer);
  19066. var index = 0;
  19067. for (var y = height - 1; y >= 0; y--) {
  19068. for (var x = 0; x < width; x++) {
  19069. var srcPos = dataOffset + (x + y * width) * 4;
  19070. byteArray[index + 2] = srcData[srcPos];
  19071. byteArray[index + 1] = srcData[srcPos + 1];
  19072. byteArray[index] = srcData[srcPos + 2];
  19073. byteArray[index + 3] = srcData[srcPos + 3];
  19074. index += 4;
  19075. }
  19076. }
  19077. return byteArray;
  19078. };
  19079. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  19080. var byteArray = new Uint8Array(dataLength);
  19081. var srcData = new Uint8Array(arrayBuffer);
  19082. var index = 0;
  19083. for (var y = height - 1; y >= 0; y--) {
  19084. for (var x = 0; x < width; x++) {
  19085. var srcPos = dataOffset + (x + y * width) * 3;
  19086. byteArray[index + 2] = srcData[srcPos];
  19087. byteArray[index + 1] = srcData[srcPos + 1];
  19088. byteArray[index] = srcData[srcPos + 2];
  19089. index += 3;
  19090. }
  19091. }
  19092. return byteArray;
  19093. };
  19094. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  19095. var byteArray = new Uint8Array(dataLength);
  19096. var srcData = new Uint8Array(arrayBuffer);
  19097. var index = 0;
  19098. for (var y = height - 1; y >= 0; y--) {
  19099. for (var x = 0; x < width; x++) {
  19100. var srcPos = dataOffset + (x + y * width);
  19101. byteArray[index] = srcData[srcPos];
  19102. index++;
  19103. }
  19104. }
  19105. return byteArray;
  19106. };
  19107. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  19108. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  19109. if (header[off_magic] != DDS_MAGIC) {
  19110. BABYLON.Tools.Error("Invalid magic number in DDS header");
  19111. return;
  19112. }
  19113. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  19114. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  19115. return;
  19116. }
  19117. if (info.isFourCC) {
  19118. fourCC = header[off_pfFourCC];
  19119. switch (fourCC) {
  19120. case FOURCC_DXT1:
  19121. blockBytes = 8;
  19122. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  19123. break;
  19124. case FOURCC_DXT3:
  19125. blockBytes = 16;
  19126. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  19127. break;
  19128. case FOURCC_DXT5:
  19129. blockBytes = 16;
  19130. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  19131. break;
  19132. default:
  19133. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  19134. return;
  19135. }
  19136. }
  19137. mipmapCount = 1;
  19138. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  19139. mipmapCount = Math.max(1, header[off_mipmapCount]);
  19140. }
  19141. var bpp = header[off_RGBbpp];
  19142. for (var face = 0; face < faces; face++) {
  19143. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  19144. width = header[off_width];
  19145. height = header[off_height];
  19146. dataOffset = header[off_size] + 4;
  19147. for (i = 0; i < mipmapCount; ++i) {
  19148. if (info.isRGB) {
  19149. if (bpp == 24) {
  19150. dataLength = width * height * 3;
  19151. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  19152. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  19153. } else {
  19154. dataLength = width * height * 4;
  19155. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  19156. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  19157. }
  19158. } else if (info.isLuminance) {
  19159. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  19160. var unpaddedRowSize = width;
  19161. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  19162. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  19163. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  19164. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  19165. } else {
  19166. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  19167. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  19168. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  19169. }
  19170. dataOffset += dataLength;
  19171. width *= 0.5;
  19172. height *= 0.5;
  19173. width = Math.max(1.0, width);
  19174. height = Math.max(1.0, height);
  19175. }
  19176. }
  19177. };
  19178. return DDSTools;
  19179. })();
  19180. Internals.DDSTools = DDSTools;
  19181. })(BABYLON.Internals || (BABYLON.Internals = {}));
  19182. var Internals = BABYLON.Internals;
  19183. })(BABYLON || (BABYLON = {}));
  19184. var BABYLON;
  19185. (function (BABYLON) {
  19186. var SmartArray = (function () {
  19187. function SmartArray(capacity) {
  19188. this.length = 0;
  19189. this._duplicateId = 0;
  19190. this.data = new Array(capacity);
  19191. this._id = SmartArray._GlobalId++;
  19192. }
  19193. SmartArray.prototype.push = function (value) {
  19194. this.data[this.length++] = value;
  19195. if (this.length > this.data.length) {
  19196. this.data.length *= 2;
  19197. }
  19198. if (!value.__smartArrayFlags) {
  19199. value.__smartArrayFlags = {};
  19200. }
  19201. value.__smartArrayFlags[this._id] = this._duplicateId;
  19202. };
  19203. SmartArray.prototype.pushNoDuplicate = function (value) {
  19204. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  19205. return;
  19206. }
  19207. this.push(value);
  19208. };
  19209. SmartArray.prototype.sort = function (compareFn) {
  19210. this.data.sort(compareFn);
  19211. };
  19212. SmartArray.prototype.reset = function () {
  19213. this.length = 0;
  19214. this._duplicateId++;
  19215. };
  19216. SmartArray.prototype.concat = function (array) {
  19217. if (array.length === 0) {
  19218. return;
  19219. }
  19220. if (this.length + array.length > this.data.length) {
  19221. this.data.length = (this.length + array.length) * 2;
  19222. }
  19223. for (var index = 0; index < array.length; index++) {
  19224. this.data[this.length++] = (array.data || array)[index];
  19225. }
  19226. };
  19227. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  19228. if (array.length === 0) {
  19229. return;
  19230. }
  19231. if (this.length + array.length > this.data.length) {
  19232. this.data.length = (this.length + array.length) * 2;
  19233. }
  19234. for (var index = 0; index < array.length; index++) {
  19235. var item = (array.data || array)[index];
  19236. this.pushNoDuplicate(item);
  19237. }
  19238. };
  19239. SmartArray.prototype.indexOf = function (value) {
  19240. var position = this.data.indexOf(value);
  19241. if (position >= this.length) {
  19242. return -1;
  19243. }
  19244. return position;
  19245. };
  19246. SmartArray._GlobalId = 0;
  19247. return SmartArray;
  19248. })();
  19249. BABYLON.SmartArray = SmartArray;
  19250. })(BABYLON || (BABYLON = {}));
  19251. var BABYLON;
  19252. (function (BABYLON) {
  19253. var CannonJSPlugin = (function () {
  19254. function CannonJSPlugin() {
  19255. this._registeredMeshes = [];
  19256. this._physicsMaterials = [];
  19257. this.updateBodyPosition = function (mesh) {
  19258. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19259. var registeredMesh = this._registeredMeshes[index];
  19260. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  19261. var body = registeredMesh.body;
  19262. var center = mesh.getBoundingInfo().boundingBox.center;
  19263. body.position.set(center.x, center.z, center.y);
  19264. body.quaternion.x = mesh.rotationQuaternion.x;
  19265. body.quaternion.z = mesh.rotationQuaternion.y;
  19266. body.quaternion.y = mesh.rotationQuaternion.z;
  19267. body.quaternion.w = -mesh.rotationQuaternion.w;
  19268. return;
  19269. }
  19270. }
  19271. };
  19272. }
  19273. CannonJSPlugin.prototype.initialize = function (iterations) {
  19274. if (typeof iterations === "undefined") { iterations = 10; }
  19275. this._world = new CANNON.World();
  19276. this._world.broadphase = new CANNON.NaiveBroadphase();
  19277. this._world.solver.iterations = iterations;
  19278. };
  19279. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  19280. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  19281. };
  19282. CannonJSPlugin.prototype.runOneStep = function (delta) {
  19283. this._world.step(delta);
  19284. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19285. var registeredMesh = this._registeredMeshes[index];
  19286. if (registeredMesh.isChild) {
  19287. continue;
  19288. }
  19289. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  19290. var deltaPos = registeredMesh.delta;
  19291. if (deltaPos) {
  19292. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  19293. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  19294. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  19295. } else {
  19296. registeredMesh.mesh.position.x = bodyX;
  19297. registeredMesh.mesh.position.y = bodyZ;
  19298. registeredMesh.mesh.position.z = bodyY;
  19299. }
  19300. if (!registeredMesh.mesh.rotationQuaternion) {
  19301. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  19302. }
  19303. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  19304. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  19305. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  19306. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  19307. }
  19308. };
  19309. CannonJSPlugin.prototype.setGravity = function (gravity) {
  19310. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  19311. };
  19312. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  19313. this.unregisterMesh(mesh);
  19314. mesh.computeWorldMatrix(true);
  19315. switch (impostor) {
  19316. case BABYLON.PhysicsEngine.SphereImpostor:
  19317. var bbox = mesh.getBoundingInfo().boundingBox;
  19318. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  19319. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  19320. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  19321. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  19322. case BABYLON.PhysicsEngine.BoxImpostor:
  19323. bbox = mesh.getBoundingInfo().boundingBox;
  19324. var min = bbox.minimumWorld;
  19325. var max = bbox.maximumWorld;
  19326. var box = max.subtract(min).scale(0.5);
  19327. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  19328. case BABYLON.PhysicsEngine.PlaneImpostor:
  19329. return this._createPlane(mesh, options);
  19330. case BABYLON.PhysicsEngine.MeshImpostor:
  19331. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19332. var rawFaces = mesh.getIndices();
  19333. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  19334. }
  19335. return null;
  19336. };
  19337. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  19338. var shape = new CANNON.Sphere(radius);
  19339. if (!options) {
  19340. return shape;
  19341. }
  19342. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  19343. };
  19344. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  19345. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  19346. if (!options) {
  19347. return shape;
  19348. }
  19349. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  19350. };
  19351. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  19352. var shape = new CANNON.Plane();
  19353. if (!options) {
  19354. return shape;
  19355. }
  19356. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  19357. };
  19358. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  19359. var verts = [], faces = [];
  19360. mesh.computeWorldMatrix(true);
  19361. for (var i = 0; i < rawVerts.length; i += 3) {
  19362. var transformed = BABYLON.Vector3.Zero();
  19363. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  19364. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  19365. }
  19366. for (var j = 0; j < rawFaces.length; j += 3) {
  19367. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  19368. }
  19369. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  19370. if (!options) {
  19371. return shape;
  19372. }
  19373. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  19374. };
  19375. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  19376. var index;
  19377. var mat;
  19378. for (index = 0; index < this._physicsMaterials.length; index++) {
  19379. mat = this._physicsMaterials[index];
  19380. if (mat.friction === friction && mat.restitution === restitution) {
  19381. return mat;
  19382. }
  19383. }
  19384. var currentMat = new CANNON.Material();
  19385. currentMat.friction = friction;
  19386. currentMat.restitution = restitution;
  19387. this._physicsMaterials.push(currentMat);
  19388. for (index = 0; index < this._physicsMaterials.length; index++) {
  19389. mat = this._physicsMaterials[index];
  19390. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  19391. contactMaterial.contactEquationStiffness = 1e10;
  19392. contactMaterial.contactEquationRegularizationTime = 10;
  19393. this._world.addContactMaterial(contactMaterial);
  19394. }
  19395. return currentMat;
  19396. };
  19397. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  19398. var initialRotation = null;
  19399. if (mesh.rotationQuaternion) {
  19400. initialRotation = mesh.rotationQuaternion.clone();
  19401. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  19402. }
  19403. var bbox = mesh.getBoundingInfo().boundingBox;
  19404. var deltaPosition = mesh.position.subtract(bbox.center);
  19405. var material = this._addMaterial(friction, restitution);
  19406. var body = new CANNON.RigidBody(mass, shape, material);
  19407. if (initialRotation) {
  19408. body.quaternion.x = initialRotation.x;
  19409. body.quaternion.z = initialRotation.y;
  19410. body.quaternion.y = initialRotation.z;
  19411. body.quaternion.w = -initialRotation.w;
  19412. }
  19413. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  19414. this._world.add(body);
  19415. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  19416. return body;
  19417. };
  19418. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  19419. var compoundShape = new CANNON.Compound();
  19420. for (var index = 0; index < parts.length; index++) {
  19421. var mesh = parts[index].mesh;
  19422. var shape = this.registerMesh(mesh, parts[index].impostor);
  19423. if (index == 0) {
  19424. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  19425. } else {
  19426. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  19427. }
  19428. }
  19429. var initialMesh = parts[0].mesh;
  19430. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  19431. body.parts = parts;
  19432. return body;
  19433. };
  19434. CannonJSPlugin.prototype._unbindBody = function (body) {
  19435. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19436. var registeredMesh = this._registeredMeshes[index];
  19437. if (registeredMesh.body === body) {
  19438. registeredMesh.body = null;
  19439. registeredMesh.delta = 0;
  19440. }
  19441. }
  19442. };
  19443. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  19444. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19445. var registeredMesh = this._registeredMeshes[index];
  19446. if (registeredMesh.mesh === mesh) {
  19447. if (registeredMesh.body) {
  19448. this._world.remove(registeredMesh.body);
  19449. this._unbindBody(registeredMesh.body);
  19450. }
  19451. this._registeredMeshes.splice(index, 1);
  19452. return;
  19453. }
  19454. }
  19455. };
  19456. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  19457. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  19458. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  19459. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19460. var registeredMesh = this._registeredMeshes[index];
  19461. if (registeredMesh.mesh === mesh) {
  19462. registeredMesh.body.applyImpulse(impulse, worldPoint);
  19463. return;
  19464. }
  19465. }
  19466. };
  19467. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  19468. var body1 = null, body2 = null;
  19469. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19470. var registeredMesh = this._registeredMeshes[index];
  19471. if (registeredMesh.mesh === mesh1) {
  19472. body1 = registeredMesh.body;
  19473. } else if (registeredMesh.mesh === mesh2) {
  19474. body2 = registeredMesh.body;
  19475. }
  19476. }
  19477. if (!body1 || !body2) {
  19478. return false;
  19479. }
  19480. 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));
  19481. this._world.addConstraint(constraint);
  19482. return true;
  19483. };
  19484. CannonJSPlugin.prototype.dispose = function () {
  19485. while (this._registeredMeshes.length) {
  19486. this.unregisterMesh(this._registeredMeshes[0].mesh);
  19487. }
  19488. };
  19489. CannonJSPlugin.prototype.isSupported = function () {
  19490. return window.CANNON !== undefined;
  19491. };
  19492. return CannonJSPlugin;
  19493. })();
  19494. BABYLON.CannonJSPlugin = CannonJSPlugin;
  19495. })(BABYLON || (BABYLON = {}));
  19496. var __extends = this.__extends || function (d, b) {
  19497. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19498. function __() { this.constructor = d; }
  19499. __.prototype = b.prototype;
  19500. d.prototype = new __();
  19501. };
  19502. var BABYLON;
  19503. (function (BABYLON) {
  19504. var Condition = (function () {
  19505. function Condition(actionManager) {
  19506. this._actionManager = actionManager;
  19507. }
  19508. Condition.prototype.isValid = function () {
  19509. return true;
  19510. };
  19511. Condition.prototype._getProperty = function (propertyPath) {
  19512. return this._actionManager._getProperty(propertyPath);
  19513. };
  19514. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  19515. return this._actionManager._getEffectiveTarget(target, propertyPath);
  19516. };
  19517. return Condition;
  19518. })();
  19519. BABYLON.Condition = Condition;
  19520. var ValueCondition = (function (_super) {
  19521. __extends(ValueCondition, _super);
  19522. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  19523. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  19524. _super.call(this, actionManager);
  19525. this.propertyPath = propertyPath;
  19526. this.value = value;
  19527. this.operator = operator;
  19528. this._target = this._getEffectiveTarget(target, this.propertyPath);
  19529. this._property = this._getProperty(this.propertyPath);
  19530. }
  19531. Object.defineProperty(ValueCondition, "IsEqual", {
  19532. get: function () {
  19533. return ValueCondition._IsEqual;
  19534. },
  19535. enumerable: true,
  19536. configurable: true
  19537. });
  19538. Object.defineProperty(ValueCondition, "IsDifferent", {
  19539. get: function () {
  19540. return ValueCondition._IsDifferent;
  19541. },
  19542. enumerable: true,
  19543. configurable: true
  19544. });
  19545. Object.defineProperty(ValueCondition, "IsGreater", {
  19546. get: function () {
  19547. return ValueCondition._IsGreater;
  19548. },
  19549. enumerable: true,
  19550. configurable: true
  19551. });
  19552. Object.defineProperty(ValueCondition, "IsLesser", {
  19553. get: function () {
  19554. return ValueCondition._IsLesser;
  19555. },
  19556. enumerable: true,
  19557. configurable: true
  19558. });
  19559. ValueCondition.prototype.isValid = function () {
  19560. switch (this.operator) {
  19561. case ValueCondition.IsGreater:
  19562. return this._target[this._property] > this.value;
  19563. case ValueCondition.IsLesser:
  19564. return this._target[this._property] < this.value;
  19565. case ValueCondition.IsEqual:
  19566. case ValueCondition.IsDifferent:
  19567. var check;
  19568. if (this.value.equals) {
  19569. check = this.value.equals(this._target[this._property]);
  19570. } else {
  19571. check = this.value === this._target[this._property];
  19572. }
  19573. return this.operator === ValueCondition.IsEqual ? check : !check;
  19574. }
  19575. return false;
  19576. };
  19577. ValueCondition._IsEqual = 0;
  19578. ValueCondition._IsDifferent = 1;
  19579. ValueCondition._IsGreater = 2;
  19580. ValueCondition._IsLesser = 3;
  19581. return ValueCondition;
  19582. })(Condition);
  19583. BABYLON.ValueCondition = ValueCondition;
  19584. var PredicateCondition = (function (_super) {
  19585. __extends(PredicateCondition, _super);
  19586. function PredicateCondition(actionManager, predicate) {
  19587. _super.call(this, actionManager);
  19588. this.predicate = predicate;
  19589. }
  19590. PredicateCondition.prototype.isValid = function () {
  19591. return this.predicate();
  19592. };
  19593. return PredicateCondition;
  19594. })(Condition);
  19595. BABYLON.PredicateCondition = PredicateCondition;
  19596. var StateCondition = (function (_super) {
  19597. __extends(StateCondition, _super);
  19598. function StateCondition(actionManager, target, value) {
  19599. _super.call(this, actionManager);
  19600. this.value = value;
  19601. this._target = target;
  19602. }
  19603. StateCondition.prototype.isValid = function () {
  19604. return this._target.state === this.value;
  19605. };
  19606. return StateCondition;
  19607. })(Condition);
  19608. BABYLON.StateCondition = StateCondition;
  19609. })(BABYLON || (BABYLON = {}));
  19610. var BABYLON;
  19611. (function (BABYLON) {
  19612. var Action = (function () {
  19613. function Action(triggerOptions, condition) {
  19614. this.triggerOptions = triggerOptions;
  19615. if (triggerOptions.parameter) {
  19616. this.trigger = triggerOptions.trigger;
  19617. this._triggerParameter = triggerOptions.parameter;
  19618. } else {
  19619. this.trigger = triggerOptions;
  19620. }
  19621. this._nextActiveAction = this;
  19622. this._condition = condition;
  19623. }
  19624. Action.prototype._prepare = function () {
  19625. };
  19626. Action.prototype.getTriggerParameter = function () {
  19627. return this._triggerParameter;
  19628. };
  19629. Action.prototype._executeCurrent = function (evt) {
  19630. if (this._condition) {
  19631. var currentRenderId = this._actionManager.getScene().getRenderId();
  19632. if (this._condition._evaluationId === currentRenderId) {
  19633. if (!this._condition._currentResult) {
  19634. return;
  19635. }
  19636. } else {
  19637. this._condition._evaluationId = currentRenderId;
  19638. if (!this._condition.isValid()) {
  19639. this._condition._currentResult = false;
  19640. return;
  19641. }
  19642. this._condition._currentResult = true;
  19643. }
  19644. }
  19645. this._nextActiveAction.execute(evt);
  19646. if (this._nextActiveAction._child) {
  19647. if (!this._nextActiveAction._child._actionManager) {
  19648. this._nextActiveAction._child._actionManager = this._actionManager;
  19649. }
  19650. this._nextActiveAction = this._nextActiveAction._child;
  19651. } else {
  19652. this._nextActiveAction = this;
  19653. }
  19654. };
  19655. Action.prototype.execute = function (evt) {
  19656. };
  19657. Action.prototype.then = function (action) {
  19658. this._child = action;
  19659. action._actionManager = this._actionManager;
  19660. action._prepare();
  19661. return action;
  19662. };
  19663. Action.prototype._getProperty = function (propertyPath) {
  19664. return this._actionManager._getProperty(propertyPath);
  19665. };
  19666. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  19667. return this._actionManager._getEffectiveTarget(target, propertyPath);
  19668. };
  19669. return Action;
  19670. })();
  19671. BABYLON.Action = Action;
  19672. })(BABYLON || (BABYLON = {}));
  19673. var BABYLON;
  19674. (function (BABYLON) {
  19675. var ActionEvent = (function () {
  19676. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  19677. this.source = source;
  19678. this.pointerX = pointerX;
  19679. this.pointerY = pointerY;
  19680. this.meshUnderPointer = meshUnderPointer;
  19681. this.sourceEvent = sourceEvent;
  19682. }
  19683. ActionEvent.CreateNew = function (source) {
  19684. var scene = source.getScene();
  19685. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer);
  19686. };
  19687. ActionEvent.CreateNewFromScene = function (scene, evt) {
  19688. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  19689. };
  19690. return ActionEvent;
  19691. })();
  19692. BABYLON.ActionEvent = ActionEvent;
  19693. var ActionManager = (function () {
  19694. function ActionManager(scene) {
  19695. this.actions = new Array();
  19696. this._scene = scene;
  19697. scene._actionManagers.push(this);
  19698. }
  19699. Object.defineProperty(ActionManager, "NothingTrigger", {
  19700. get: function () {
  19701. return ActionManager._NothingTrigger;
  19702. },
  19703. enumerable: true,
  19704. configurable: true
  19705. });
  19706. Object.defineProperty(ActionManager, "OnPickTrigger", {
  19707. get: function () {
  19708. return ActionManager._OnPickTrigger;
  19709. },
  19710. enumerable: true,
  19711. configurable: true
  19712. });
  19713. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  19714. get: function () {
  19715. return ActionManager._OnLeftPickTrigger;
  19716. },
  19717. enumerable: true,
  19718. configurable: true
  19719. });
  19720. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  19721. get: function () {
  19722. return ActionManager._OnRightPickTrigger;
  19723. },
  19724. enumerable: true,
  19725. configurable: true
  19726. });
  19727. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  19728. get: function () {
  19729. return ActionManager._OnCenterPickTrigger;
  19730. },
  19731. enumerable: true,
  19732. configurable: true
  19733. });
  19734. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  19735. get: function () {
  19736. return ActionManager._OnPointerOverTrigger;
  19737. },
  19738. enumerable: true,
  19739. configurable: true
  19740. });
  19741. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  19742. get: function () {
  19743. return ActionManager._OnPointerOutTrigger;
  19744. },
  19745. enumerable: true,
  19746. configurable: true
  19747. });
  19748. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  19749. get: function () {
  19750. return ActionManager._OnEveryFrameTrigger;
  19751. },
  19752. enumerable: true,
  19753. configurable: true
  19754. });
  19755. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  19756. get: function () {
  19757. return ActionManager._OnIntersectionEnterTrigger;
  19758. },
  19759. enumerable: true,
  19760. configurable: true
  19761. });
  19762. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  19763. get: function () {
  19764. return ActionManager._OnIntersectionExitTrigger;
  19765. },
  19766. enumerable: true,
  19767. configurable: true
  19768. });
  19769. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  19770. get: function () {
  19771. return ActionManager._OnKeyDownTrigger;
  19772. },
  19773. enumerable: true,
  19774. configurable: true
  19775. });
  19776. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  19777. get: function () {
  19778. return ActionManager._OnKeyUpTrigger;
  19779. },
  19780. enumerable: true,
  19781. configurable: true
  19782. });
  19783. ActionManager.prototype.dispose = function () {
  19784. var index = this._scene._actionManagers.indexOf(this);
  19785. if (index > -1) {
  19786. this._scene._actionManagers.splice(index, 1);
  19787. }
  19788. };
  19789. ActionManager.prototype.getScene = function () {
  19790. return this._scene;
  19791. };
  19792. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  19793. for (var index = 0; index < this.actions.length; index++) {
  19794. var action = this.actions[index];
  19795. if (triggers.indexOf(action.trigger) > -1) {
  19796. return true;
  19797. }
  19798. }
  19799. return false;
  19800. };
  19801. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  19802. get: function () {
  19803. for (var index = 0; index < this.actions.length; index++) {
  19804. var action = this.actions[index];
  19805. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  19806. return true;
  19807. }
  19808. }
  19809. return false;
  19810. },
  19811. enumerable: true,
  19812. configurable: true
  19813. });
  19814. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  19815. get: function () {
  19816. for (var index = 0; index < this.actions.length; index++) {
  19817. var action = this.actions[index];
  19818. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  19819. return true;
  19820. }
  19821. }
  19822. return false;
  19823. },
  19824. enumerable: true,
  19825. configurable: true
  19826. });
  19827. ActionManager.prototype.registerAction = function (action) {
  19828. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  19829. if (this.getScene().actionManager !== this) {
  19830. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  19831. return null;
  19832. }
  19833. }
  19834. this.actions.push(action);
  19835. action._actionManager = this;
  19836. action._prepare();
  19837. return action;
  19838. };
  19839. ActionManager.prototype.processTrigger = function (trigger, evt) {
  19840. for (var index = 0; index < this.actions.length; index++) {
  19841. var action = this.actions[index];
  19842. if (action.trigger === trigger) {
  19843. if (trigger == ActionManager.OnKeyUpTrigger || trigger == ActionManager.OnKeyDownTrigger) {
  19844. var parameter = action.getTriggerParameter();
  19845. if (parameter) {
  19846. if (evt.sourceEvent.key !== parameter) {
  19847. continue;
  19848. }
  19849. }
  19850. }
  19851. action._executeCurrent(evt);
  19852. }
  19853. }
  19854. };
  19855. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  19856. var properties = propertyPath.split(".");
  19857. for (var index = 0; index < properties.length - 1; index++) {
  19858. target = target[properties[index]];
  19859. }
  19860. return target;
  19861. };
  19862. ActionManager.prototype._getProperty = function (propertyPath) {
  19863. var properties = propertyPath.split(".");
  19864. return properties[properties.length - 1];
  19865. };
  19866. ActionManager._NothingTrigger = 0;
  19867. ActionManager._OnPickTrigger = 1;
  19868. ActionManager._OnLeftPickTrigger = 2;
  19869. ActionManager._OnRightPickTrigger = 3;
  19870. ActionManager._OnCenterPickTrigger = 4;
  19871. ActionManager._OnPointerOverTrigger = 5;
  19872. ActionManager._OnPointerOutTrigger = 6;
  19873. ActionManager._OnEveryFrameTrigger = 7;
  19874. ActionManager._OnIntersectionEnterTrigger = 8;
  19875. ActionManager._OnIntersectionExitTrigger = 9;
  19876. ActionManager._OnKeyDownTrigger = 10;
  19877. ActionManager._OnKeyUpTrigger = 11;
  19878. return ActionManager;
  19879. })();
  19880. BABYLON.ActionManager = ActionManager;
  19881. })(BABYLON || (BABYLON = {}));
  19882. var __extends = this.__extends || function (d, b) {
  19883. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19884. function __() { this.constructor = d; }
  19885. __.prototype = b.prototype;
  19886. d.prototype = new __();
  19887. };
  19888. var BABYLON;
  19889. (function (BABYLON) {
  19890. var InterpolateValueAction = (function (_super) {
  19891. __extends(InterpolateValueAction, _super);
  19892. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  19893. if (typeof duration === "undefined") { duration = 1000; }
  19894. _super.call(this, triggerOptions, condition);
  19895. this.propertyPath = propertyPath;
  19896. this.value = value;
  19897. this.duration = duration;
  19898. this.stopOtherAnimations = stopOtherAnimations;
  19899. this._target = target;
  19900. }
  19901. InterpolateValueAction.prototype._prepare = function () {
  19902. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19903. this._property = this._getProperty(this.propertyPath);
  19904. };
  19905. InterpolateValueAction.prototype.execute = function () {
  19906. var scene = this._actionManager.getScene();
  19907. var keys = [
  19908. {
  19909. frame: 0,
  19910. value: this._target[this._property]
  19911. }, {
  19912. frame: 100,
  19913. value: this.value
  19914. }
  19915. ];
  19916. var dataType;
  19917. if (typeof this.value === "number") {
  19918. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  19919. } else if (this.value instanceof BABYLON.Color3) {
  19920. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  19921. } else if (this.value instanceof BABYLON.Vector3) {
  19922. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  19923. } else if (this.value instanceof BABYLON.Matrix) {
  19924. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  19925. } else if (this.value instanceof BABYLON.Quaternion) {
  19926. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  19927. } else {
  19928. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  19929. return;
  19930. }
  19931. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  19932. animation.setKeys(keys);
  19933. if (this.stopOtherAnimations) {
  19934. scene.stopAnimation(this._target);
  19935. }
  19936. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  19937. };
  19938. return InterpolateValueAction;
  19939. })(BABYLON.Action);
  19940. BABYLON.InterpolateValueAction = InterpolateValueAction;
  19941. })(BABYLON || (BABYLON = {}));
  19942. var __extends = this.__extends || function (d, b) {
  19943. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19944. function __() { this.constructor = d; }
  19945. __.prototype = b.prototype;
  19946. d.prototype = new __();
  19947. };
  19948. var BABYLON;
  19949. (function (BABYLON) {
  19950. var SwitchBooleanAction = (function (_super) {
  19951. __extends(SwitchBooleanAction, _super);
  19952. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  19953. _super.call(this, triggerOptions, condition);
  19954. this.propertyPath = propertyPath;
  19955. this._target = target;
  19956. }
  19957. SwitchBooleanAction.prototype._prepare = function () {
  19958. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19959. this._property = this._getProperty(this.propertyPath);
  19960. };
  19961. SwitchBooleanAction.prototype.execute = function () {
  19962. this._target[this._property] = !this._target[this._property];
  19963. };
  19964. return SwitchBooleanAction;
  19965. })(BABYLON.Action);
  19966. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  19967. var SetStateAction = (function (_super) {
  19968. __extends(SetStateAction, _super);
  19969. function SetStateAction(triggerOptions, target, value, condition) {
  19970. _super.call(this, triggerOptions, condition);
  19971. this.value = value;
  19972. this._target = target;
  19973. }
  19974. SetStateAction.prototype.execute = function () {
  19975. this._target.state = this.value;
  19976. };
  19977. return SetStateAction;
  19978. })(BABYLON.Action);
  19979. BABYLON.SetStateAction = SetStateAction;
  19980. var SetValueAction = (function (_super) {
  19981. __extends(SetValueAction, _super);
  19982. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  19983. _super.call(this, triggerOptions, condition);
  19984. this.propertyPath = propertyPath;
  19985. this.value = value;
  19986. this._target = target;
  19987. }
  19988. SetValueAction.prototype._prepare = function () {
  19989. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19990. this._property = this._getProperty(this.propertyPath);
  19991. };
  19992. SetValueAction.prototype.execute = function () {
  19993. this._target[this._property] = this.value;
  19994. };
  19995. return SetValueAction;
  19996. })(BABYLON.Action);
  19997. BABYLON.SetValueAction = SetValueAction;
  19998. var IncrementValueAction = (function (_super) {
  19999. __extends(IncrementValueAction, _super);
  20000. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  20001. _super.call(this, triggerOptions, condition);
  20002. this.propertyPath = propertyPath;
  20003. this.value = value;
  20004. this._target = target;
  20005. }
  20006. IncrementValueAction.prototype._prepare = function () {
  20007. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  20008. this._property = this._getProperty(this.propertyPath);
  20009. if (typeof this._target[this._property] !== "number") {
  20010. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  20011. }
  20012. };
  20013. IncrementValueAction.prototype.execute = function () {
  20014. this._target[this._property] += this.value;
  20015. };
  20016. return IncrementValueAction;
  20017. })(BABYLON.Action);
  20018. BABYLON.IncrementValueAction = IncrementValueAction;
  20019. var PlayAnimationAction = (function (_super) {
  20020. __extends(PlayAnimationAction, _super);
  20021. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  20022. _super.call(this, triggerOptions, condition);
  20023. this.from = from;
  20024. this.to = to;
  20025. this.loop = loop;
  20026. this._target = target;
  20027. }
  20028. PlayAnimationAction.prototype._prepare = function () {
  20029. };
  20030. PlayAnimationAction.prototype.execute = function () {
  20031. var scene = this._actionManager.getScene();
  20032. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  20033. };
  20034. return PlayAnimationAction;
  20035. })(BABYLON.Action);
  20036. BABYLON.PlayAnimationAction = PlayAnimationAction;
  20037. var StopAnimationAction = (function (_super) {
  20038. __extends(StopAnimationAction, _super);
  20039. function StopAnimationAction(triggerOptions, target, condition) {
  20040. _super.call(this, triggerOptions, condition);
  20041. this._target = target;
  20042. }
  20043. StopAnimationAction.prototype._prepare = function () {
  20044. };
  20045. StopAnimationAction.prototype.execute = function () {
  20046. var scene = this._actionManager.getScene();
  20047. scene.stopAnimation(this._target);
  20048. };
  20049. return StopAnimationAction;
  20050. })(BABYLON.Action);
  20051. BABYLON.StopAnimationAction = StopAnimationAction;
  20052. var DoNothingAction = (function (_super) {
  20053. __extends(DoNothingAction, _super);
  20054. function DoNothingAction(triggerOptions, condition) {
  20055. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  20056. _super.call(this, triggerOptions, condition);
  20057. }
  20058. DoNothingAction.prototype.execute = function () {
  20059. };
  20060. return DoNothingAction;
  20061. })(BABYLON.Action);
  20062. BABYLON.DoNothingAction = DoNothingAction;
  20063. var CombineAction = (function (_super) {
  20064. __extends(CombineAction, _super);
  20065. function CombineAction(triggerOptions, children, condition) {
  20066. _super.call(this, triggerOptions, condition);
  20067. this.children = children;
  20068. }
  20069. CombineAction.prototype._prepare = function () {
  20070. for (var index = 0; index < this.children.length; index++) {
  20071. this.children[index]._actionManager = this._actionManager;
  20072. this.children[index]._prepare();
  20073. }
  20074. };
  20075. CombineAction.prototype.execute = function (evt) {
  20076. for (var index = 0; index < this.children.length; index++) {
  20077. this.children[index].execute(evt);
  20078. }
  20079. };
  20080. return CombineAction;
  20081. })(BABYLON.Action);
  20082. BABYLON.CombineAction = CombineAction;
  20083. var ExecuteCodeAction = (function (_super) {
  20084. __extends(ExecuteCodeAction, _super);
  20085. function ExecuteCodeAction(triggerOptions, func, condition) {
  20086. _super.call(this, triggerOptions, condition);
  20087. this.func = func;
  20088. }
  20089. ExecuteCodeAction.prototype.execute = function (evt) {
  20090. this.func(evt);
  20091. };
  20092. return ExecuteCodeAction;
  20093. })(BABYLON.Action);
  20094. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  20095. var SetParentAction = (function (_super) {
  20096. __extends(SetParentAction, _super);
  20097. function SetParentAction(triggerOptions, target, parent, condition) {
  20098. _super.call(this, triggerOptions, condition);
  20099. this._target = target;
  20100. this._parent = parent;
  20101. }
  20102. SetParentAction.prototype._prepare = function () {
  20103. };
  20104. SetParentAction.prototype.execute = function () {
  20105. if (this._target.parent === this._parent) {
  20106. return;
  20107. }
  20108. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  20109. invertParentWorldMatrix.invert();
  20110. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  20111. this._target.parent = this._parent;
  20112. };
  20113. return SetParentAction;
  20114. })(BABYLON.Action);
  20115. BABYLON.SetParentAction = SetParentAction;
  20116. })(BABYLON || (BABYLON = {}));
  20117. var __extends = this.__extends || function (d, b) {
  20118. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20119. function __() { this.constructor = d; }
  20120. __.prototype = b.prototype;
  20121. d.prototype = new __();
  20122. };
  20123. var BABYLON;
  20124. (function (BABYLON) {
  20125. var Geometry = (function () {
  20126. function Geometry(id, scene, vertexData, updatable, mesh) {
  20127. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20128. this._totalVertices = 0;
  20129. this._indices = [];
  20130. this.id = id;
  20131. this._engine = scene.getEngine();
  20132. this._meshes = [];
  20133. this._scene = scene;
  20134. if (vertexData) {
  20135. this.setAllVerticesData(vertexData, updatable);
  20136. } else {
  20137. this._totalVertices = 0;
  20138. this._indices = [];
  20139. }
  20140. if (mesh) {
  20141. this.applyToMesh(mesh);
  20142. }
  20143. }
  20144. Geometry.prototype.getScene = function () {
  20145. return this._scene;
  20146. };
  20147. Geometry.prototype.getEngine = function () {
  20148. return this._engine;
  20149. };
  20150. Geometry.prototype.isReady = function () {
  20151. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  20152. };
  20153. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  20154. vertexData.applyToGeometry(this, updatable);
  20155. };
  20156. Geometry.prototype.setVerticesData = function (kind, data, updatable) {
  20157. this._vertexBuffers = this._vertexBuffers || {};
  20158. if (this._vertexBuffers[kind]) {
  20159. this._vertexBuffers[kind].dispose();
  20160. }
  20161. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0);
  20162. if (kind === BABYLON.VertexBuffer.PositionKind) {
  20163. var stride = this._vertexBuffers[kind].getStrideSize();
  20164. this._totalVertices = data.length / stride;
  20165. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  20166. var meshes = this._meshes;
  20167. var numOfMeshes = meshes.length;
  20168. for (var index = 0; index < numOfMeshes; index++) {
  20169. var mesh = meshes[index];
  20170. mesh._resetPointsArrayCache();
  20171. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20172. mesh._createGlobalSubMesh();
  20173. mesh.computeWorldMatrix(true);
  20174. }
  20175. }
  20176. };
  20177. Geometry.prototype.updateVerticesDataDirectly = function (kind, data) {
  20178. var vertexBuffer = this.getVertexBuffer(kind);
  20179. if (!vertexBuffer) {
  20180. return;
  20181. }
  20182. vertexBuffer.updateDirectly(data);
  20183. };
  20184. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  20185. var vertexBuffer = this.getVertexBuffer(kind);
  20186. if (!vertexBuffer) {
  20187. return;
  20188. }
  20189. vertexBuffer.update(data);
  20190. if (kind === BABYLON.VertexBuffer.PositionKind) {
  20191. var extend;
  20192. if (updateExtends) {
  20193. var stride = vertexBuffer.getStrideSize();
  20194. this._totalVertices = data.length / stride;
  20195. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  20196. }
  20197. var meshes = this._meshes;
  20198. var numOfMeshes = meshes.length;
  20199. for (var index = 0; index < numOfMeshes; index++) {
  20200. var mesh = meshes[index];
  20201. mesh._resetPointsArrayCache();
  20202. if (updateExtends) {
  20203. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20204. }
  20205. }
  20206. }
  20207. };
  20208. Geometry.prototype.getTotalVertices = function () {
  20209. if (!this.isReady()) {
  20210. return 0;
  20211. }
  20212. return this._totalVertices;
  20213. };
  20214. Geometry.prototype.getVerticesData = function (kind) {
  20215. var vertexBuffer = this.getVertexBuffer(kind);
  20216. if (!vertexBuffer) {
  20217. return null;
  20218. }
  20219. return vertexBuffer.getData();
  20220. };
  20221. Geometry.prototype.getVertexBuffer = function (kind) {
  20222. if (!this.isReady()) {
  20223. return null;
  20224. }
  20225. return this._vertexBuffers[kind];
  20226. };
  20227. Geometry.prototype.getVertexBuffers = function () {
  20228. if (!this.isReady()) {
  20229. return null;
  20230. }
  20231. return this._vertexBuffers;
  20232. };
  20233. Geometry.prototype.isVerticesDataPresent = function (kind) {
  20234. if (!this._vertexBuffers) {
  20235. if (this._delayInfo) {
  20236. return this._delayInfo.indexOf(kind) !== -1;
  20237. }
  20238. return false;
  20239. }
  20240. return this._vertexBuffers[kind] !== undefined;
  20241. };
  20242. Geometry.prototype.getVerticesDataKinds = function () {
  20243. var result = [];
  20244. if (!this._vertexBuffers && this._delayInfo) {
  20245. for (var kind in this._delayInfo) {
  20246. result.push(kind);
  20247. }
  20248. } else {
  20249. for (kind in this._vertexBuffers) {
  20250. result.push(kind);
  20251. }
  20252. }
  20253. return result;
  20254. };
  20255. Geometry.prototype.setIndices = function (indices) {
  20256. if (this._indexBuffer) {
  20257. this._engine._releaseBuffer(this._indexBuffer);
  20258. }
  20259. this._indices = indices;
  20260. if (this._meshes.length !== 0 && this._indices) {
  20261. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  20262. }
  20263. var meshes = this._meshes;
  20264. var numOfMeshes = meshes.length;
  20265. for (var index = 0; index < numOfMeshes; index++) {
  20266. meshes[index]._createGlobalSubMesh();
  20267. }
  20268. };
  20269. Geometry.prototype.getTotalIndices = function () {
  20270. if (!this.isReady()) {
  20271. return 0;
  20272. }
  20273. return this._indices.length;
  20274. };
  20275. Geometry.prototype.getIndices = function () {
  20276. if (!this.isReady()) {
  20277. return null;
  20278. }
  20279. return this._indices;
  20280. };
  20281. Geometry.prototype.getIndexBuffer = function () {
  20282. if (!this.isReady()) {
  20283. return null;
  20284. }
  20285. return this._indexBuffer;
  20286. };
  20287. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  20288. var meshes = this._meshes;
  20289. var index = meshes.indexOf(mesh);
  20290. if (index === -1) {
  20291. return;
  20292. }
  20293. for (var kind in this._vertexBuffers) {
  20294. this._vertexBuffers[kind].dispose();
  20295. }
  20296. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  20297. this._indexBuffer = null;
  20298. }
  20299. meshes.splice(index, 1);
  20300. mesh._geometry = null;
  20301. if (meshes.length == 0 && shouldDispose) {
  20302. this.dispose();
  20303. }
  20304. };
  20305. Geometry.prototype.applyToMesh = function (mesh) {
  20306. if (mesh._geometry === this) {
  20307. return;
  20308. }
  20309. var previousGeometry = mesh._geometry;
  20310. if (previousGeometry) {
  20311. previousGeometry.releaseForMesh(mesh);
  20312. }
  20313. var meshes = this._meshes;
  20314. mesh._geometry = this;
  20315. this._scene.pushGeometry(this);
  20316. meshes.push(mesh);
  20317. if (this.isReady()) {
  20318. this._applyToMesh(mesh);
  20319. } else {
  20320. mesh._boundingInfo = this._boundingInfo;
  20321. }
  20322. };
  20323. Geometry.prototype._applyToMesh = function (mesh) {
  20324. var numOfMeshes = this._meshes.length;
  20325. for (var kind in this._vertexBuffers) {
  20326. if (numOfMeshes === 1) {
  20327. this._vertexBuffers[kind].create();
  20328. }
  20329. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  20330. if (kind === BABYLON.VertexBuffer.PositionKind) {
  20331. mesh._resetPointsArrayCache();
  20332. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  20333. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20334. mesh._createGlobalSubMesh();
  20335. }
  20336. }
  20337. if (numOfMeshes === 1 && this._indices) {
  20338. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  20339. }
  20340. if (this._indexBuffer) {
  20341. this._indexBuffer.references = numOfMeshes;
  20342. }
  20343. };
  20344. Geometry.prototype.load = function (scene, onLoaded) {
  20345. var _this = this;
  20346. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20347. return;
  20348. }
  20349. if (this.isReady()) {
  20350. if (onLoaded) {
  20351. onLoaded();
  20352. }
  20353. return;
  20354. }
  20355. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20356. scene._addPendingData(this);
  20357. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20358. _this._delayLoadingFunction(JSON.parse(data), _this);
  20359. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20360. _this._delayInfo = [];
  20361. scene._removePendingData(_this);
  20362. var meshes = _this._meshes;
  20363. var numOfMeshes = meshes.length;
  20364. for (var index = 0; index < numOfMeshes; index++) {
  20365. _this._applyToMesh(meshes[index]);
  20366. }
  20367. if (onLoaded) {
  20368. onLoaded();
  20369. }
  20370. }, function () {
  20371. }, scene.database);
  20372. };
  20373. Geometry.prototype.dispose = function () {
  20374. var meshes = this._meshes;
  20375. var numOfMeshes = meshes.length;
  20376. for (var index = 0; index < numOfMeshes; index++) {
  20377. this.releaseForMesh(meshes[index]);
  20378. }
  20379. this._meshes = [];
  20380. for (var kind in this._vertexBuffers) {
  20381. this._vertexBuffers[kind].dispose();
  20382. }
  20383. this._vertexBuffers = [];
  20384. this._totalVertices = 0;
  20385. if (this._indexBuffer) {
  20386. this._engine._releaseBuffer(this._indexBuffer);
  20387. }
  20388. this._indexBuffer = null;
  20389. this._indices = [];
  20390. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20391. this.delayLoadingFile = null;
  20392. this._delayLoadingFunction = null;
  20393. this._delayInfo = [];
  20394. this._boundingInfo = null;
  20395. var geometries = this._scene.getGeometries();
  20396. index = geometries.indexOf(this);
  20397. if (index > -1) {
  20398. geometries.splice(index, 1);
  20399. }
  20400. };
  20401. Geometry.prototype.copy = function (id) {
  20402. var vertexData = new BABYLON.VertexData();
  20403. vertexData.indices = [];
  20404. var indices = this.getIndices();
  20405. for (var index = 0; index < indices.length; index++) {
  20406. vertexData.indices.push(indices[index]);
  20407. }
  20408. var updatable = false;
  20409. var stopChecking = false;
  20410. for (var kind in this._vertexBuffers) {
  20411. vertexData.set(this.getVerticesData(kind), kind);
  20412. if (!stopChecking) {
  20413. updatable = this.getVertexBuffer(kind).isUpdatable();
  20414. stopChecking = !updatable;
  20415. }
  20416. }
  20417. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  20418. geometry.delayLoadState = this.delayLoadState;
  20419. geometry.delayLoadingFile = this.delayLoadingFile;
  20420. geometry._delayLoadingFunction = this._delayLoadingFunction;
  20421. for (kind in this._delayInfo) {
  20422. geometry._delayInfo = geometry._delayInfo || [];
  20423. geometry._delayInfo.push(kind);
  20424. }
  20425. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  20426. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20427. return geometry;
  20428. };
  20429. Geometry.ExtractFromMesh = function (mesh, id) {
  20430. var geometry = mesh._geometry;
  20431. if (!geometry) {
  20432. return null;
  20433. }
  20434. return geometry.copy(id);
  20435. };
  20436. Geometry.RandomId = function () {
  20437. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  20438. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  20439. return v.toString(16);
  20440. });
  20441. };
  20442. return Geometry;
  20443. })();
  20444. BABYLON.Geometry = Geometry;
  20445. (function (Geometry) {
  20446. (function (Primitives) {
  20447. var _Primitive = (function (_super) {
  20448. __extends(_Primitive, _super);
  20449. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  20450. this._beingRegenerated = true;
  20451. this._canBeRegenerated = canBeRegenerated;
  20452. _super.call(this, id, scene, vertexData, false, mesh);
  20453. this._beingRegenerated = false;
  20454. }
  20455. _Primitive.prototype.canBeRegenerated = function () {
  20456. return this._canBeRegenerated;
  20457. };
  20458. _Primitive.prototype.regenerate = function () {
  20459. if (!this._canBeRegenerated) {
  20460. return;
  20461. }
  20462. this._beingRegenerated = true;
  20463. this.setAllVerticesData(this._regenerateVertexData(), false);
  20464. this._beingRegenerated = false;
  20465. };
  20466. _Primitive.prototype.asNewGeometry = function (id) {
  20467. return _super.prototype.copy.call(this, id);
  20468. };
  20469. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  20470. if (!this._beingRegenerated) {
  20471. return;
  20472. }
  20473. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  20474. };
  20475. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  20476. if (!this._beingRegenerated) {
  20477. return;
  20478. }
  20479. _super.prototype.setVerticesData.call(this, kind, data, false);
  20480. };
  20481. _Primitive.prototype._regenerateVertexData = function () {
  20482. throw new Error("Abstract method");
  20483. };
  20484. _Primitive.prototype.copy = function (id) {
  20485. throw new Error("Must be overriden in sub-classes.");
  20486. };
  20487. return _Primitive;
  20488. })(Geometry);
  20489. Primitives._Primitive = _Primitive;
  20490. var Box = (function (_super) {
  20491. __extends(Box, _super);
  20492. function Box(id, scene, size, canBeRegenerated, mesh) {
  20493. this.size = size;
  20494. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20495. }
  20496. Box.prototype._regenerateVertexData = function () {
  20497. return BABYLON.VertexData.CreateBox(this.size);
  20498. };
  20499. Box.prototype.copy = function (id) {
  20500. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  20501. };
  20502. return Box;
  20503. })(_Primitive);
  20504. Primitives.Box = Box;
  20505. var Sphere = (function (_super) {
  20506. __extends(Sphere, _super);
  20507. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  20508. this.segments = segments;
  20509. this.diameter = diameter;
  20510. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20511. }
  20512. Sphere.prototype._regenerateVertexData = function () {
  20513. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  20514. };
  20515. Sphere.prototype.copy = function (id) {
  20516. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  20517. };
  20518. return Sphere;
  20519. })(_Primitive);
  20520. Primitives.Sphere = Sphere;
  20521. var Cylinder = (function (_super) {
  20522. __extends(Cylinder, _super);
  20523. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  20524. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  20525. this.height = height;
  20526. this.diameterTop = diameterTop;
  20527. this.diameterBottom = diameterBottom;
  20528. this.tessellation = tessellation;
  20529. this.subdivisions = subdivisions;
  20530. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20531. }
  20532. Cylinder.prototype._regenerateVertexData = function () {
  20533. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  20534. };
  20535. Cylinder.prototype.copy = function (id) {
  20536. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  20537. };
  20538. return Cylinder;
  20539. })(_Primitive);
  20540. Primitives.Cylinder = Cylinder;
  20541. var Torus = (function (_super) {
  20542. __extends(Torus, _super);
  20543. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  20544. this.diameter = diameter;
  20545. this.thickness = thickness;
  20546. this.tessellation = tessellation;
  20547. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20548. }
  20549. Torus.prototype._regenerateVertexData = function () {
  20550. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  20551. };
  20552. Torus.prototype.copy = function (id) {
  20553. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  20554. };
  20555. return Torus;
  20556. })(_Primitive);
  20557. Primitives.Torus = Torus;
  20558. var Ground = (function (_super) {
  20559. __extends(Ground, _super);
  20560. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  20561. this.width = width;
  20562. this.height = height;
  20563. this.subdivisions = subdivisions;
  20564. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20565. }
  20566. Ground.prototype._regenerateVertexData = function () {
  20567. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  20568. };
  20569. Ground.prototype.copy = function (id) {
  20570. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  20571. };
  20572. return Ground;
  20573. })(_Primitive);
  20574. Primitives.Ground = Ground;
  20575. var TiledGround = (function (_super) {
  20576. __extends(TiledGround, _super);
  20577. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  20578. this.xmin = xmin;
  20579. this.zmin = zmin;
  20580. this.xmax = xmax;
  20581. this.zmax = zmax;
  20582. this.subdivisions = subdivisions;
  20583. this.precision = precision;
  20584. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20585. }
  20586. TiledGround.prototype._regenerateVertexData = function () {
  20587. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  20588. };
  20589. TiledGround.prototype.copy = function (id) {
  20590. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  20591. };
  20592. return TiledGround;
  20593. })(_Primitive);
  20594. Primitives.TiledGround = TiledGround;
  20595. var Plane = (function (_super) {
  20596. __extends(Plane, _super);
  20597. function Plane(id, scene, size, canBeRegenerated, mesh) {
  20598. this.size = size;
  20599. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20600. }
  20601. Plane.prototype._regenerateVertexData = function () {
  20602. return BABYLON.VertexData.CreatePlane(this.size);
  20603. };
  20604. Plane.prototype.copy = function (id) {
  20605. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  20606. };
  20607. return Plane;
  20608. })(_Primitive);
  20609. Primitives.Plane = Plane;
  20610. var TorusKnot = (function (_super) {
  20611. __extends(TorusKnot, _super);
  20612. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  20613. this.radius = radius;
  20614. this.tube = tube;
  20615. this.radialSegments = radialSegments;
  20616. this.tubularSegments = tubularSegments;
  20617. this.p = p;
  20618. this.q = q;
  20619. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20620. }
  20621. TorusKnot.prototype._regenerateVertexData = function () {
  20622. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  20623. };
  20624. TorusKnot.prototype.copy = function (id) {
  20625. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  20626. };
  20627. return TorusKnot;
  20628. })(_Primitive);
  20629. Primitives.TorusKnot = TorusKnot;
  20630. })(Geometry.Primitives || (Geometry.Primitives = {}));
  20631. var Primitives = Geometry.Primitives;
  20632. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  20633. var Geometry = BABYLON.Geometry;
  20634. })(BABYLON || (BABYLON = {}));
  20635. var __extends = this.__extends || function (d, b) {
  20636. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20637. function __() { this.constructor = d; }
  20638. __.prototype = b.prototype;
  20639. d.prototype = new __();
  20640. };
  20641. var BABYLON;
  20642. (function (BABYLON) {
  20643. var Gamepads = (function () {
  20644. function Gamepads(ongamedpadconnected) {
  20645. var _this = this;
  20646. this.babylonGamepads = [];
  20647. this.oneGamepadConnected = false;
  20648. this.isMonitoring = false;
  20649. this.gamepadEventSupported = 'GamepadEvent' in window;
  20650. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  20651. 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=";
  20652. this._callbackGamepadConnected = ongamedpadconnected;
  20653. if (this.gamepadSupportAvailable) {
  20654. if (this.gamepadEventSupported) {
  20655. window.addEventListener('gamepadconnected', function (evt) {
  20656. _this._onGamepadConnected(evt);
  20657. }, false);
  20658. window.addEventListener('gamepaddisconnected', function (evt) {
  20659. _this._onGamepadDisconnected(evt);
  20660. }, false);
  20661. } else {
  20662. this._startMonitoringGamepads();
  20663. }
  20664. if (!this.oneGamepadConnected) {
  20665. this._insertGamepadDOMInstructions();
  20666. }
  20667. } else {
  20668. this._insertGamepadDOMNotSupported();
  20669. }
  20670. }
  20671. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  20672. Gamepads.gamepadDOMInfo = document.createElement("div");
  20673. var buttonAImage = document.createElement("img");
  20674. buttonAImage.src = this.buttonADataURL;
  20675. var spanMessage = document.createElement("span");
  20676. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  20677. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  20678. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  20679. Gamepads.gamepadDOMInfo.style.position = "absolute";
  20680. Gamepads.gamepadDOMInfo.style.width = "100%";
  20681. Gamepads.gamepadDOMInfo.style.height = "48px";
  20682. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  20683. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  20684. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  20685. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  20686. buttonAImage.style.position = "relative";
  20687. buttonAImage.style.bottom = "8px";
  20688. spanMessage.style.position = "relative";
  20689. spanMessage.style.fontSize = "32px";
  20690. spanMessage.style.bottom = "32px";
  20691. spanMessage.style.color = "green";
  20692. document.body.appendChild(Gamepads.gamepadDOMInfo);
  20693. };
  20694. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  20695. Gamepads.gamepadDOMInfo = document.createElement("div");
  20696. var spanMessage = document.createElement("span");
  20697. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  20698. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  20699. Gamepads.gamepadDOMInfo.style.position = "absolute";
  20700. Gamepads.gamepadDOMInfo.style.width = "100%";
  20701. Gamepads.gamepadDOMInfo.style.height = "40px";
  20702. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  20703. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  20704. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  20705. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  20706. spanMessage.style.position = "relative";
  20707. spanMessage.style.fontSize = "32px";
  20708. spanMessage.style.color = "red";
  20709. document.body.appendChild(Gamepads.gamepadDOMInfo);
  20710. };
  20711. Gamepads.prototype.dispose = function () {
  20712. document.body.removeChild(Gamepads.gamepadDOMInfo);
  20713. };
  20714. Gamepads.prototype._onGamepadConnected = function (evt) {
  20715. var newGamepad = this._addNewGamepad(evt.gamepad);
  20716. if (this._callbackGamepadConnected)
  20717. this._callbackGamepadConnected(newGamepad);
  20718. this._startMonitoringGamepads();
  20719. };
  20720. Gamepads.prototype._addNewGamepad = function (gamepad) {
  20721. if (!this.oneGamepadConnected) {
  20722. this.oneGamepadConnected = true;
  20723. if (Gamepads.gamepadDOMInfo) {
  20724. document.body.removeChild(Gamepads.gamepadDOMInfo);
  20725. Gamepads.gamepadDOMInfo = null;
  20726. }
  20727. }
  20728. var newGamepad;
  20729. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  20730. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  20731. } else {
  20732. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  20733. }
  20734. this.babylonGamepads.push(newGamepad);
  20735. return newGamepad;
  20736. };
  20737. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  20738. for (var i in this.babylonGamepads) {
  20739. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  20740. this.babylonGamepads.splice(i, 1);
  20741. break;
  20742. }
  20743. }
  20744. if (this.babylonGamepads.length == 0) {
  20745. this._stopMonitoringGamepads();
  20746. }
  20747. };
  20748. Gamepads.prototype._startMonitoringGamepads = function () {
  20749. if (!this.isMonitoring) {
  20750. this.isMonitoring = true;
  20751. this._checkGamepadsStatus();
  20752. }
  20753. };
  20754. Gamepads.prototype._stopMonitoringGamepads = function () {
  20755. this.isMonitoring = false;
  20756. };
  20757. Gamepads.prototype._checkGamepadsStatus = function () {
  20758. var _this = this;
  20759. this._updateGamepadObjects();
  20760. for (var i in this.babylonGamepads) {
  20761. this.babylonGamepads[i].update();
  20762. }
  20763. if (this.isMonitoring) {
  20764. if (window.requestAnimationFrame) {
  20765. window.requestAnimationFrame(function () {
  20766. _this._checkGamepadsStatus();
  20767. });
  20768. } else if (window.mozRequestAnimationFrame) {
  20769. window.mozRequestAnimationFrame(function () {
  20770. _this._checkGamepadsStatus();
  20771. });
  20772. } else if (window.webkitRequestAnimationFrame) {
  20773. window.webkitRequestAnimationFrame(function () {
  20774. _this._checkGamepadsStatus();
  20775. });
  20776. }
  20777. }
  20778. };
  20779. Gamepads.prototype._updateGamepadObjects = function () {
  20780. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  20781. for (var i = 0; i < gamepads.length; i++) {
  20782. if (gamepads[i]) {
  20783. if (!(gamepads[i].index in this.babylonGamepads)) {
  20784. var newGamepad = this._addNewGamepad(gamepads[i]);
  20785. if (this._callbackGamepadConnected) {
  20786. this._callbackGamepadConnected(newGamepad);
  20787. }
  20788. } else {
  20789. this.babylonGamepads[i].browserGamepad = gamepads[i];
  20790. }
  20791. }
  20792. }
  20793. };
  20794. return Gamepads;
  20795. })();
  20796. BABYLON.Gamepads = Gamepads;
  20797. var StickValues = (function () {
  20798. function StickValues(x, y) {
  20799. this.x = x;
  20800. this.y = y;
  20801. }
  20802. return StickValues;
  20803. })();
  20804. BABYLON.StickValues = StickValues;
  20805. var Gamepad = (function () {
  20806. function Gamepad(id, index, browserGamepad) {
  20807. this.id = id;
  20808. this.index = index;
  20809. this.browserGamepad = browserGamepad;
  20810. if (this.browserGamepad.axes.length >= 2) {
  20811. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  20812. }
  20813. if (this.browserGamepad.axes.length >= 4) {
  20814. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  20815. }
  20816. }
  20817. Gamepad.prototype.onleftstickchanged = function (callback) {
  20818. this._onleftstickchanged = callback;
  20819. };
  20820. Gamepad.prototype.onrightstickchanged = function (callback) {
  20821. this._onrightstickchanged = callback;
  20822. };
  20823. Object.defineProperty(Gamepad.prototype, "leftStick", {
  20824. get: function () {
  20825. return this._leftStick;
  20826. },
  20827. set: function (newValues) {
  20828. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  20829. this._onleftstickchanged(newValues);
  20830. }
  20831. this._leftStick = newValues;
  20832. },
  20833. enumerable: true,
  20834. configurable: true
  20835. });
  20836. Object.defineProperty(Gamepad.prototype, "rightStick", {
  20837. get: function () {
  20838. return this._rightStick;
  20839. },
  20840. set: function (newValues) {
  20841. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  20842. this._onrightstickchanged(newValues);
  20843. }
  20844. this._rightStick = newValues;
  20845. },
  20846. enumerable: true,
  20847. configurable: true
  20848. });
  20849. Gamepad.prototype.update = function () {
  20850. if (this._leftStick) {
  20851. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  20852. }
  20853. if (this._rightStick) {
  20854. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  20855. }
  20856. };
  20857. return Gamepad;
  20858. })();
  20859. BABYLON.Gamepad = Gamepad;
  20860. var GenericPad = (function (_super) {
  20861. __extends(GenericPad, _super);
  20862. function GenericPad(id, index, gamepad) {
  20863. _super.call(this, id, index, gamepad);
  20864. this.id = id;
  20865. this.index = index;
  20866. this.gamepad = gamepad;
  20867. this._buttons = new Array(gamepad.buttons.length);
  20868. }
  20869. GenericPad.prototype.onbuttondown = function (callback) {
  20870. this._onbuttondown = callback;
  20871. };
  20872. GenericPad.prototype.onbuttonup = function (callback) {
  20873. this._onbuttonup = callback;
  20874. };
  20875. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  20876. if (newValue !== currentValue) {
  20877. if (this._onbuttondown && newValue === 1) {
  20878. this._onbuttondown(buttonIndex);
  20879. }
  20880. if (this._onbuttonup && newValue === 0) {
  20881. this._onbuttonup(buttonIndex);
  20882. }
  20883. }
  20884. return newValue;
  20885. };
  20886. GenericPad.prototype.update = function () {
  20887. _super.prototype.update.call(this);
  20888. for (var index = 0; index < this._buttons.length; index++) {
  20889. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  20890. }
  20891. };
  20892. return GenericPad;
  20893. })(Gamepad);
  20894. BABYLON.GenericPad = GenericPad;
  20895. (function (Xbox360Button) {
  20896. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  20897. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  20898. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  20899. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  20900. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  20901. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  20902. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  20903. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  20904. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  20905. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  20906. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  20907. var Xbox360Button = BABYLON.Xbox360Button;
  20908. (function (Xbox360Dpad) {
  20909. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  20910. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  20911. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  20912. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  20913. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  20914. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  20915. var Xbox360Pad = (function (_super) {
  20916. __extends(Xbox360Pad, _super);
  20917. function Xbox360Pad() {
  20918. _super.apply(this, arguments);
  20919. this._leftTrigger = 0;
  20920. this._rightTrigger = 0;
  20921. this._buttonA = 0;
  20922. this._buttonB = 0;
  20923. this._buttonX = 0;
  20924. this._buttonY = 0;
  20925. this._buttonBack = 0;
  20926. this._buttonStart = 0;
  20927. this._buttonLB = 0;
  20928. this._buttonRB = 0;
  20929. this._buttonLeftStick = 0;
  20930. this._buttonRightStick = 0;
  20931. this._dPadUp = 0;
  20932. this._dPadDown = 0;
  20933. this._dPadLeft = 0;
  20934. this._dPadRight = 0;
  20935. }
  20936. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  20937. this._onlefttriggerchanged = callback;
  20938. };
  20939. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  20940. this._onrighttriggerchanged = callback;
  20941. };
  20942. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  20943. get: function () {
  20944. return this._leftTrigger;
  20945. },
  20946. set: function (newValue) {
  20947. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  20948. this._onlefttriggerchanged(newValue);
  20949. }
  20950. this._leftTrigger = newValue;
  20951. },
  20952. enumerable: true,
  20953. configurable: true
  20954. });
  20955. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  20956. get: function () {
  20957. return this._rightTrigger;
  20958. },
  20959. set: function (newValue) {
  20960. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  20961. this._onrighttriggerchanged(newValue);
  20962. }
  20963. this._rightTrigger = newValue;
  20964. },
  20965. enumerable: true,
  20966. configurable: true
  20967. });
  20968. Xbox360Pad.prototype.onbuttondown = function (callback) {
  20969. this._onbuttondown = callback;
  20970. };
  20971. Xbox360Pad.prototype.onbuttonup = function (callback) {
  20972. this._onbuttonup = callback;
  20973. };
  20974. Xbox360Pad.prototype.ondpaddown = function (callback) {
  20975. this._ondpaddown = callback;
  20976. };
  20977. Xbox360Pad.prototype.ondpadup = function (callback) {
  20978. this._ondpadup = callback;
  20979. };
  20980. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  20981. if (newValue !== currentValue) {
  20982. if (this._onbuttondown && newValue === 1) {
  20983. this._onbuttondown(buttonType);
  20984. }
  20985. if (this._onbuttonup && newValue === 0) {
  20986. this._onbuttonup(buttonType);
  20987. }
  20988. }
  20989. return newValue;
  20990. };
  20991. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  20992. if (newValue !== currentValue) {
  20993. if (this._ondpaddown && newValue === 1) {
  20994. this._ondpaddown(buttonType);
  20995. }
  20996. if (this._ondpadup && newValue === 0) {
  20997. this._ondpadup(buttonType);
  20998. }
  20999. }
  21000. return newValue;
  21001. };
  21002. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  21003. get: function () {
  21004. return this._buttonA;
  21005. },
  21006. set: function (value) {
  21007. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  21008. },
  21009. enumerable: true,
  21010. configurable: true
  21011. });
  21012. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  21013. get: function () {
  21014. return this._buttonB;
  21015. },
  21016. set: function (value) {
  21017. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  21018. },
  21019. enumerable: true,
  21020. configurable: true
  21021. });
  21022. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  21023. get: function () {
  21024. return this._buttonX;
  21025. },
  21026. set: function (value) {
  21027. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  21028. },
  21029. enumerable: true,
  21030. configurable: true
  21031. });
  21032. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  21033. get: function () {
  21034. return this._buttonY;
  21035. },
  21036. set: function (value) {
  21037. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  21038. },
  21039. enumerable: true,
  21040. configurable: true
  21041. });
  21042. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  21043. get: function () {
  21044. return this._buttonStart;
  21045. },
  21046. set: function (value) {
  21047. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  21048. },
  21049. enumerable: true,
  21050. configurable: true
  21051. });
  21052. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  21053. get: function () {
  21054. return this._buttonBack;
  21055. },
  21056. set: function (value) {
  21057. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  21058. },
  21059. enumerable: true,
  21060. configurable: true
  21061. });
  21062. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  21063. get: function () {
  21064. return this._buttonLB;
  21065. },
  21066. set: function (value) {
  21067. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  21068. },
  21069. enumerable: true,
  21070. configurable: true
  21071. });
  21072. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  21073. get: function () {
  21074. return this._buttonRB;
  21075. },
  21076. set: function (value) {
  21077. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  21078. },
  21079. enumerable: true,
  21080. configurable: true
  21081. });
  21082. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  21083. get: function () {
  21084. return this._buttonLeftStick;
  21085. },
  21086. set: function (value) {
  21087. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  21088. },
  21089. enumerable: true,
  21090. configurable: true
  21091. });
  21092. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  21093. get: function () {
  21094. return this._buttonRightStick;
  21095. },
  21096. set: function (value) {
  21097. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  21098. },
  21099. enumerable: true,
  21100. configurable: true
  21101. });
  21102. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  21103. get: function () {
  21104. return this._dPadUp;
  21105. },
  21106. set: function (value) {
  21107. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  21108. },
  21109. enumerable: true,
  21110. configurable: true
  21111. });
  21112. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  21113. get: function () {
  21114. return this._dPadDown;
  21115. },
  21116. set: function (value) {
  21117. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  21118. },
  21119. enumerable: true,
  21120. configurable: true
  21121. });
  21122. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  21123. get: function () {
  21124. return this._dPadLeft;
  21125. },
  21126. set: function (value) {
  21127. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  21128. },
  21129. enumerable: true,
  21130. configurable: true
  21131. });
  21132. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  21133. get: function () {
  21134. return this._dPadRight;
  21135. },
  21136. set: function (value) {
  21137. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  21138. },
  21139. enumerable: true,
  21140. configurable: true
  21141. });
  21142. Xbox360Pad.prototype.update = function () {
  21143. _super.prototype.update.call(this);
  21144. this.buttonA = this.browserGamepad.buttons[0].value;
  21145. this.buttonB = this.browserGamepad.buttons[1].value;
  21146. this.buttonX = this.browserGamepad.buttons[2].value;
  21147. this.buttonY = this.browserGamepad.buttons[3].value;
  21148. this.buttonLB = this.browserGamepad.buttons[4].value;
  21149. this.buttonRB = this.browserGamepad.buttons[5].value;
  21150. this.leftTrigger = this.browserGamepad.buttons[6].value;
  21151. this.rightTrigger = this.browserGamepad.buttons[7].value;
  21152. this.buttonBack = this.browserGamepad.buttons[8].value;
  21153. this.buttonStart = this.browserGamepad.buttons[9].value;
  21154. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  21155. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  21156. this.dPadUp = this.browserGamepad.buttons[12].value;
  21157. this.dPadDown = this.browserGamepad.buttons[13].value;
  21158. this.dPadLeft = this.browserGamepad.buttons[14].value;
  21159. this.dPadRight = this.browserGamepad.buttons[15].value;
  21160. };
  21161. return Xbox360Pad;
  21162. })(Gamepad);
  21163. BABYLON.Xbox360Pad = Xbox360Pad;
  21164. })(BABYLON || (BABYLON = {}));
  21165. var __extends = this.__extends || function (d, b) {
  21166. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21167. function __() { this.constructor = d; }
  21168. __.prototype = b.prototype;
  21169. d.prototype = new __();
  21170. };
  21171. var BABYLON;
  21172. (function (BABYLON) {
  21173. var GamepadCamera = (function (_super) {
  21174. __extends(GamepadCamera, _super);
  21175. function GamepadCamera(name, position, scene) {
  21176. var _this = this;
  21177. _super.call(this, name, position, scene);
  21178. this.angularSensibility = 200;
  21179. this.moveSensibility = 75;
  21180. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21181. _this._onNewGameConnected(gamepad);
  21182. });
  21183. }
  21184. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21185. if (gamepad.index === 0) {
  21186. this._gamepad = gamepad;
  21187. }
  21188. };
  21189. GamepadCamera.prototype._checkInputs = function () {
  21190. if (!this._gamepad) {
  21191. return;
  21192. }
  21193. var LSValues = this._gamepad.leftStick;
  21194. var normalizedLX = LSValues.x / this.moveSensibility;
  21195. var normalizedLY = LSValues.y / this.moveSensibility;
  21196. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  21197. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  21198. var RSValues = this._gamepad.rightStick;
  21199. var normalizedRX = RSValues.x / this.angularSensibility;
  21200. var normalizedRY = RSValues.y / this.angularSensibility;
  21201. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  21202. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  21203. ;
  21204. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21205. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  21206. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21207. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  21208. };
  21209. GamepadCamera.prototype.dispose = function () {
  21210. this._gamepads.dispose();
  21211. _super.prototype.dispose.call(this);
  21212. };
  21213. return GamepadCamera;
  21214. })(BABYLON.FreeCamera);
  21215. BABYLON.GamepadCamera = GamepadCamera;
  21216. })(BABYLON || (BABYLON = {}));
  21217. var __extends = this.__extends || function (d, b) {
  21218. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21219. function __() { this.constructor = d; }
  21220. __.prototype = b.prototype;
  21221. d.prototype = new __();
  21222. };
  21223. var BABYLON;
  21224. (function (BABYLON) {
  21225. var LinesMesh = (function (_super) {
  21226. __extends(LinesMesh, _super);
  21227. function LinesMesh(name, scene, updatable) {
  21228. if (typeof updatable === "undefined") { updatable = false; }
  21229. _super.call(this, name, scene);
  21230. this.color = new BABYLON.Color3(1, 1, 1);
  21231. this.alpha = 1;
  21232. this._indices = new Array();
  21233. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  21234. attributes: ["position"],
  21235. uniforms: ["worldViewProjection", "color"],
  21236. needAlphaBlending: true
  21237. });
  21238. }
  21239. Object.defineProperty(LinesMesh.prototype, "material", {
  21240. get: function () {
  21241. return this._colorShader;
  21242. },
  21243. enumerable: true,
  21244. configurable: true
  21245. });
  21246. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  21247. get: function () {
  21248. return false;
  21249. },
  21250. enumerable: true,
  21251. configurable: true
  21252. });
  21253. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  21254. get: function () {
  21255. return false;
  21256. },
  21257. enumerable: true,
  21258. configurable: true
  21259. });
  21260. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  21261. var engine = this.getScene().getEngine();
  21262. var indexToBind = this._geometry.getIndexBuffer();
  21263. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  21264. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  21265. };
  21266. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21267. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21268. return;
  21269. }
  21270. var engine = this.getScene().getEngine();
  21271. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  21272. };
  21273. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  21274. return null;
  21275. };
  21276. LinesMesh.prototype.dispose = function (doNotRecurse) {
  21277. this._colorShader.dispose();
  21278. _super.prototype.dispose.call(this, doNotRecurse);
  21279. };
  21280. return LinesMesh;
  21281. })(BABYLON.Mesh);
  21282. BABYLON.LinesMesh = LinesMesh;
  21283. })(BABYLON || (BABYLON = {}));
  21284. var BABYLON;
  21285. (function (BABYLON) {
  21286. var OutlineRenderer = (function () {
  21287. function OutlineRenderer(scene) {
  21288. this._scene = scene;
  21289. }
  21290. OutlineRenderer.prototype.render = function (subMesh, batch) {
  21291. var scene = this._scene;
  21292. var engine = this._scene.getEngine();
  21293. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  21294. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  21295. return;
  21296. }
  21297. var mesh = subMesh.getRenderingMesh();
  21298. var material = subMesh.getMaterial();
  21299. engine.enableEffect(this._effect);
  21300. this._effect.setFloat("offset", mesh.outlineWidth);
  21301. this._effect.setColor3("color", mesh.outlineColor);
  21302. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  21303. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  21304. if (useBones) {
  21305. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  21306. }
  21307. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  21308. if (material && material.needAlphaTesting()) {
  21309. var alphaTexture = material.getAlphaTestTexture();
  21310. this._effect.setTexture("diffuseSampler", alphaTexture);
  21311. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  21312. }
  21313. if (hardwareInstancedRendering) {
  21314. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  21315. } else {
  21316. if (batch.renderSelf[subMesh._id]) {
  21317. this._effect.setMatrix("world", mesh.getWorldMatrix());
  21318. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  21319. }
  21320. if (batch.visibleInstances[subMesh._id]) {
  21321. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  21322. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  21323. this._effect.setMatrix("world", instance.getWorldMatrix());
  21324. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  21325. }
  21326. }
  21327. }
  21328. };
  21329. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  21330. var defines = [];
  21331. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  21332. var mesh = subMesh.getMesh();
  21333. var material = subMesh.getMaterial();
  21334. if (material && material.needAlphaTesting()) {
  21335. defines.push("#define ALPHATEST");
  21336. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21337. attribs.push(BABYLON.VertexBuffer.UVKind);
  21338. defines.push("#define UV1");
  21339. }
  21340. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  21341. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  21342. defines.push("#define UV2");
  21343. }
  21344. }
  21345. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21346. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21347. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21348. defines.push("#define BONES");
  21349. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  21350. }
  21351. if (useInstances) {
  21352. defines.push("#define INSTANCES");
  21353. attribs.push("world0");
  21354. attribs.push("world1");
  21355. attribs.push("world2");
  21356. attribs.push("world3");
  21357. }
  21358. var join = defines.join("\n");
  21359. if (this._cachedDefines != join) {
  21360. this._cachedDefines = join;
  21361. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  21362. }
  21363. return this._effect.isReady();
  21364. };
  21365. return OutlineRenderer;
  21366. })();
  21367. BABYLON.OutlineRenderer = OutlineRenderer;
  21368. })(BABYLON || (BABYLON = {}));
  21369. var BABYLON;
  21370. (function (BABYLON) {
  21371. var MeshAssetTask = (function () {
  21372. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  21373. this.name = name;
  21374. this.meshesNames = meshesNames;
  21375. this.rootUrl = rootUrl;
  21376. this.sceneFilename = sceneFilename;
  21377. this.isCompleted = false;
  21378. }
  21379. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21380. var _this = this;
  21381. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  21382. _this.loadedMeshes = meshes;
  21383. _this.loadedParticleSystems = particleSystems;
  21384. _this.loadedSkeletons = skeletons;
  21385. _this.isCompleted = true;
  21386. if (_this.onSuccess) {
  21387. _this.onSuccess(_this);
  21388. }
  21389. onSuccess();
  21390. }, null, function () {
  21391. if (_this.onError) {
  21392. _this.onError(_this);
  21393. }
  21394. onError();
  21395. });
  21396. };
  21397. return MeshAssetTask;
  21398. })();
  21399. BABYLON.MeshAssetTask = MeshAssetTask;
  21400. var TextFileAssetTask = (function () {
  21401. function TextFileAssetTask(name, url) {
  21402. this.name = name;
  21403. this.url = url;
  21404. this.isCompleted = false;
  21405. }
  21406. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21407. var _this = this;
  21408. BABYLON.Tools.LoadFile(this.url, function (data) {
  21409. _this.text = data;
  21410. _this.isCompleted = true;
  21411. if (_this.onSuccess) {
  21412. _this.onSuccess(_this);
  21413. }
  21414. onSuccess();
  21415. }, null, scene.database, false, function () {
  21416. if (_this.onError) {
  21417. _this.onError(_this);
  21418. }
  21419. onError();
  21420. });
  21421. };
  21422. return TextFileAssetTask;
  21423. })();
  21424. BABYLON.TextFileAssetTask = TextFileAssetTask;
  21425. var BinaryFileAssetTask = (function () {
  21426. function BinaryFileAssetTask(name, url) {
  21427. this.name = name;
  21428. this.url = url;
  21429. this.isCompleted = false;
  21430. }
  21431. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21432. var _this = this;
  21433. BABYLON.Tools.LoadFile(this.url, function (data) {
  21434. _this.data = data;
  21435. _this.isCompleted = true;
  21436. if (_this.onSuccess) {
  21437. _this.onSuccess(_this);
  21438. }
  21439. onSuccess();
  21440. }, null, scene.database, true, function () {
  21441. if (_this.onError) {
  21442. _this.onError(_this);
  21443. }
  21444. onError();
  21445. });
  21446. };
  21447. return BinaryFileAssetTask;
  21448. })();
  21449. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  21450. var ImageAssetTask = (function () {
  21451. function ImageAssetTask(name, url) {
  21452. this.name = name;
  21453. this.url = url;
  21454. this.isCompleted = false;
  21455. }
  21456. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21457. var _this = this;
  21458. var img = new Image();
  21459. img.onload = function () {
  21460. _this.image = img;
  21461. _this.isCompleted = true;
  21462. if (_this.onSuccess) {
  21463. _this.onSuccess(_this);
  21464. }
  21465. onSuccess();
  21466. };
  21467. img.onerror = function () {
  21468. if (_this.onError) {
  21469. _this.onError(_this);
  21470. }
  21471. onError();
  21472. };
  21473. img.src = this.url;
  21474. };
  21475. return ImageAssetTask;
  21476. })();
  21477. BABYLON.ImageAssetTask = ImageAssetTask;
  21478. var TextureAssetTask = (function () {
  21479. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  21480. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21481. this.name = name;
  21482. this.url = url;
  21483. this.noMipmap = noMipmap;
  21484. this.invertY = invertY;
  21485. this.samplingMode = samplingMode;
  21486. this.isCompleted = false;
  21487. }
  21488. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21489. var _this = this;
  21490. var onload = function () {
  21491. _this.isCompleted = true;
  21492. if (_this.onSuccess) {
  21493. _this.onSuccess(_this);
  21494. }
  21495. onSuccess();
  21496. };
  21497. var onerror = function () {
  21498. if (_this.onError) {
  21499. _this.onError(_this);
  21500. }
  21501. onError();
  21502. };
  21503. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  21504. };
  21505. return TextureAssetTask;
  21506. })();
  21507. BABYLON.TextureAssetTask = TextureAssetTask;
  21508. var AssetsManager = (function () {
  21509. function AssetsManager(scene) {
  21510. this._tasks = new Array();
  21511. this._waitingTasksCount = 0;
  21512. this.useDefaultLoadingScreen = true;
  21513. this._scene = scene;
  21514. }
  21515. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  21516. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  21517. this._tasks.push(task);
  21518. return task;
  21519. };
  21520. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  21521. var task = new TextFileAssetTask(taskName, url);
  21522. this._tasks.push(task);
  21523. return task;
  21524. };
  21525. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  21526. var task = new BinaryFileAssetTask(taskName, url);
  21527. this._tasks.push(task);
  21528. return task;
  21529. };
  21530. AssetsManager.prototype.addImageTask = function (taskName, url) {
  21531. var task = new ImageAssetTask(taskName, url);
  21532. this._tasks.push(task);
  21533. return task;
  21534. };
  21535. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  21536. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21537. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  21538. this._tasks.push(task);
  21539. return task;
  21540. };
  21541. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  21542. this._waitingTasksCount--;
  21543. if (this._waitingTasksCount === 0) {
  21544. if (this.onFinish) {
  21545. this.onFinish(this._tasks);
  21546. }
  21547. this._scene.getEngine().hideLoadingUI();
  21548. }
  21549. };
  21550. AssetsManager.prototype._runTask = function (task) {
  21551. var _this = this;
  21552. task.run(this._scene, function () {
  21553. if (_this.onTaskSuccess) {
  21554. _this.onTaskSuccess(task);
  21555. }
  21556. _this._decreaseWaitingTasksCount();
  21557. }, function () {
  21558. if (_this.onTaskError) {
  21559. _this.onTaskError(task);
  21560. }
  21561. _this._decreaseWaitingTasksCount();
  21562. });
  21563. };
  21564. AssetsManager.prototype.reset = function () {
  21565. this._tasks = new Array();
  21566. return this;
  21567. };
  21568. AssetsManager.prototype.load = function () {
  21569. this._waitingTasksCount = this._tasks.length;
  21570. if (this._waitingTasksCount === 0) {
  21571. if (this.onFinish) {
  21572. this.onFinish(this._tasks);
  21573. }
  21574. return this;
  21575. }
  21576. if (this.useDefaultLoadingScreen) {
  21577. this._scene.getEngine().displayLoadingUI();
  21578. }
  21579. for (var index = 0; index < this._tasks.length; index++) {
  21580. var task = this._tasks[index];
  21581. this._runTask(task);
  21582. }
  21583. return this;
  21584. };
  21585. return AssetsManager;
  21586. })();
  21587. BABYLON.AssetsManager = AssetsManager;
  21588. })(BABYLON || (BABYLON = {}));
  21589. var __extends = this.__extends || function (d, b) {
  21590. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21591. function __() { this.constructor = d; }
  21592. __.prototype = b.prototype;
  21593. d.prototype = new __();
  21594. };
  21595. var BABYLON;
  21596. (function (BABYLON) {
  21597. var VRDeviceOrientationCamera = (function (_super) {
  21598. __extends(VRDeviceOrientationCamera, _super);
  21599. function VRDeviceOrientationCamera(name, position, scene) {
  21600. _super.call(this, name, position, scene);
  21601. this._alpha = 0;
  21602. this._beta = 0;
  21603. this._gamma = 0;
  21604. }
  21605. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  21606. this._alpha = +evt.alpha | 0;
  21607. this._beta = +evt.beta | 0;
  21608. this._gamma = +evt.gamma | 0;
  21609. if (this._gamma < 0) {
  21610. this._gamma = 90 + this._gamma;
  21611. } else {
  21612. this._gamma = 270 - this._gamma;
  21613. }
  21614. this.rotation.x = this._gamma / 180.0 * Math.PI;
  21615. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  21616. this.rotation.z = this._beta / 180.0 * Math.PI;
  21617. };
  21618. return VRDeviceOrientationCamera;
  21619. })(BABYLON.OculusCamera);
  21620. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  21621. })(BABYLON || (BABYLON = {}));
  21622. var __extends = this.__extends || function (d, b) {
  21623. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21624. function __() { this.constructor = d; }
  21625. __.prototype = b.prototype;
  21626. d.prototype = new __();
  21627. };
  21628. var BABYLON;
  21629. (function (BABYLON) {
  21630. var WebVRCamera = (function (_super) {
  21631. __extends(WebVRCamera, _super);
  21632. function WebVRCamera(name, position, scene) {
  21633. _super.call(this, name, position, scene);
  21634. this._hmdDevice = null;
  21635. this._sensorDevice = null;
  21636. this._cacheState = null;
  21637. this._cacheQuaternion = new BABYLON.Quaternion();
  21638. this._cacheRotation = BABYLON.Vector3.Zero();
  21639. this._vrEnabled = false;
  21640. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  21641. }
  21642. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  21643. var size = devices.length;
  21644. var i = 0;
  21645. this._sensorDevice = null;
  21646. this._hmdDevice = null;
  21647. while (i < size && this._hmdDevice === null) {
  21648. if (devices[i] instanceof HMDVRDevice) {
  21649. this._hmdDevice = devices[i];
  21650. }
  21651. i++;
  21652. }
  21653. i = 0;
  21654. while (i < size && this._sensorDevice === null) {
  21655. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  21656. this._sensorDevice = devices[i];
  21657. }
  21658. i++;
  21659. }
  21660. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  21661. };
  21662. WebVRCamera.prototype._update = function () {
  21663. if (this._vrEnabled) {
  21664. this._cacheState = this._sensorDevice.getState();
  21665. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  21666. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  21667. this.rotation.x = -this._cacheRotation.z;
  21668. this.rotation.y = -this._cacheRotation.y;
  21669. this.rotation.z = this._cacheRotation.x;
  21670. }
  21671. _super.prototype._update.call(this);
  21672. };
  21673. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  21674. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21675. if (navigator.getVRDevices) {
  21676. navigator.getVRDevices().then(this._getWebVRDevices);
  21677. } else if (navigator.mozGetVRDevices) {
  21678. navigator.mozGetVRDevices(this._getWebVRDevices);
  21679. }
  21680. };
  21681. WebVRCamera.prototype.detachControl = function (element) {
  21682. _super.prototype.detachControl.call(this, element);
  21683. this._vrEnabled = false;
  21684. };
  21685. return WebVRCamera;
  21686. })(BABYLON.OculusCamera);
  21687. BABYLON.WebVRCamera = WebVRCamera;
  21688. })(BABYLON || (BABYLON = {}));
  21689. var __extends = this.__extends || function (d, b) {
  21690. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21691. function __() { this.constructor = d; }
  21692. __.prototype = b.prototype;
  21693. d.prototype = new __();
  21694. };
  21695. var BABYLON;
  21696. (function (BABYLON) {
  21697. var SceneOptimization = (function () {
  21698. function SceneOptimization(priority) {
  21699. if (typeof priority === "undefined") { priority = 0; }
  21700. this.priority = priority;
  21701. this.apply = function (scene) {
  21702. return true;
  21703. };
  21704. }
  21705. return SceneOptimization;
  21706. })();
  21707. BABYLON.SceneOptimization = SceneOptimization;
  21708. var TextureOptimization = (function (_super) {
  21709. __extends(TextureOptimization, _super);
  21710. function TextureOptimization(priority, maximumSize) {
  21711. if (typeof priority === "undefined") { priority = 0; }
  21712. if (typeof maximumSize === "undefined") { maximumSize = 1024; }
  21713. var _this = this;
  21714. _super.call(this, priority);
  21715. this.priority = priority;
  21716. this.maximumSize = maximumSize;
  21717. this.apply = function (scene) {
  21718. var allDone = true;
  21719. for (var index = 0; index < scene.textures.length; index++) {
  21720. var texture = scene.textures[index];
  21721. if (!texture.canRescale) {
  21722. continue;
  21723. }
  21724. var currentSize = texture.getSize();
  21725. var maxDimension = Math.max(currentSize.width, currentSize.height);
  21726. if (maxDimension > _this.maximumSize) {
  21727. texture.scale(0.5);
  21728. allDone = false;
  21729. }
  21730. }
  21731. return allDone;
  21732. };
  21733. }
  21734. return TextureOptimization;
  21735. })(SceneOptimization);
  21736. BABYLON.TextureOptimization = TextureOptimization;
  21737. var HardwareScalingOptimization = (function (_super) {
  21738. __extends(HardwareScalingOptimization, _super);
  21739. function HardwareScalingOptimization(priority, maximumScale) {
  21740. if (typeof priority === "undefined") { priority = 0; }
  21741. if (typeof maximumScale === "undefined") { maximumScale = 2; }
  21742. var _this = this;
  21743. _super.call(this, priority);
  21744. this.priority = priority;
  21745. this.maximumScale = maximumScale;
  21746. this._currentScale = 1;
  21747. this.apply = function (scene) {
  21748. _this._currentScale++;
  21749. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  21750. return _this._currentScale >= _this.maximumScale;
  21751. };
  21752. }
  21753. return HardwareScalingOptimization;
  21754. })(SceneOptimization);
  21755. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  21756. var ShadowsOptimization = (function (_super) {
  21757. __extends(ShadowsOptimization, _super);
  21758. function ShadowsOptimization() {
  21759. _super.apply(this, arguments);
  21760. this.apply = function (scene) {
  21761. scene.shadowsEnabled = false;
  21762. return true;
  21763. };
  21764. }
  21765. return ShadowsOptimization;
  21766. })(SceneOptimization);
  21767. BABYLON.ShadowsOptimization = ShadowsOptimization;
  21768. var PostProcessesOptimization = (function (_super) {
  21769. __extends(PostProcessesOptimization, _super);
  21770. function PostProcessesOptimization() {
  21771. _super.apply(this, arguments);
  21772. this.apply = function (scene) {
  21773. scene.postProcessesEnabled = false;
  21774. return true;
  21775. };
  21776. }
  21777. return PostProcessesOptimization;
  21778. })(SceneOptimization);
  21779. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  21780. var LensFlaresOptimization = (function (_super) {
  21781. __extends(LensFlaresOptimization, _super);
  21782. function LensFlaresOptimization() {
  21783. _super.apply(this, arguments);
  21784. this.apply = function (scene) {
  21785. scene.lensFlaresEnabled = false;
  21786. return true;
  21787. };
  21788. }
  21789. return LensFlaresOptimization;
  21790. })(SceneOptimization);
  21791. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  21792. var ParticlesOptimization = (function (_super) {
  21793. __extends(ParticlesOptimization, _super);
  21794. function ParticlesOptimization() {
  21795. _super.apply(this, arguments);
  21796. this.apply = function (scene) {
  21797. scene.particlesEnabled = false;
  21798. return true;
  21799. };
  21800. }
  21801. return ParticlesOptimization;
  21802. })(SceneOptimization);
  21803. BABYLON.ParticlesOptimization = ParticlesOptimization;
  21804. var RenderTargetsOptimization = (function (_super) {
  21805. __extends(RenderTargetsOptimization, _super);
  21806. function RenderTargetsOptimization() {
  21807. _super.apply(this, arguments);
  21808. this.apply = function (scene) {
  21809. scene.renderTargetsEnabled = false;
  21810. return true;
  21811. };
  21812. }
  21813. return RenderTargetsOptimization;
  21814. })(SceneOptimization);
  21815. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  21816. var SceneOptimizerOptions = (function () {
  21817. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  21818. if (typeof targetFrameRate === "undefined") { targetFrameRate = 60; }
  21819. if (typeof trackerDuration === "undefined") { trackerDuration = 2000; }
  21820. this.targetFrameRate = targetFrameRate;
  21821. this.trackerDuration = trackerDuration;
  21822. this.optimizations = new Array();
  21823. }
  21824. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  21825. var result = new SceneOptimizerOptions(targetFrameRate);
  21826. var priority = 0;
  21827. result.optimizations.push(new ShadowsOptimization(priority));
  21828. result.optimizations.push(new LensFlaresOptimization(priority));
  21829. priority++;
  21830. result.optimizations.push(new PostProcessesOptimization(priority));
  21831. result.optimizations.push(new ParticlesOptimization(priority));
  21832. priority++;
  21833. result.optimizations.push(new TextureOptimization(priority, 1024));
  21834. return result;
  21835. };
  21836. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  21837. var result = new SceneOptimizerOptions(targetFrameRate);
  21838. var priority = 0;
  21839. result.optimizations.push(new ShadowsOptimization(priority));
  21840. result.optimizations.push(new LensFlaresOptimization(priority));
  21841. priority++;
  21842. result.optimizations.push(new PostProcessesOptimization(priority));
  21843. result.optimizations.push(new ParticlesOptimization(priority));
  21844. priority++;
  21845. result.optimizations.push(new TextureOptimization(priority, 512));
  21846. priority++;
  21847. result.optimizations.push(new RenderTargetsOptimization(priority));
  21848. priority++;
  21849. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  21850. return result;
  21851. };
  21852. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  21853. var result = new SceneOptimizerOptions(targetFrameRate);
  21854. var priority = 0;
  21855. result.optimizations.push(new ShadowsOptimization(priority));
  21856. result.optimizations.push(new LensFlaresOptimization(priority));
  21857. priority++;
  21858. result.optimizations.push(new PostProcessesOptimization(priority));
  21859. result.optimizations.push(new ParticlesOptimization(priority));
  21860. priority++;
  21861. result.optimizations.push(new TextureOptimization(priority, 256));
  21862. priority++;
  21863. result.optimizations.push(new RenderTargetsOptimization(priority));
  21864. priority++;
  21865. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  21866. return result;
  21867. };
  21868. return SceneOptimizerOptions;
  21869. })();
  21870. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  21871. var SceneOptimizer = (function () {
  21872. function SceneOptimizer() {
  21873. }
  21874. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  21875. if (BABYLON.Tools.GetFps() >= options.targetFrameRate) {
  21876. if (onSuccess) {
  21877. onSuccess();
  21878. }
  21879. return;
  21880. }
  21881. var allDone = true;
  21882. var noOptimizationApplied = true;
  21883. for (var index = 0; index < options.optimizations.length; index++) {
  21884. var optimization = options.optimizations[index];
  21885. if (optimization.priority === currentPriorityLevel) {
  21886. noOptimizationApplied = false;
  21887. allDone = allDone && optimization.apply(scene);
  21888. }
  21889. }
  21890. if (noOptimizationApplied) {
  21891. if (onFailure) {
  21892. onFailure();
  21893. }
  21894. return;
  21895. }
  21896. if (allDone) {
  21897. currentPriorityLevel++;
  21898. }
  21899. scene.executeWhenReady(function () {
  21900. setTimeout(function () {
  21901. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  21902. }, options.trackerDuration);
  21903. });
  21904. };
  21905. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  21906. if (!options) {
  21907. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  21908. }
  21909. scene.executeWhenReady(function () {
  21910. setTimeout(function () {
  21911. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  21912. }, options.trackerDuration);
  21913. });
  21914. };
  21915. return SceneOptimizer;
  21916. })();
  21917. BABYLON.SceneOptimizer = SceneOptimizer;
  21918. })(BABYLON || (BABYLON = {}));
  21919. var BABYLON;
  21920. (function (BABYLON) {
  21921. (function (Internals) {
  21922. var MeshLODLevel = (function () {
  21923. function MeshLODLevel(distance, mesh) {
  21924. this.distance = distance;
  21925. this.mesh = mesh;
  21926. }
  21927. return MeshLODLevel;
  21928. })();
  21929. Internals.MeshLODLevel = MeshLODLevel;
  21930. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21931. var Internals = BABYLON.Internals;
  21932. })(BABYLON || (BABYLON = {}));