babylon.2.0-alpha.debug.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var Color3 = (function () {
  4. function Color3(r, g, b) {
  5. if (typeof r === "undefined") { r = 0; }
  6. if (typeof g === "undefined") { g = 0; }
  7. if (typeof b === "undefined") { b = 0; }
  8. this.r = r;
  9. this.g = g;
  10. this.b = b;
  11. }
  12. Color3.prototype.toString = function () {
  13. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  14. };
  15. Color3.prototype.toArray = function (array, index) {
  16. if (index === undefined) {
  17. index = 0;
  18. }
  19. array[index] = this.r;
  20. array[index + 1] = this.g;
  21. array[index + 2] = this.b;
  22. };
  23. Color3.prototype.toColor4 = function (alpha) {
  24. if (typeof alpha === "undefined") { alpha = 1; }
  25. return new Color4(this.r, this.g, this.b, alpha);
  26. };
  27. Color3.prototype.asArray = function () {
  28. var result = [];
  29. this.toArray(result, 0);
  30. return result;
  31. };
  32. Color3.prototype.toLuminance = function () {
  33. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  34. };
  35. Color3.prototype.multiply = function (otherColor) {
  36. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  37. };
  38. Color3.prototype.multiplyToRef = function (otherColor, result) {
  39. result.r = this.r * otherColor.r;
  40. result.g = this.g * otherColor.g;
  41. result.b = this.b * otherColor.b;
  42. };
  43. Color3.prototype.equals = function (otherColor) {
  44. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  45. };
  46. Color3.prototype.scale = function (scale) {
  47. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  48. };
  49. Color3.prototype.scaleToRef = function (scale, result) {
  50. result.r = this.r * scale;
  51. result.g = this.g * scale;
  52. result.b = this.b * scale;
  53. };
  54. Color3.prototype.add = function (otherColor) {
  55. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  56. };
  57. Color3.prototype.addToRef = function (otherColor, result) {
  58. result.r = this.r + otherColor.r;
  59. result.g = this.g + otherColor.g;
  60. result.b = this.b + otherColor.b;
  61. };
  62. Color3.prototype.subtract = function (otherColor) {
  63. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  64. };
  65. Color3.prototype.subtractToRef = function (otherColor, result) {
  66. result.r = this.r - otherColor.r;
  67. result.g = this.g - otherColor.g;
  68. result.b = this.b - otherColor.b;
  69. };
  70. Color3.prototype.clone = function () {
  71. return new Color3(this.r, this.g, this.b);
  72. };
  73. Color3.prototype.copyFrom = function (source) {
  74. this.r = source.r;
  75. this.g = source.g;
  76. this.b = source.b;
  77. };
  78. Color3.prototype.copyFromFloats = function (r, g, b) {
  79. this.r = r;
  80. this.g = g;
  81. this.b = b;
  82. };
  83. Color3.FromArray = function (array) {
  84. return new Color3(array[0], array[1], array[2]);
  85. };
  86. Color3.FromInts = function (r, g, b) {
  87. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  88. };
  89. Color3.Lerp = function (start, end, amount) {
  90. var r = start.r + ((end.r - start.r) * amount);
  91. var g = start.g + ((end.g - start.g) * amount);
  92. var b = start.b + ((end.b - start.b) * amount);
  93. return new Color3(r, g, b);
  94. };
  95. Color3.Red = function () {
  96. return new Color3(1, 0, 0);
  97. };
  98. Color3.Green = function () {
  99. return new Color3(0, 1, 0);
  100. };
  101. Color3.Blue = function () {
  102. return new Color3(0, 0, 1);
  103. };
  104. Color3.Black = function () {
  105. return new Color3(0, 0, 0);
  106. };
  107. Color3.White = function () {
  108. return new Color3(1, 1, 1);
  109. };
  110. Color3.Purple = function () {
  111. return new Color3(0.5, 0, 0.5);
  112. };
  113. Color3.Magenta = function () {
  114. return new Color3(1, 0, 1);
  115. };
  116. Color3.Yellow = function () {
  117. return new Color3(1, 1, 0);
  118. };
  119. Color3.Gray = function () {
  120. return new Color3(0.5, 0.5, 0.5);
  121. };
  122. return Color3;
  123. })();
  124. BABYLON.Color3 = Color3;
  125. var Color4 = (function () {
  126. function Color4(r, g, b, a) {
  127. this.r = r;
  128. this.g = g;
  129. this.b = b;
  130. this.a = a;
  131. }
  132. Color4.prototype.addInPlace = function (right) {
  133. this.r += right.r;
  134. this.g += right.g;
  135. this.b += right.b;
  136. this.a += right.a;
  137. };
  138. Color4.prototype.asArray = function () {
  139. var result = [];
  140. this.toArray(result, 0);
  141. return result;
  142. };
  143. Color4.prototype.toArray = function (array, index) {
  144. if (index === undefined) {
  145. index = 0;
  146. }
  147. array[index] = this.r;
  148. array[index + 1] = this.g;
  149. array[index + 2] = this.b;
  150. array[index + 3] = this.a;
  151. };
  152. Color4.prototype.add = function (right) {
  153. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  154. };
  155. Color4.prototype.subtract = function (right) {
  156. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  157. };
  158. Color4.prototype.subtractToRef = function (right, result) {
  159. result.r = this.r - right.r;
  160. result.g = this.g - right.g;
  161. result.b = this.b - right.b;
  162. result.a = this.a - right.a;
  163. };
  164. Color4.prototype.scale = function (scale) {
  165. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  166. };
  167. Color4.prototype.scaleToRef = function (scale, result) {
  168. result.r = this.r * scale;
  169. result.g = this.g * scale;
  170. result.b = this.b * scale;
  171. result.a = this.a * scale;
  172. };
  173. Color4.prototype.toString = function () {
  174. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  175. };
  176. Color4.prototype.clone = function () {
  177. return new Color4(this.r, this.g, this.b, this.a);
  178. };
  179. Color4.Lerp = function (left, right, amount) {
  180. var result = new Color4(0, 0, 0, 0);
  181. BABYLON.Color4.LerpToRef(left, right, amount, result);
  182. return result;
  183. };
  184. Color4.LerpToRef = function (left, right, amount, result) {
  185. result.r = left.r + (right.r - left.r) * amount;
  186. result.g = left.g + (right.g - left.g) * amount;
  187. result.b = left.b + (right.b - left.b) * amount;
  188. result.a = left.a + (right.a - left.a) * amount;
  189. };
  190. Color4.FromArray = function (array, offset) {
  191. if (typeof offset === "undefined") { offset = 0; }
  192. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  193. };
  194. Color4.FromInts = function (r, g, b, a) {
  195. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  196. };
  197. return Color4;
  198. })();
  199. BABYLON.Color4 = Color4;
  200. var Vector2 = (function () {
  201. function Vector2(x, y) {
  202. this.x = x;
  203. this.y = y;
  204. }
  205. Vector2.prototype.toString = function () {
  206. return "{X: " + this.x + " Y:" + this.y + "}";
  207. };
  208. Vector2.prototype.toArray = function (array, index) {
  209. if (index === undefined) {
  210. index = 0;
  211. }
  212. array[index] = this.x;
  213. array[index + 1] = this.y;
  214. };
  215. Vector2.prototype.asArray = function () {
  216. var result = [];
  217. this.toArray(result, 0);
  218. return result;
  219. };
  220. Vector2.prototype.copyFrom = function (source) {
  221. this.x = source.x;
  222. this.y = source.y;
  223. };
  224. Vector2.prototype.copyFromFloats = function (x, y) {
  225. this.x = x;
  226. this.y = y;
  227. };
  228. Vector2.prototype.add = function (otherVector) {
  229. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  230. };
  231. Vector2.prototype.addVector3 = function (otherVector) {
  232. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  233. };
  234. Vector2.prototype.subtract = function (otherVector) {
  235. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  236. };
  237. Vector2.prototype.subtractInPlace = function (otherVector) {
  238. this.x -= otherVector.x;
  239. this.y -= otherVector.y;
  240. };
  241. Vector2.prototype.multiplyInPlace = function (otherVector) {
  242. this.x *= otherVector.x;
  243. this.y *= otherVector.y;
  244. };
  245. Vector2.prototype.multiply = function (otherVector) {
  246. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  247. };
  248. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  249. result.x = this.x * otherVector.x;
  250. result.y = this.y * otherVector.y;
  251. };
  252. Vector2.prototype.multiplyByFloats = function (x, y) {
  253. return new Vector2(this.x * x, this.y * y);
  254. };
  255. Vector2.prototype.divide = function (otherVector) {
  256. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  257. };
  258. Vector2.prototype.divideToRef = function (otherVector, result) {
  259. result.x = this.x / otherVector.x;
  260. result.y = this.y / otherVector.y;
  261. };
  262. Vector2.prototype.negate = function () {
  263. return new Vector2(-this.x, -this.y);
  264. };
  265. Vector2.prototype.scaleInPlace = function (scale) {
  266. this.x *= scale;
  267. this.y *= scale;
  268. return this;
  269. };
  270. Vector2.prototype.scale = function (scale) {
  271. return new Vector2(this.x * scale, this.y * scale);
  272. };
  273. Vector2.prototype.equals = function (otherVector) {
  274. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  275. };
  276. Vector2.prototype.length = function () {
  277. return Math.sqrt(this.x * this.x + this.y * this.y);
  278. };
  279. Vector2.prototype.lengthSquared = function () {
  280. return (this.x * this.x + this.y * this.y);
  281. };
  282. Vector2.prototype.normalize = function () {
  283. var len = this.length();
  284. if (len === 0)
  285. return this;
  286. var num = 1.0 / len;
  287. this.x *= num;
  288. this.y *= num;
  289. return this;
  290. };
  291. Vector2.prototype.clone = function () {
  292. return new Vector2(this.x, this.y);
  293. };
  294. Vector2.Zero = function () {
  295. return new Vector2(0, 0);
  296. };
  297. Vector2.FromArray = function (array, offset) {
  298. if (!offset) {
  299. offset = 0;
  300. }
  301. return new Vector2(array[offset], array[offset + 1]);
  302. };
  303. Vector2.FromArrayToRef = function (array, offset, result) {
  304. result.x = array[offset];
  305. result.y = array[offset + 1];
  306. };
  307. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  308. var squared = amount * amount;
  309. var cubed = amount * squared;
  310. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  311. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  312. return new Vector2(x, y);
  313. };
  314. Vector2.Clamp = function (value, min, max) {
  315. var x = value.x;
  316. x = (x > max.x) ? max.x : x;
  317. x = (x < min.x) ? min.x : x;
  318. var y = value.y;
  319. y = (y > max.y) ? max.y : y;
  320. y = (y < min.y) ? min.y : y;
  321. return new Vector2(x, y);
  322. };
  323. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  324. var squared = amount * amount;
  325. var cubed = amount * squared;
  326. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  327. var part2 = (-2.0 * cubed) + (3.0 * squared);
  328. var part3 = (cubed - (2.0 * squared)) + amount;
  329. var part4 = cubed - squared;
  330. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  331. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  332. return new Vector2(x, y);
  333. };
  334. Vector2.Lerp = function (start, end, amount) {
  335. var x = start.x + ((end.x - start.x) * amount);
  336. var y = start.y + ((end.y - start.y) * amount);
  337. return new Vector2(x, y);
  338. };
  339. Vector2.Dot = function (left, right) {
  340. return left.x * right.x + left.y * right.y;
  341. };
  342. Vector2.Normalize = function (vector) {
  343. var newVector = vector.clone();
  344. newVector.normalize();
  345. return newVector;
  346. };
  347. Vector2.Minimize = function (left, right) {
  348. var x = (left.x < right.x) ? left.x : right.x;
  349. var y = (left.y < right.y) ? left.y : right.y;
  350. return new Vector2(x, y);
  351. };
  352. Vector2.Maximize = function (left, right) {
  353. var x = (left.x > right.x) ? left.x : right.x;
  354. var y = (left.y > right.y) ? left.y : right.y;
  355. return new Vector2(x, y);
  356. };
  357. Vector2.Transform = function (vector, transformation) {
  358. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  359. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  360. return new Vector2(x, y);
  361. };
  362. Vector2.Distance = function (value1, value2) {
  363. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  364. };
  365. Vector2.DistanceSquared = function (value1, value2) {
  366. var x = value1.x - value2.x;
  367. var y = value1.y - value2.y;
  368. return (x * x) + (y * y);
  369. };
  370. return Vector2;
  371. })();
  372. BABYLON.Vector2 = Vector2;
  373. var Vector3 = (function () {
  374. function Vector3(x, y, z) {
  375. this.x = x;
  376. this.y = y;
  377. this.z = z;
  378. }
  379. Vector3.prototype.toString = function () {
  380. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  381. };
  382. Vector3.prototype.asArray = function () {
  383. var result = [];
  384. this.toArray(result, 0);
  385. return result;
  386. };
  387. Vector3.prototype.toArray = function (array, index) {
  388. if (index === undefined) {
  389. index = 0;
  390. }
  391. array[index] = this.x;
  392. array[index + 1] = this.y;
  393. array[index + 2] = this.z;
  394. };
  395. Vector3.prototype.addInPlace = function (otherVector) {
  396. this.x += otherVector.x;
  397. this.y += otherVector.y;
  398. this.z += otherVector.z;
  399. };
  400. Vector3.prototype.add = function (otherVector) {
  401. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  402. };
  403. Vector3.prototype.addToRef = function (otherVector, result) {
  404. result.x = this.x + otherVector.x;
  405. result.y = this.y + otherVector.y;
  406. result.z = this.z + otherVector.z;
  407. };
  408. Vector3.prototype.subtractInPlace = function (otherVector) {
  409. this.x -= otherVector.x;
  410. this.y -= otherVector.y;
  411. this.z -= otherVector.z;
  412. };
  413. Vector3.prototype.subtract = function (otherVector) {
  414. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  415. };
  416. Vector3.prototype.subtractToRef = function (otherVector, result) {
  417. result.x = this.x - otherVector.x;
  418. result.y = this.y - otherVector.y;
  419. result.z = this.z - otherVector.z;
  420. };
  421. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  422. return new Vector3(this.x - x, this.y - y, this.z - z);
  423. };
  424. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  425. result.x = this.x - x;
  426. result.y = this.y - y;
  427. result.z = this.z - z;
  428. };
  429. Vector3.prototype.negate = function () {
  430. return new Vector3(-this.x, -this.y, -this.z);
  431. };
  432. Vector3.prototype.scaleInPlace = function (scale) {
  433. this.x *= scale;
  434. this.y *= scale;
  435. this.z *= scale;
  436. return this;
  437. };
  438. Vector3.prototype.scale = function (scale) {
  439. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  440. };
  441. Vector3.prototype.scaleToRef = function (scale, result) {
  442. result.x = this.x * scale;
  443. result.y = this.y * scale;
  444. result.z = this.z * scale;
  445. };
  446. Vector3.prototype.equals = function (otherVector) {
  447. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  448. };
  449. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  450. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  451. };
  452. Vector3.prototype.equalsToFloats = function (x, y, z) {
  453. return this.x === x && this.y === y && this.z === z;
  454. };
  455. Vector3.prototype.multiplyInPlace = function (otherVector) {
  456. this.x *= otherVector.x;
  457. this.y *= otherVector.y;
  458. this.z *= otherVector.z;
  459. };
  460. Vector3.prototype.multiply = function (otherVector) {
  461. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  462. };
  463. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  464. result.x = this.x * otherVector.x;
  465. result.y = this.y * otherVector.y;
  466. result.z = this.z * otherVector.z;
  467. };
  468. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  469. return new Vector3(this.x * x, this.y * y, this.z * z);
  470. };
  471. Vector3.prototype.divide = function (otherVector) {
  472. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  473. };
  474. Vector3.prototype.divideToRef = function (otherVector, result) {
  475. result.x = this.x / otherVector.x;
  476. result.y = this.y / otherVector.y;
  477. result.z = this.z / otherVector.z;
  478. };
  479. Vector3.prototype.MinimizeInPlace = function (other) {
  480. if (other.x < this.x)
  481. this.x = other.x;
  482. if (other.y < this.y)
  483. this.y = other.y;
  484. if (other.z < this.z)
  485. this.z = other.z;
  486. };
  487. Vector3.prototype.MaximizeInPlace = function (other) {
  488. if (other.x > this.x)
  489. this.x = other.x;
  490. if (other.y > this.y)
  491. this.y = other.y;
  492. if (other.z > this.z)
  493. this.z = other.z;
  494. };
  495. Vector3.prototype.length = function () {
  496. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  497. };
  498. Vector3.prototype.lengthSquared = function () {
  499. return (this.x * this.x + this.y * this.y + this.z * this.z);
  500. };
  501. Vector3.prototype.normalize = function () {
  502. var len = this.length();
  503. if (len === 0)
  504. return this;
  505. var num = 1.0 / len;
  506. this.x *= num;
  507. this.y *= num;
  508. this.z *= num;
  509. return this;
  510. };
  511. Vector3.prototype.clone = function () {
  512. return new Vector3(this.x, this.y, this.z);
  513. };
  514. Vector3.prototype.copyFrom = function (source) {
  515. this.x = source.x;
  516. this.y = source.y;
  517. this.z = source.z;
  518. };
  519. Vector3.prototype.copyFromFloats = function (x, y, z) {
  520. this.x = x;
  521. this.y = y;
  522. this.z = z;
  523. };
  524. Vector3.FromArray = function (array, offset) {
  525. if (!offset) {
  526. offset = 0;
  527. }
  528. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  529. };
  530. Vector3.FromArrayToRef = function (array, offset, result) {
  531. result.x = array[offset];
  532. result.y = array[offset + 1];
  533. result.z = array[offset + 2];
  534. };
  535. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  536. result.x = array[offset];
  537. result.y = array[offset + 1];
  538. result.z = array[offset + 2];
  539. };
  540. Vector3.FromFloatsToRef = function (x, y, z, result) {
  541. result.x = x;
  542. result.y = y;
  543. result.z = z;
  544. };
  545. Vector3.Zero = function () {
  546. return new Vector3(0, 0, 0);
  547. };
  548. Vector3.Up = function () {
  549. return new Vector3(0, 1.0, 0);
  550. };
  551. Vector3.TransformCoordinates = function (vector, transformation) {
  552. var result = Vector3.Zero();
  553. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  554. return result;
  555. };
  556. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  557. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  558. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  559. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  560. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  561. result.x = x / w;
  562. result.y = y / w;
  563. result.z = z / w;
  564. };
  565. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  566. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  567. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  568. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  569. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  570. result.x = rx / rw;
  571. result.y = ry / rw;
  572. result.z = rz / rw;
  573. };
  574. Vector3.TransformNormal = function (vector, transformation) {
  575. var result = Vector3.Zero();
  576. Vector3.TransformNormalToRef(vector, transformation, result);
  577. return result;
  578. };
  579. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  580. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  581. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  582. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  583. };
  584. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  585. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  586. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  587. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  588. };
  589. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  590. var squared = amount * amount;
  591. var cubed = amount * squared;
  592. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  593. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  594. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  595. return new Vector3(x, y, z);
  596. };
  597. Vector3.Clamp = function (value, min, max) {
  598. var x = value.x;
  599. x = (x > max.x) ? max.x : x;
  600. x = (x < min.x) ? min.x : x;
  601. var y = value.y;
  602. y = (y > max.y) ? max.y : y;
  603. y = (y < min.y) ? min.y : y;
  604. var z = value.z;
  605. z = (z > max.z) ? max.z : z;
  606. z = (z < min.z) ? min.z : z;
  607. return new Vector3(x, y, z);
  608. };
  609. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  610. var squared = amount * amount;
  611. var cubed = amount * squared;
  612. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  613. var part2 = (-2.0 * cubed) + (3.0 * squared);
  614. var part3 = (cubed - (2.0 * squared)) + amount;
  615. var part4 = cubed - squared;
  616. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  617. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  618. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  619. return new Vector3(x, y, z);
  620. };
  621. Vector3.Lerp = function (start, end, amount) {
  622. var x = start.x + ((end.x - start.x) * amount);
  623. var y = start.y + ((end.y - start.y) * amount);
  624. var z = start.z + ((end.z - start.z) * amount);
  625. return new Vector3(x, y, z);
  626. };
  627. Vector3.Dot = function (left, right) {
  628. return (left.x * right.x + left.y * right.y + left.z * right.z);
  629. };
  630. Vector3.Cross = function (left, right) {
  631. var result = Vector3.Zero();
  632. Vector3.CrossToRef(left, right, result);
  633. return result;
  634. };
  635. Vector3.CrossToRef = function (left, right, result) {
  636. result.x = left.y * right.z - left.z * right.y;
  637. result.y = left.z * right.x - left.x * right.z;
  638. result.z = left.x * right.y - left.y * right.x;
  639. };
  640. Vector3.Normalize = function (vector) {
  641. var result = Vector3.Zero();
  642. Vector3.NormalizeToRef(vector, result);
  643. return result;
  644. };
  645. Vector3.NormalizeToRef = function (vector, result) {
  646. result.copyFrom(vector);
  647. result.normalize();
  648. };
  649. Vector3.Project = function (vector, world, transform, viewport) {
  650. var cw = viewport.width;
  651. var ch = viewport.height;
  652. var cx = viewport.x;
  653. var cy = viewport.y;
  654. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  655. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  656. return Vector3.TransformCoordinates(vector, finalMatrix);
  657. };
  658. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  659. var matrix = world.multiply(view).multiply(projection);
  660. matrix.invert();
  661. source.x = source.x / viewportWidth * 2 - 1;
  662. source.y = -(source.y / viewportHeight * 2 - 1);
  663. var vector = BABYLON.Vector3.TransformCoordinates(source, matrix);
  664. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  665. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  666. vector = vector.scale(1.0 / num);
  667. }
  668. return vector;
  669. };
  670. Vector3.Minimize = function (left, right) {
  671. var min = left.clone();
  672. min.MinimizeInPlace(right);
  673. return min;
  674. };
  675. Vector3.Maximize = function (left, right) {
  676. var max = left.clone();
  677. max.MaximizeInPlace(right);
  678. return max;
  679. };
  680. Vector3.Distance = function (value1, value2) {
  681. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  682. };
  683. Vector3.DistanceSquared = function (value1, value2) {
  684. var x = value1.x - value2.x;
  685. var y = value1.y - value2.y;
  686. var z = value1.z - value2.z;
  687. return (x * x) + (y * y) + (z * z);
  688. };
  689. Vector3.Center = function (value1, value2) {
  690. var center = value1.add(value2);
  691. center.scaleInPlace(0.5);
  692. return center;
  693. };
  694. return Vector3;
  695. })();
  696. BABYLON.Vector3 = Vector3;
  697. var Quaternion = (function () {
  698. function Quaternion(x, y, z, w) {
  699. if (typeof x === "undefined") { x = 0; }
  700. if (typeof y === "undefined") { y = 0; }
  701. if (typeof z === "undefined") { z = 0; }
  702. if (typeof w === "undefined") { w = 1; }
  703. this.x = x;
  704. this.y = y;
  705. this.z = z;
  706. this.w = w;
  707. }
  708. Quaternion.prototype.toString = function () {
  709. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  710. };
  711. Quaternion.prototype.asArray = function () {
  712. return [this.x, this.y, this.z, this.w];
  713. };
  714. Quaternion.prototype.equals = function (otherQuaternion) {
  715. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  716. };
  717. Quaternion.prototype.clone = function () {
  718. return new Quaternion(this.x, this.y, this.z, this.w);
  719. };
  720. Quaternion.prototype.copyFrom = function (other) {
  721. this.x = other.x;
  722. this.y = other.y;
  723. this.z = other.z;
  724. this.w = other.w;
  725. };
  726. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  727. this.x = x;
  728. this.y = y;
  729. this.z = z;
  730. this.w = w;
  731. };
  732. Quaternion.prototype.add = function (other) {
  733. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  734. };
  735. Quaternion.prototype.subtract = function (other) {
  736. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  737. };
  738. Quaternion.prototype.scale = function (value) {
  739. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  740. };
  741. Quaternion.prototype.multiply = function (q1) {
  742. var result = new Quaternion(0, 0, 0, 1.0);
  743. this.multiplyToRef(q1, result);
  744. return result;
  745. };
  746. Quaternion.prototype.multiplyToRef = function (q1, result) {
  747. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  748. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  749. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  750. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  751. };
  752. Quaternion.prototype.length = function () {
  753. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  754. };
  755. Quaternion.prototype.normalize = function () {
  756. var length = 1.0 / this.length();
  757. this.x *= length;
  758. this.y *= length;
  759. this.z *= length;
  760. this.w *= length;
  761. };
  762. Quaternion.prototype.toEulerAngles = function () {
  763. var result = Vector3.Zero();
  764. this.toEulerAnglesToRef(result);
  765. return result;
  766. };
  767. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  768. var qx = this.x;
  769. var qy = this.y;
  770. var qz = this.z;
  771. var qw = this.w;
  772. var sqx = qx * qx;
  773. var sqy = qy * qy;
  774. var sqz = qz * qz;
  775. var yaw = Math.atan2(2.0 * (qy * qw - qx * qz), 1.0 - 2.0 * (sqy + sqz));
  776. var pitch = Math.asin(2.0 * (qx * qy + qz * qw));
  777. var roll = Math.atan2(2.0 * (qx * qw - qy * qz), 1.0 - 2.0 * (sqx + sqz));
  778. var gimbaLockTest = qx * qy + qz * qw;
  779. if (gimbaLockTest > 0.499) {
  780. yaw = 2.0 * Math.atan2(qx, qw);
  781. roll = 0;
  782. } else if (gimbaLockTest < -0.499) {
  783. yaw = -2.0 * Math.atan2(qx, qw);
  784. roll = 0;
  785. }
  786. result.x = pitch;
  787. result.y = yaw;
  788. result.z = roll;
  789. };
  790. Quaternion.prototype.toRotationMatrix = function (result) {
  791. var xx = this.x * this.x;
  792. var yy = this.y * this.y;
  793. var zz = this.z * this.z;
  794. var xy = this.x * this.y;
  795. var zw = this.z * this.w;
  796. var zx = this.z * this.x;
  797. var yw = this.y * this.w;
  798. var yz = this.y * this.z;
  799. var xw = this.x * this.w;
  800. result.m[0] = 1.0 - (2.0 * (yy + zz));
  801. result.m[1] = 2.0 * (xy + zw);
  802. result.m[2] = 2.0 * (zx - yw);
  803. result.m[3] = 0;
  804. result.m[4] = 2.0 * (xy - zw);
  805. result.m[5] = 1.0 - (2.0 * (zz + xx));
  806. result.m[6] = 2.0 * (yz + xw);
  807. result.m[7] = 0;
  808. result.m[8] = 2.0 * (zx + yw);
  809. result.m[9] = 2.0 * (yz - xw);
  810. result.m[10] = 1.0 - (2.0 * (yy + xx));
  811. result.m[11] = 0;
  812. result.m[12] = 0;
  813. result.m[13] = 0;
  814. result.m[14] = 0;
  815. result.m[15] = 1.0;
  816. };
  817. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  818. var data = matrix.m;
  819. var m11 = data[0], m12 = data[4], m13 = data[8];
  820. var m21 = data[1], m22 = data[5], m23 = data[9];
  821. var m31 = data[2], m32 = data[6], m33 = data[10];
  822. var trace = m11 + m22 + m33;
  823. var s;
  824. if (trace > 0) {
  825. s = 0.5 / Math.sqrt(trace + 1.0);
  826. this.w = 0.25 / s;
  827. this.x = (m32 - m23) * s;
  828. this.y = (m13 - m31) * s;
  829. this.z = (m21 - m12) * s;
  830. return;
  831. }
  832. if (m11 > m22 && m11 > m33) {
  833. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  834. this.w = (m32 - m23) / s;
  835. this.x = 0.25 * s;
  836. this.y = (m12 + m21) / s;
  837. this.z = (m13 + m31) / s;
  838. return;
  839. }
  840. if (m22 > m33) {
  841. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  842. this.w = (m13 - m31) / s;
  843. this.x = (m12 + m21) / s;
  844. this.y = 0.25 * s;
  845. this.z = (m23 + m32) / s;
  846. return;
  847. }
  848. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  849. this.w = (m21 - m12) / s;
  850. this.x = (m13 + m31) / s;
  851. this.y = (m23 + m32) / s;
  852. this.z = 0.25 * s;
  853. };
  854. Quaternion.Inverse = function (q) {
  855. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  856. };
  857. Quaternion.RotationAxis = function (axis, angle) {
  858. var result = new Quaternion();
  859. var sin = Math.sin(angle / 2);
  860. result.w = Math.cos(angle / 2);
  861. result.x = axis.x * sin;
  862. result.y = axis.y * sin;
  863. result.z = axis.z * sin;
  864. return result;
  865. };
  866. Quaternion.FromArray = function (array, offset) {
  867. if (!offset) {
  868. offset = 0;
  869. }
  870. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  871. };
  872. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  873. var result = new Quaternion();
  874. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  875. return result;
  876. };
  877. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  878. var halfRoll = roll * 0.5;
  879. var halfPitch = pitch * 0.5;
  880. var halfYaw = yaw * 0.5;
  881. var sinRoll = Math.sin(halfRoll);
  882. var cosRoll = Math.cos(halfRoll);
  883. var sinPitch = Math.sin(halfPitch);
  884. var cosPitch = Math.cos(halfPitch);
  885. var sinYaw = Math.sin(halfYaw);
  886. var cosYaw = Math.cos(halfYaw);
  887. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  888. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  889. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  890. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  891. };
  892. Quaternion.Slerp = function (left, right, amount) {
  893. var num2;
  894. var num3;
  895. var num = amount;
  896. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  897. var flag = false;
  898. if (num4 < 0) {
  899. flag = true;
  900. num4 = -num4;
  901. }
  902. if (num4 > 0.999999) {
  903. num3 = 1 - num;
  904. num2 = flag ? -num : num;
  905. } else {
  906. var num5 = Math.acos(num4);
  907. var num6 = (1.0 / Math.sin(num5));
  908. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  909. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  910. }
  911. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  912. };
  913. return Quaternion;
  914. })();
  915. BABYLON.Quaternion = Quaternion;
  916. var Matrix = (function () {
  917. function Matrix() {
  918. this.m = new Float32Array(16);
  919. }
  920. Matrix.prototype.isIdentity = function () {
  921. if (this.m[0] != 1.0 || this.m[5] != 1.0 || this.m[10] != 1.0 || this.m[15] != 1.0)
  922. return false;
  923. if (this.m[1] != 0.0 || this.m[2] != 0.0 || this.m[3] != 0.0 || this.m[4] != 0.0 || this.m[6] != 0.0 || this.m[7] != 0.0 || this.m[8] != 0.0 || this.m[9] != 0.0 || this.m[11] != 0.0 || this.m[12] != 0.0 || this.m[13] != 0.0 || this.m[14] != 0.0)
  924. return false;
  925. return true;
  926. };
  927. Matrix.prototype.determinant = function () {
  928. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  929. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  930. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  931. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  932. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  933. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  934. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  935. };
  936. Matrix.prototype.toArray = function () {
  937. return this.m;
  938. };
  939. Matrix.prototype.asArray = function () {
  940. return this.toArray();
  941. };
  942. Matrix.prototype.invert = function () {
  943. this.invertToRef(this);
  944. };
  945. Matrix.prototype.invertToRef = function (other) {
  946. var l1 = this.m[0];
  947. var l2 = this.m[1];
  948. var l3 = this.m[2];
  949. var l4 = this.m[3];
  950. var l5 = this.m[4];
  951. var l6 = this.m[5];
  952. var l7 = this.m[6];
  953. var l8 = this.m[7];
  954. var l9 = this.m[8];
  955. var l10 = this.m[9];
  956. var l11 = this.m[10];
  957. var l12 = this.m[11];
  958. var l13 = this.m[12];
  959. var l14 = this.m[13];
  960. var l15 = this.m[14];
  961. var l16 = this.m[15];
  962. var l17 = (l11 * l16) - (l12 * l15);
  963. var l18 = (l10 * l16) - (l12 * l14);
  964. var l19 = (l10 * l15) - (l11 * l14);
  965. var l20 = (l9 * l16) - (l12 * l13);
  966. var l21 = (l9 * l15) - (l11 * l13);
  967. var l22 = (l9 * l14) - (l10 * l13);
  968. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  969. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  970. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  971. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  972. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  973. var l28 = (l7 * l16) - (l8 * l15);
  974. var l29 = (l6 * l16) - (l8 * l14);
  975. var l30 = (l6 * l15) - (l7 * l14);
  976. var l31 = (l5 * l16) - (l8 * l13);
  977. var l32 = (l5 * l15) - (l7 * l13);
  978. var l33 = (l5 * l14) - (l6 * l13);
  979. var l34 = (l7 * l12) - (l8 * l11);
  980. var l35 = (l6 * l12) - (l8 * l10);
  981. var l36 = (l6 * l11) - (l7 * l10);
  982. var l37 = (l5 * l12) - (l8 * l9);
  983. var l38 = (l5 * l11) - (l7 * l9);
  984. var l39 = (l5 * l10) - (l6 * l9);
  985. other.m[0] = l23 * l27;
  986. other.m[4] = l24 * l27;
  987. other.m[8] = l25 * l27;
  988. other.m[12] = l26 * l27;
  989. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  990. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  991. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  992. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  993. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  994. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  995. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  996. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  997. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  998. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  999. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1000. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1001. };
  1002. Matrix.prototype.setTranslation = function (vector3) {
  1003. this.m[12] = vector3.x;
  1004. this.m[13] = vector3.y;
  1005. this.m[14] = vector3.z;
  1006. };
  1007. Matrix.prototype.multiply = function (other) {
  1008. var result = new Matrix();
  1009. this.multiplyToRef(other, result);
  1010. return result;
  1011. };
  1012. Matrix.prototype.copyFrom = function (other) {
  1013. for (var index = 0; index < 16; index++) {
  1014. this.m[index] = other.m[index];
  1015. }
  1016. };
  1017. Matrix.prototype.copyToArray = function (array, offset) {
  1018. if (typeof offset === "undefined") { offset = 0; }
  1019. for (var index = 0; index < 16; index++) {
  1020. array[offset + index] = this.m[index];
  1021. }
  1022. };
  1023. Matrix.prototype.multiplyToRef = function (other, result) {
  1024. this.multiplyToArray(other, result.m, 0);
  1025. };
  1026. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1027. var tm0 = this.m[0];
  1028. var tm1 = this.m[1];
  1029. var tm2 = this.m[2];
  1030. var tm3 = this.m[3];
  1031. var tm4 = this.m[4];
  1032. var tm5 = this.m[5];
  1033. var tm6 = this.m[6];
  1034. var tm7 = this.m[7];
  1035. var tm8 = this.m[8];
  1036. var tm9 = this.m[9];
  1037. var tm10 = this.m[10];
  1038. var tm11 = this.m[11];
  1039. var tm12 = this.m[12];
  1040. var tm13 = this.m[13];
  1041. var tm14 = this.m[14];
  1042. var tm15 = this.m[15];
  1043. var om0 = other.m[0];
  1044. var om1 = other.m[1];
  1045. var om2 = other.m[2];
  1046. var om3 = other.m[3];
  1047. var om4 = other.m[4];
  1048. var om5 = other.m[5];
  1049. var om6 = other.m[6];
  1050. var om7 = other.m[7];
  1051. var om8 = other.m[8];
  1052. var om9 = other.m[9];
  1053. var om10 = other.m[10];
  1054. var om11 = other.m[11];
  1055. var om12 = other.m[12];
  1056. var om13 = other.m[13];
  1057. var om14 = other.m[14];
  1058. var om15 = other.m[15];
  1059. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1060. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1061. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1062. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1063. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1064. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1065. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1066. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1067. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1068. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1069. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1070. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1071. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1072. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1073. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1074. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1075. };
  1076. Matrix.prototype.equals = function (value) {
  1077. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1078. };
  1079. Matrix.prototype.clone = function () {
  1080. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1081. };
  1082. Matrix.FromArray = function (array, offset) {
  1083. var result = new Matrix();
  1084. if (!offset) {
  1085. offset = 0;
  1086. }
  1087. Matrix.FromArrayToRef(array, offset, result);
  1088. return result;
  1089. };
  1090. Matrix.FromArrayToRef = function (array, offset, result) {
  1091. for (var index = 0; index < 16; index++) {
  1092. result.m[index] = array[index + offset];
  1093. }
  1094. };
  1095. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1096. result.m[0] = initialM11;
  1097. result.m[1] = initialM12;
  1098. result.m[2] = initialM13;
  1099. result.m[3] = initialM14;
  1100. result.m[4] = initialM21;
  1101. result.m[5] = initialM22;
  1102. result.m[6] = initialM23;
  1103. result.m[7] = initialM24;
  1104. result.m[8] = initialM31;
  1105. result.m[9] = initialM32;
  1106. result.m[10] = initialM33;
  1107. result.m[11] = initialM34;
  1108. result.m[12] = initialM41;
  1109. result.m[13] = initialM42;
  1110. result.m[14] = initialM43;
  1111. result.m[15] = initialM44;
  1112. };
  1113. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1114. var result = new Matrix();
  1115. result.m[0] = initialM11;
  1116. result.m[1] = initialM12;
  1117. result.m[2] = initialM13;
  1118. result.m[3] = initialM14;
  1119. result.m[4] = initialM21;
  1120. result.m[5] = initialM22;
  1121. result.m[6] = initialM23;
  1122. result.m[7] = initialM24;
  1123. result.m[8] = initialM31;
  1124. result.m[9] = initialM32;
  1125. result.m[10] = initialM33;
  1126. result.m[11] = initialM34;
  1127. result.m[12] = initialM41;
  1128. result.m[13] = initialM42;
  1129. result.m[14] = initialM43;
  1130. result.m[15] = initialM44;
  1131. return result;
  1132. };
  1133. Matrix.Identity = function () {
  1134. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1135. };
  1136. Matrix.IdentityToRef = function (result) {
  1137. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1138. };
  1139. Matrix.Zero = function () {
  1140. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1141. };
  1142. Matrix.RotationX = function (angle) {
  1143. var result = new Matrix();
  1144. Matrix.RotationXToRef(angle, result);
  1145. return result;
  1146. };
  1147. Matrix.RotationXToRef = function (angle, result) {
  1148. var s = Math.sin(angle);
  1149. var c = Math.cos(angle);
  1150. result.m[0] = 1.0;
  1151. result.m[15] = 1.0;
  1152. result.m[5] = c;
  1153. result.m[10] = c;
  1154. result.m[9] = -s;
  1155. result.m[6] = s;
  1156. result.m[1] = 0;
  1157. result.m[2] = 0;
  1158. result.m[3] = 0;
  1159. result.m[4] = 0;
  1160. result.m[7] = 0;
  1161. result.m[8] = 0;
  1162. result.m[11] = 0;
  1163. result.m[12] = 0;
  1164. result.m[13] = 0;
  1165. result.m[14] = 0;
  1166. };
  1167. Matrix.RotationY = function (angle) {
  1168. var result = new Matrix();
  1169. Matrix.RotationYToRef(angle, result);
  1170. return result;
  1171. };
  1172. Matrix.RotationYToRef = function (angle, result) {
  1173. var s = Math.sin(angle);
  1174. var c = Math.cos(angle);
  1175. result.m[5] = 1.0;
  1176. result.m[15] = 1.0;
  1177. result.m[0] = c;
  1178. result.m[2] = -s;
  1179. result.m[8] = s;
  1180. result.m[10] = c;
  1181. result.m[1] = 0;
  1182. result.m[3] = 0;
  1183. result.m[4] = 0;
  1184. result.m[6] = 0;
  1185. result.m[7] = 0;
  1186. result.m[9] = 0;
  1187. result.m[11] = 0;
  1188. result.m[12] = 0;
  1189. result.m[13] = 0;
  1190. result.m[14] = 0;
  1191. };
  1192. Matrix.RotationZ = function (angle) {
  1193. var result = new Matrix();
  1194. Matrix.RotationZToRef(angle, result);
  1195. return result;
  1196. };
  1197. Matrix.RotationZToRef = function (angle, result) {
  1198. var s = Math.sin(angle);
  1199. var c = Math.cos(angle);
  1200. result.m[10] = 1.0;
  1201. result.m[15] = 1.0;
  1202. result.m[0] = c;
  1203. result.m[1] = s;
  1204. result.m[4] = -s;
  1205. result.m[5] = c;
  1206. result.m[2] = 0;
  1207. result.m[3] = 0;
  1208. result.m[6] = 0;
  1209. result.m[7] = 0;
  1210. result.m[8] = 0;
  1211. result.m[9] = 0;
  1212. result.m[11] = 0;
  1213. result.m[12] = 0;
  1214. result.m[13] = 0;
  1215. result.m[14] = 0;
  1216. };
  1217. Matrix.RotationAxis = function (axis, angle) {
  1218. var s = Math.sin(-angle);
  1219. var c = Math.cos(-angle);
  1220. var c1 = 1 - c;
  1221. axis.normalize();
  1222. var result = Matrix.Zero();
  1223. result.m[0] = (axis.x * axis.x) * c1 + c;
  1224. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1225. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1226. result.m[3] = 0.0;
  1227. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1228. result.m[5] = (axis.y * axis.y) * c1 + c;
  1229. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1230. result.m[7] = 0.0;
  1231. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1232. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1233. result.m[10] = (axis.z * axis.z) * c1 + c;
  1234. result.m[11] = 0.0;
  1235. result.m[15] = 1.0;
  1236. return result;
  1237. };
  1238. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1239. var result = new Matrix();
  1240. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1241. return result;
  1242. };
  1243. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1244. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1245. this._tempQuaternion.toRotationMatrix(result);
  1246. };
  1247. Matrix.Scaling = function (x, y, z) {
  1248. var result = Matrix.Zero();
  1249. Matrix.ScalingToRef(x, y, z, result);
  1250. return result;
  1251. };
  1252. Matrix.ScalingToRef = function (x, y, z, result) {
  1253. result.m[0] = x;
  1254. result.m[1] = 0;
  1255. result.m[2] = 0;
  1256. result.m[3] = 0;
  1257. result.m[4] = 0;
  1258. result.m[5] = y;
  1259. result.m[6] = 0;
  1260. result.m[7] = 0;
  1261. result.m[8] = 0;
  1262. result.m[9] = 0;
  1263. result.m[10] = z;
  1264. result.m[11] = 0;
  1265. result.m[12] = 0;
  1266. result.m[13] = 0;
  1267. result.m[14] = 0;
  1268. result.m[15] = 1.0;
  1269. };
  1270. Matrix.Translation = function (x, y, z) {
  1271. var result = Matrix.Identity();
  1272. Matrix.TranslationToRef(x, y, z, result);
  1273. return result;
  1274. };
  1275. Matrix.TranslationToRef = function (x, y, z, result) {
  1276. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1277. };
  1278. Matrix.LookAtLH = function (eye, target, up) {
  1279. var result = Matrix.Zero();
  1280. Matrix.LookAtLHToRef(eye, target, up, result);
  1281. return result;
  1282. };
  1283. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1284. target.subtractToRef(eye, this._zAxis);
  1285. this._zAxis.normalize();
  1286. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1287. this._xAxis.normalize();
  1288. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1289. this._yAxis.normalize();
  1290. var ex = -Vector3.Dot(this._xAxis, eye);
  1291. var ey = -Vector3.Dot(this._yAxis, eye);
  1292. var ez = -Vector3.Dot(this._zAxis, eye);
  1293. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1294. };
  1295. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1296. var hw = 2.0 / width;
  1297. var hh = 2.0 / height;
  1298. var id = 1.0 / (zfar - znear);
  1299. var nid = znear / (znear - zfar);
  1300. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1301. };
  1302. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1303. var matrix = Matrix.Zero();
  1304. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1305. return matrix;
  1306. };
  1307. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1308. result.m[0] = 2.0 / (right - left);
  1309. result.m[1] = result.m[2] = result.m[3] = 0;
  1310. result.m[5] = 2.0 / (top - bottom);
  1311. result.m[4] = result.m[6] = result.m[7] = 0;
  1312. result.m[10] = -1.0 / (znear - zfar);
  1313. result.m[8] = result.m[9] = result.m[11] = 0;
  1314. result.m[12] = (left + right) / (left - right);
  1315. result.m[13] = (top + bottom) / (bottom - top);
  1316. result.m[14] = znear / (znear - zfar);
  1317. result.m[15] = 1.0;
  1318. };
  1319. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1320. var matrix = Matrix.Zero();
  1321. matrix.m[0] = (2.0 * znear) / width;
  1322. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1323. matrix.m[5] = (2.0 * znear) / height;
  1324. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1325. matrix.m[10] = -zfar / (znear - zfar);
  1326. matrix.m[8] = matrix.m[9] = 0.0;
  1327. matrix.m[11] = 1.0;
  1328. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1329. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1330. return matrix;
  1331. };
  1332. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1333. var matrix = Matrix.Zero();
  1334. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1335. return matrix;
  1336. };
  1337. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1338. var tan = 1.0 / (Math.tan(fov * 0.5));
  1339. result.m[0] = tan / aspect;
  1340. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1341. result.m[5] = tan;
  1342. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1343. result.m[8] = result.m[9] = 0.0;
  1344. result.m[10] = -zfar / (znear - zfar);
  1345. result.m[11] = 1.0;
  1346. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1347. result.m[14] = (znear * zfar) / (znear - zfar);
  1348. };
  1349. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1350. var cw = viewport.width;
  1351. var ch = viewport.height;
  1352. var cx = viewport.x;
  1353. var cy = viewport.y;
  1354. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  1355. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1356. };
  1357. Matrix.Transpose = function (matrix) {
  1358. var result = new Matrix();
  1359. result.m[0] = matrix.m[0];
  1360. result.m[1] = matrix.m[4];
  1361. result.m[2] = matrix.m[8];
  1362. result.m[3] = matrix.m[12];
  1363. result.m[4] = matrix.m[1];
  1364. result.m[5] = matrix.m[5];
  1365. result.m[6] = matrix.m[9];
  1366. result.m[7] = matrix.m[13];
  1367. result.m[8] = matrix.m[2];
  1368. result.m[9] = matrix.m[6];
  1369. result.m[10] = matrix.m[10];
  1370. result.m[11] = matrix.m[14];
  1371. result.m[12] = matrix.m[3];
  1372. result.m[13] = matrix.m[7];
  1373. result.m[14] = matrix.m[11];
  1374. result.m[15] = matrix.m[15];
  1375. return result;
  1376. };
  1377. Matrix.Reflection = function (plane) {
  1378. var matrix = new Matrix();
  1379. Matrix.ReflectionToRef(plane, matrix);
  1380. return matrix;
  1381. };
  1382. Matrix.ReflectionToRef = function (plane, result) {
  1383. plane.normalize();
  1384. var x = plane.normal.x;
  1385. var y = plane.normal.y;
  1386. var z = plane.normal.z;
  1387. var temp = -2 * x;
  1388. var temp2 = -2 * y;
  1389. var temp3 = -2 * z;
  1390. result.m[0] = (temp * x) + 1;
  1391. result.m[1] = temp2 * x;
  1392. result.m[2] = temp3 * x;
  1393. result.m[3] = 0.0;
  1394. result.m[4] = temp * y;
  1395. result.m[5] = (temp2 * y) + 1;
  1396. result.m[6] = temp3 * y;
  1397. result.m[7] = 0.0;
  1398. result.m[8] = temp * z;
  1399. result.m[9] = temp2 * z;
  1400. result.m[10] = (temp3 * z) + 1;
  1401. result.m[11] = 0.0;
  1402. result.m[12] = temp * plane.d;
  1403. result.m[13] = temp2 * plane.d;
  1404. result.m[14] = temp3 * plane.d;
  1405. result.m[15] = 1.0;
  1406. };
  1407. Matrix._tempQuaternion = new Quaternion();
  1408. Matrix._xAxis = Vector3.Zero();
  1409. Matrix._yAxis = Vector3.Zero();
  1410. Matrix._zAxis = Vector3.Zero();
  1411. return Matrix;
  1412. })();
  1413. BABYLON.Matrix = Matrix;
  1414. var Plane = (function () {
  1415. function Plane(a, b, c, d) {
  1416. this.normal = new Vector3(a, b, c);
  1417. this.d = d;
  1418. }
  1419. Plane.prototype.asArray = function () {
  1420. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1421. };
  1422. Plane.prototype.clone = function () {
  1423. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1424. };
  1425. Plane.prototype.normalize = function () {
  1426. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1427. var magnitude = 0;
  1428. if (norm != 0) {
  1429. magnitude = 1.0 / norm;
  1430. }
  1431. this.normal.x *= magnitude;
  1432. this.normal.y *= magnitude;
  1433. this.normal.z *= magnitude;
  1434. this.d *= magnitude;
  1435. };
  1436. Plane.prototype.transform = function (transformation) {
  1437. var transposedMatrix = BABYLON.Matrix.Transpose(transformation);
  1438. var x = this.normal.x;
  1439. var y = this.normal.y;
  1440. var z = this.normal.z;
  1441. var d = this.d;
  1442. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1443. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1444. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1445. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1446. return new BABYLON.Plane(normalX, normalY, normalZ, finalD);
  1447. };
  1448. Plane.prototype.dotCoordinate = function (point) {
  1449. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1450. };
  1451. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1452. var x1 = point2.x - point1.x;
  1453. var y1 = point2.y - point1.y;
  1454. var z1 = point2.z - point1.z;
  1455. var x2 = point3.x - point1.x;
  1456. var y2 = point3.y - point1.y;
  1457. var z2 = point3.z - point1.z;
  1458. var yz = (y1 * z2) - (z1 * y2);
  1459. var xz = (z1 * x2) - (x1 * z2);
  1460. var xy = (x1 * y2) - (y1 * x2);
  1461. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1462. var invPyth;
  1463. if (pyth != 0) {
  1464. invPyth = 1.0 / pyth;
  1465. } else {
  1466. invPyth = 0;
  1467. }
  1468. this.normal.x = yz * invPyth;
  1469. this.normal.y = xz * invPyth;
  1470. this.normal.z = xy * invPyth;
  1471. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1472. };
  1473. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1474. var dot = Vector3.Dot(this.normal, direction);
  1475. return (dot <= epsilon);
  1476. };
  1477. Plane.prototype.signedDistanceTo = function (point) {
  1478. return Vector3.Dot(point, this.normal) + this.d;
  1479. };
  1480. Plane.FromArray = function (array) {
  1481. return new BABYLON.Plane(array[0], array[1], array[2], array[3]);
  1482. };
  1483. Plane.FromPoints = function (point1, point2, point3) {
  1484. var result = new BABYLON.Plane(0, 0, 0, 0);
  1485. result.copyFromPoints(point1, point2, point3);
  1486. return result;
  1487. };
  1488. Plane.FromPositionAndNormal = function (origin, normal) {
  1489. var result = new BABYLON.Plane(0, 0, 0, 0);
  1490. normal.normalize();
  1491. result.normal = normal;
  1492. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1493. return result;
  1494. };
  1495. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1496. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1497. return Vector3.Dot(point, normal) + d;
  1498. };
  1499. return Plane;
  1500. })();
  1501. BABYLON.Plane = Plane;
  1502. var Viewport = (function () {
  1503. function Viewport(x, y, width, height) {
  1504. this.x = x;
  1505. this.y = y;
  1506. this.width = width;
  1507. this.height = height;
  1508. }
  1509. Viewport.prototype.toGlobal = function (engine) {
  1510. var width = engine.getRenderWidth();
  1511. var height = engine.getRenderHeight();
  1512. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1513. };
  1514. return Viewport;
  1515. })();
  1516. BABYLON.Viewport = Viewport;
  1517. var Frustum = (function () {
  1518. function Frustum() {
  1519. }
  1520. Frustum.GetPlanes = function (transform) {
  1521. var frustumPlanes = [];
  1522. for (var index = 0; index < 6; index++) {
  1523. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1524. }
  1525. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1526. return frustumPlanes;
  1527. };
  1528. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1529. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1530. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1531. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1532. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1533. frustumPlanes[0].normalize();
  1534. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1535. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1536. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1537. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1538. frustumPlanes[1].normalize();
  1539. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1540. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1541. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1542. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1543. frustumPlanes[2].normalize();
  1544. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1545. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1546. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1547. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1548. frustumPlanes[3].normalize();
  1549. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1550. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1551. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1552. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1553. frustumPlanes[4].normalize();
  1554. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1555. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1556. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1557. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1558. frustumPlanes[5].normalize();
  1559. };
  1560. return Frustum;
  1561. })();
  1562. BABYLON.Frustum = Frustum;
  1563. var Ray = (function () {
  1564. function Ray(origin, direction) {
  1565. this.origin = origin;
  1566. this.direction = direction;
  1567. }
  1568. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1569. var d = 0.0;
  1570. var maxValue = Number.MAX_VALUE;
  1571. if (Math.abs(this.direction.x) < 0.0000001) {
  1572. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1573. return false;
  1574. }
  1575. } else {
  1576. var inv = 1.0 / this.direction.x;
  1577. var min = (minimum.x - this.origin.x) * inv;
  1578. var max = (maximum.x - this.origin.x) * inv;
  1579. if (min > max) {
  1580. var temp = min;
  1581. min = max;
  1582. max = temp;
  1583. }
  1584. d = Math.max(min, d);
  1585. maxValue = Math.min(max, maxValue);
  1586. if (d > maxValue) {
  1587. return false;
  1588. }
  1589. }
  1590. if (Math.abs(this.direction.y) < 0.0000001) {
  1591. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1592. return false;
  1593. }
  1594. } else {
  1595. inv = 1.0 / this.direction.y;
  1596. min = (minimum.y - this.origin.y) * inv;
  1597. max = (maximum.y - this.origin.y) * inv;
  1598. if (min > max) {
  1599. temp = min;
  1600. min = max;
  1601. max = temp;
  1602. }
  1603. d = Math.max(min, d);
  1604. maxValue = Math.min(max, maxValue);
  1605. if (d > maxValue) {
  1606. return false;
  1607. }
  1608. }
  1609. if (Math.abs(this.direction.z) < 0.0000001) {
  1610. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1611. return false;
  1612. }
  1613. } else {
  1614. inv = 1.0 / this.direction.z;
  1615. min = (minimum.z - this.origin.z) * inv;
  1616. max = (maximum.z - this.origin.z) * inv;
  1617. if (min > max) {
  1618. temp = min;
  1619. min = max;
  1620. max = temp;
  1621. }
  1622. d = Math.max(min, d);
  1623. maxValue = Math.min(max, maxValue);
  1624. if (d > maxValue) {
  1625. return false;
  1626. }
  1627. }
  1628. return true;
  1629. };
  1630. Ray.prototype.intersectsBox = function (box) {
  1631. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1632. };
  1633. Ray.prototype.intersectsSphere = function (sphere) {
  1634. var x = sphere.center.x - this.origin.x;
  1635. var y = sphere.center.y - this.origin.y;
  1636. var z = sphere.center.z - this.origin.z;
  1637. var pyth = (x * x) + (y * y) + (z * z);
  1638. var rr = sphere.radius * sphere.radius;
  1639. if (pyth <= rr) {
  1640. return true;
  1641. }
  1642. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1643. if (dot < 0.0) {
  1644. return false;
  1645. }
  1646. var temp = pyth - (dot * dot);
  1647. return temp <= rr;
  1648. };
  1649. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1650. if (!this._edge1) {
  1651. this._edge1 = BABYLON.Vector3.Zero();
  1652. this._edge2 = BABYLON.Vector3.Zero();
  1653. this._pvec = BABYLON.Vector3.Zero();
  1654. this._tvec = BABYLON.Vector3.Zero();
  1655. this._qvec = BABYLON.Vector3.Zero();
  1656. }
  1657. vertex1.subtractToRef(vertex0, this._edge1);
  1658. vertex2.subtractToRef(vertex0, this._edge2);
  1659. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1660. var det = Vector3.Dot(this._edge1, this._pvec);
  1661. if (det === 0) {
  1662. return null;
  1663. }
  1664. var invdet = 1 / det;
  1665. this.origin.subtractToRef(vertex0, this._tvec);
  1666. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1667. if (bu < 0 || bu > 1.0) {
  1668. return null;
  1669. }
  1670. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1671. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1672. if (bv < 0 || bu + bv > 1.0) {
  1673. return null;
  1674. }
  1675. return new BABYLON.IntersectionInfo(bu, bv, Vector3.Dot(this._edge2, this._qvec) * invdet);
  1676. };
  1677. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1678. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1679. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1680. var direction = end.subtract(start);
  1681. direction.normalize();
  1682. return new Ray(start, direction);
  1683. };
  1684. Ray.Transform = function (ray, matrix) {
  1685. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  1686. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  1687. return new Ray(newOrigin, newDirection);
  1688. };
  1689. return Ray;
  1690. })();
  1691. BABYLON.Ray = Ray;
  1692. (function (Space) {
  1693. Space[Space["LOCAL"] = 0] = "LOCAL";
  1694. Space[Space["WORLD"] = 1] = "WORLD";
  1695. })(BABYLON.Space || (BABYLON.Space = {}));
  1696. var Space = BABYLON.Space;
  1697. var Axis = (function () {
  1698. function Axis() {
  1699. }
  1700. Axis.X = new BABYLON.Vector3(1, 0, 0);
  1701. Axis.Y = new BABYLON.Vector3(0, 1, 0);
  1702. Axis.Z = new BABYLON.Vector3(0, 0, 1);
  1703. return Axis;
  1704. })();
  1705. BABYLON.Axis = Axis;
  1706. ;
  1707. })(BABYLON || (BABYLON = {}));
  1708. var BABYLON;
  1709. (function (BABYLON) {
  1710. var screenshotCanvas;
  1711. var fpsRange = 60;
  1712. var previousFramesDuration = [];
  1713. var fps = 60;
  1714. var deltaTime = 0;
  1715. var cloneValue = function (source, destinationObject) {
  1716. if (!source)
  1717. return null;
  1718. if (source instanceof BABYLON.Mesh) {
  1719. return null;
  1720. }
  1721. if (source instanceof BABYLON.SubMesh) {
  1722. return source.clone(destinationObject);
  1723. } else if (source.clone) {
  1724. return source.clone();
  1725. }
  1726. return null;
  1727. };
  1728. var Tools = (function () {
  1729. function Tools() {
  1730. }
  1731. Tools.GetFilename = function (path) {
  1732. var index = path.lastIndexOf("/");
  1733. if (index < 0)
  1734. return path;
  1735. return path.substring(index + 1);
  1736. };
  1737. Tools.GetDOMTextContent = function (element) {
  1738. var result = "";
  1739. var child = element.firstChild;
  1740. while (child) {
  1741. if (child.nodeType == 3) {
  1742. result += child.textContent;
  1743. }
  1744. child = child.nextSibling;
  1745. }
  1746. return result;
  1747. };
  1748. Tools.ToDegrees = function (angle) {
  1749. return angle * 180 / Math.PI;
  1750. };
  1751. Tools.ToRadians = function (angle) {
  1752. return angle * Math.PI / 180;
  1753. };
  1754. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  1755. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1756. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1757. for (var index = indexStart; index < indexStart + indexCount; index++) {
  1758. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  1759. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1760. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1761. }
  1762. return {
  1763. minimum: minimum,
  1764. maximum: maximum
  1765. };
  1766. };
  1767. Tools.ExtractMinAndMax = function (positions, start, count) {
  1768. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1769. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1770. for (var index = start; index < start + count; index++) {
  1771. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  1772. minimum = BABYLON.Vector3.Minimize(current, minimum);
  1773. maximum = BABYLON.Vector3.Maximize(current, maximum);
  1774. }
  1775. return {
  1776. minimum: minimum,
  1777. maximum: maximum
  1778. };
  1779. };
  1780. Tools.MakeArray = function (obj, allowsNullUndefined) {
  1781. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  1782. return undefined;
  1783. return Array.isArray(obj) ? obj : [obj];
  1784. };
  1785. Tools.GetPointerPrefix = function () {
  1786. var eventPrefix = "pointer";
  1787. if (!navigator.pointerEnabled) {
  1788. eventPrefix = "mouse";
  1789. }
  1790. return eventPrefix;
  1791. };
  1792. Tools.QueueNewFrame = function (func) {
  1793. if (window.requestAnimationFrame)
  1794. window.requestAnimationFrame(func);
  1795. else if (window.msRequestAnimationFrame)
  1796. window.msRequestAnimationFrame(func);
  1797. else if (window.webkitRequestAnimationFrame)
  1798. window.webkitRequestAnimationFrame(func);
  1799. else if (window.mozRequestAnimationFrame)
  1800. window.mozRequestAnimationFrame(func);
  1801. else if (window.oRequestAnimationFrame)
  1802. window.oRequestAnimationFrame(func);
  1803. else {
  1804. window.setTimeout(func, 16);
  1805. }
  1806. };
  1807. Tools.RequestFullscreen = function (element) {
  1808. if (element.requestFullscreen)
  1809. element.requestFullscreen();
  1810. else if (element.msRequestFullscreen)
  1811. element.msRequestFullscreen();
  1812. else if (element.webkitRequestFullscreen)
  1813. element.webkitRequestFullscreen();
  1814. else if (element.mozRequestFullScreen)
  1815. element.mozRequestFullScreen();
  1816. };
  1817. Tools.ExitFullscreen = function () {
  1818. if (document.exitFullscreen) {
  1819. document.exitFullscreen();
  1820. } else if (document.mozCancelFullScreen) {
  1821. document.mozCancelFullScreen();
  1822. } else if (document.webkitCancelFullScreen) {
  1823. document.webkitCancelFullScreen();
  1824. } else if (document.msCancelFullScreen) {
  1825. document.msCancelFullScreen();
  1826. }
  1827. };
  1828. Tools.CleanUrl = function (url) {
  1829. url = url.replace(/#/mg, "%23");
  1830. return url;
  1831. };
  1832. Tools.LoadImage = function (url, onload, onerror, database) {
  1833. url = Tools.CleanUrl(url);
  1834. var img = new Image();
  1835. if (url.substr(0, 5) != "data:")
  1836. img.crossOrigin = 'anonymous';
  1837. img.onload = function () {
  1838. onload(img);
  1839. };
  1840. img.onerror = function (err) {
  1841. onerror(img, err);
  1842. };
  1843. var noIndexedDB = function () {
  1844. img.src = url;
  1845. };
  1846. var loadFromIndexedDB = function () {
  1847. database.loadImageFromDB(url, img);
  1848. };
  1849. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  1850. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1851. } else {
  1852. if (url.indexOf("file:") === -1) {
  1853. noIndexedDB();
  1854. } else {
  1855. try {
  1856. var textureName = url.substring(5);
  1857. var blobURL;
  1858. try {
  1859. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  1860. } catch (ex) {
  1861. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  1862. }
  1863. img.src = blobURL;
  1864. } catch (e) {
  1865. Tools.Log("Error while trying to load texture: " + textureName);
  1866. img.src = null;
  1867. }
  1868. }
  1869. }
  1870. return img;
  1871. };
  1872. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  1873. url = Tools.CleanUrl(url);
  1874. var noIndexedDB = function () {
  1875. var request = new XMLHttpRequest();
  1876. var loadUrl = Tools.BaseUrl + url;
  1877. request.open('GET', loadUrl, true);
  1878. if (useArrayBuffer) {
  1879. request.responseType = "arraybuffer";
  1880. }
  1881. request.onprogress = progressCallBack;
  1882. request.onreadystatechange = function () {
  1883. if (request.readyState == 4) {
  1884. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  1885. callback(!useArrayBuffer ? request.responseText : request.response);
  1886. } else {
  1887. if (onError) {
  1888. onError();
  1889. } else {
  1890. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  1891. }
  1892. }
  1893. }
  1894. };
  1895. request.send(null);
  1896. };
  1897. var loadFromIndexedDB = function () {
  1898. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  1899. };
  1900. if (url.indexOf("file:") !== -1) {
  1901. var fileName = url.substring(5);
  1902. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  1903. } else {
  1904. if (database && database.enableSceneOffline) {
  1905. database.openAsync(loadFromIndexedDB, noIndexedDB);
  1906. } else {
  1907. noIndexedDB();
  1908. }
  1909. }
  1910. };
  1911. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  1912. var reader = new FileReader();
  1913. reader.onload = function (e) {
  1914. callback(e.target.result);
  1915. };
  1916. reader.onprogress = progressCallback;
  1917. reader.readAsDataURL(fileToLoad);
  1918. };
  1919. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  1920. var reader = new FileReader();
  1921. reader.onload = function (e) {
  1922. callback(e.target.result);
  1923. };
  1924. reader.onprogress = progressCallBack;
  1925. if (!useArrayBuffer) {
  1926. reader.readAsText(fileToLoad);
  1927. } else {
  1928. reader.readAsArrayBuffer(fileToLoad);
  1929. }
  1930. };
  1931. Tools.CheckExtends = function (v, min, max) {
  1932. if (v.x < min.x)
  1933. min.x = v.x;
  1934. if (v.y < min.y)
  1935. min.y = v.y;
  1936. if (v.z < min.z)
  1937. min.z = v.z;
  1938. if (v.x > max.x)
  1939. max.x = v.x;
  1940. if (v.y > max.y)
  1941. max.y = v.y;
  1942. if (v.z > max.z)
  1943. max.z = v.z;
  1944. };
  1945. Tools.WithinEpsilon = function (a, b) {
  1946. var num = a - b;
  1947. return -1.401298E-45 <= num && num <= 1.401298E-45;
  1948. };
  1949. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  1950. for (var prop in source) {
  1951. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  1952. continue;
  1953. }
  1954. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  1955. continue;
  1956. }
  1957. var sourceValue = source[prop];
  1958. var typeOfSourceValue = typeof sourceValue;
  1959. if (typeOfSourceValue == "function") {
  1960. continue;
  1961. }
  1962. if (typeOfSourceValue == "object") {
  1963. if (sourceValue instanceof Array) {
  1964. destination[prop] = [];
  1965. if (sourceValue.length > 0) {
  1966. if (typeof sourceValue[0] == "object") {
  1967. for (var index = 0; index < sourceValue.length; index++) {
  1968. var clonedValue = cloneValue(sourceValue[index], destination);
  1969. if (destination[prop].indexOf(clonedValue) === -1) {
  1970. destination[prop].push(clonedValue);
  1971. }
  1972. }
  1973. } else {
  1974. destination[prop] = sourceValue.slice(0);
  1975. }
  1976. }
  1977. } else {
  1978. destination[prop] = cloneValue(sourceValue, destination);
  1979. }
  1980. } else {
  1981. destination[prop] = sourceValue;
  1982. }
  1983. }
  1984. };
  1985. Tools.IsEmpty = function (obj) {
  1986. for (var i in obj) {
  1987. return false;
  1988. }
  1989. return true;
  1990. };
  1991. Tools.RegisterTopRootEvents = function (events) {
  1992. for (var index = 0; index < events.length; index++) {
  1993. var event = events[index];
  1994. window.addEventListener(event.name, event.handler, false);
  1995. try {
  1996. if (window.parent) {
  1997. window.parent.addEventListener(event.name, event.handler, false);
  1998. }
  1999. } catch (e) {
  2000. }
  2001. }
  2002. };
  2003. Tools.UnregisterTopRootEvents = function (events) {
  2004. for (var index = 0; index < events.length; index++) {
  2005. var event = events[index];
  2006. window.removeEventListener(event.name, event.handler);
  2007. try {
  2008. if (window.parent) {
  2009. window.parent.removeEventListener(event.name, event.handler);
  2010. }
  2011. } catch (e) {
  2012. }
  2013. }
  2014. };
  2015. Tools.GetFps = function () {
  2016. return fps;
  2017. };
  2018. Tools.GetDeltaTime = function () {
  2019. return deltaTime;
  2020. };
  2021. Tools._MeasureFps = function () {
  2022. previousFramesDuration.push(Tools.Now);
  2023. var length = previousFramesDuration.length;
  2024. if (length >= 2) {
  2025. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  2026. }
  2027. if (length >= fpsRange) {
  2028. if (length > fpsRange) {
  2029. previousFramesDuration.splice(0, 1);
  2030. length = previousFramesDuration.length;
  2031. }
  2032. var sum = 0;
  2033. for (var id = 0; id < length - 1; id++) {
  2034. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  2035. }
  2036. fps = 1000.0 / (sum / (length - 1));
  2037. }
  2038. };
  2039. Tools.CreateScreenshot = function (engine, camera, size) {
  2040. var width;
  2041. var height;
  2042. var scene = camera.getScene();
  2043. var previousCamera = null;
  2044. if (scene.activeCamera !== camera) {
  2045. previousCamera = scene.activeCamera;
  2046. scene.activeCamera = camera;
  2047. }
  2048. if (size.precision) {
  2049. width = Math.round(engine.getRenderWidth() * size.precision);
  2050. height = Math.round(width / engine.getAspectRatio(camera));
  2051. size = { width: width, height: height };
  2052. } else if (size.width && size.height) {
  2053. width = size.width;
  2054. height = size.height;
  2055. } else if (size.width && !size.height) {
  2056. width = size.width;
  2057. height = Math.round(width / engine.getAspectRatio(camera));
  2058. size = { width: width, height: height };
  2059. } else if (size.height && !size.width) {
  2060. height = size.height;
  2061. width = Math.round(height * engine.getAspectRatio(camera));
  2062. size = { width: width, height: height };
  2063. } else if (!isNaN(size)) {
  2064. height = size;
  2065. width = size;
  2066. } else {
  2067. Tools.Error("Invalid 'size' parameter !");
  2068. return;
  2069. }
  2070. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2071. texture.renderList = engine.scenes[0].meshes;
  2072. texture.onAfterRender = function () {
  2073. var numberOfChannelsByLine = width * 4;
  2074. var halfHeight = height / 2;
  2075. var data = engine.readPixels(0, 0, width, height);
  2076. for (var i = 0; i < halfHeight; i++) {
  2077. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2078. var currentCell = j + i * numberOfChannelsByLine;
  2079. var targetLine = height - i - 1;
  2080. var targetCell = j + targetLine * numberOfChannelsByLine;
  2081. var temp = data[currentCell];
  2082. data[currentCell] = data[targetCell];
  2083. data[targetCell] = temp;
  2084. }
  2085. }
  2086. if (!screenshotCanvas) {
  2087. screenshotCanvas = document.createElement('canvas');
  2088. }
  2089. screenshotCanvas.width = width;
  2090. screenshotCanvas.height = height;
  2091. var context = screenshotCanvas.getContext('2d');
  2092. var imageData = context.createImageData(width, height);
  2093. imageData.data.set(data);
  2094. context.putImageData(imageData, 0, 0);
  2095. var base64Image = screenshotCanvas.toDataURL();
  2096. if (("download" in document.createElement("a"))) {
  2097. var a = window.document.createElement("a");
  2098. a.href = base64Image;
  2099. var date = new Date();
  2100. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2101. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2102. window.document.body.appendChild(a);
  2103. a.addEventListener("click", function () {
  2104. a.parentElement.removeChild(a);
  2105. });
  2106. a.click();
  2107. } else {
  2108. var newWindow = window.open("");
  2109. var img = newWindow.document.createElement("img");
  2110. img.src = base64Image;
  2111. newWindow.document.body.appendChild(img);
  2112. }
  2113. };
  2114. texture.render(true);
  2115. texture.dispose();
  2116. if (previousCamera) {
  2117. scene.activeCamera = previousCamera;
  2118. }
  2119. };
  2120. Tools.ValidateXHRData = function (xhr, dataType) {
  2121. if (typeof dataType === "undefined") { dataType = 7; }
  2122. try {
  2123. if (dataType & 1) {
  2124. if (xhr.responseText && xhr.responseText.length > 0) {
  2125. return true;
  2126. } else if (dataType === 1) {
  2127. return false;
  2128. }
  2129. }
  2130. if (dataType & 2) {
  2131. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2132. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2133. return true;
  2134. } else if (dataType === 2) {
  2135. return false;
  2136. }
  2137. }
  2138. if (dataType & 4) {
  2139. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2140. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2141. return true;
  2142. } else {
  2143. return false;
  2144. }
  2145. }
  2146. } catch (e) {
  2147. }
  2148. return false;
  2149. };
  2150. Object.defineProperty(Tools, "NoneLogLevel", {
  2151. get: function () {
  2152. return Tools._NoneLogLevel;
  2153. },
  2154. enumerable: true,
  2155. configurable: true
  2156. });
  2157. Object.defineProperty(Tools, "MessageLogLevel", {
  2158. get: function () {
  2159. return Tools._MessageLogLevel;
  2160. },
  2161. enumerable: true,
  2162. configurable: true
  2163. });
  2164. Object.defineProperty(Tools, "WarningLogLevel", {
  2165. get: function () {
  2166. return Tools._WarningLogLevel;
  2167. },
  2168. enumerable: true,
  2169. configurable: true
  2170. });
  2171. Object.defineProperty(Tools, "ErrorLogLevel", {
  2172. get: function () {
  2173. return Tools._ErrorLogLevel;
  2174. },
  2175. enumerable: true,
  2176. configurable: true
  2177. });
  2178. Object.defineProperty(Tools, "AllLogLevel", {
  2179. get: function () {
  2180. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2181. },
  2182. enumerable: true,
  2183. configurable: true
  2184. });
  2185. Tools._FormatMessage = function (message) {
  2186. var padStr = function (i) {
  2187. return (i < 10) ? "0" + i : "" + i;
  2188. };
  2189. var date = new Date();
  2190. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2191. };
  2192. Tools._LogDisabled = function (message) {
  2193. };
  2194. Tools._LogEnabled = function (message) {
  2195. console.log(Tools._FormatMessage(message));
  2196. };
  2197. Tools._WarnDisabled = function (message) {
  2198. };
  2199. Tools._WarnEnabled = function (message) {
  2200. console.warn(Tools._FormatMessage(message));
  2201. };
  2202. Tools._ErrorDisabled = function (message) {
  2203. };
  2204. Tools._ErrorEnabled = function (message) {
  2205. console.error(Tools._FormatMessage(message));
  2206. };
  2207. Object.defineProperty(Tools, "LogLevels", {
  2208. set: function (level) {
  2209. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2210. Tools.Log = Tools._LogEnabled;
  2211. } else {
  2212. Tools.Log = Tools._LogDisabled;
  2213. }
  2214. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2215. Tools.Warn = Tools._WarnEnabled;
  2216. } else {
  2217. Tools.Warn = Tools._WarnDisabled;
  2218. }
  2219. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2220. Tools.Error = Tools._ErrorEnabled;
  2221. } else {
  2222. Tools.Error = Tools._ErrorDisabled;
  2223. }
  2224. },
  2225. enumerable: true,
  2226. configurable: true
  2227. });
  2228. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2229. get: function () {
  2230. return Tools._PerformanceNoneLogLevel;
  2231. },
  2232. enumerable: true,
  2233. configurable: true
  2234. });
  2235. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2236. get: function () {
  2237. return Tools._PerformanceUserMarkLogLevel;
  2238. },
  2239. enumerable: true,
  2240. configurable: true
  2241. });
  2242. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2243. get: function () {
  2244. return Tools._PerformanceConsoleLogLevel;
  2245. },
  2246. enumerable: true,
  2247. configurable: true
  2248. });
  2249. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2250. set: function (level) {
  2251. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2252. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2253. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2254. return;
  2255. }
  2256. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2257. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2258. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2259. return;
  2260. }
  2261. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2262. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2263. },
  2264. enumerable: true,
  2265. configurable: true
  2266. });
  2267. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2268. };
  2269. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2270. };
  2271. Tools._StartUserMark = function (counterName, condition) {
  2272. if (typeof condition === "undefined") { condition = true; }
  2273. if (!condition || !Tools._performance.mark) {
  2274. return;
  2275. }
  2276. Tools._performance.mark(counterName + "-Begin");
  2277. };
  2278. Tools._EndUserMark = function (counterName, condition) {
  2279. if (typeof condition === "undefined") { condition = true; }
  2280. if (!condition || !Tools._performance.mark) {
  2281. return;
  2282. }
  2283. Tools._performance.mark(counterName + "-End");
  2284. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2285. };
  2286. Tools._StartPerformanceConsole = function (counterName, condition) {
  2287. if (typeof condition === "undefined") { condition = true; }
  2288. if (!condition) {
  2289. return;
  2290. }
  2291. Tools._StartUserMark(counterName, condition);
  2292. if (console.time) {
  2293. console.time(counterName);
  2294. }
  2295. };
  2296. Tools._EndPerformanceConsole = function (counterName, condition) {
  2297. if (typeof condition === "undefined") { condition = true; }
  2298. if (!condition) {
  2299. return;
  2300. }
  2301. Tools._EndUserMark(counterName, condition);
  2302. if (console.time) {
  2303. console.timeEnd(counterName);
  2304. }
  2305. };
  2306. Object.defineProperty(Tools, "Now", {
  2307. get: function () {
  2308. if (window.performance.now) {
  2309. return window.performance.now();
  2310. }
  2311. return new Date().getTime();
  2312. },
  2313. enumerable: true,
  2314. configurable: true
  2315. });
  2316. Tools.BaseUrl = "";
  2317. Tools.GetExponantOfTwo = function (value, max) {
  2318. var count = 1;
  2319. do {
  2320. count *= 2;
  2321. } while(count < value);
  2322. if (count > max)
  2323. count = max;
  2324. return count;
  2325. };
  2326. Tools._NoneLogLevel = 0;
  2327. Tools._MessageLogLevel = 1;
  2328. Tools._WarningLogLevel = 2;
  2329. Tools._ErrorLogLevel = 4;
  2330. Tools.Log = Tools._LogEnabled;
  2331. Tools.Warn = Tools._WarnEnabled;
  2332. Tools.Error = Tools._ErrorEnabled;
  2333. Tools._PerformanceNoneLogLevel = 0;
  2334. Tools._PerformanceUserMarkLogLevel = 1;
  2335. Tools._PerformanceConsoleLogLevel = 2;
  2336. Tools._performance = window.performance;
  2337. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2338. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2339. return Tools;
  2340. })();
  2341. BABYLON.Tools = Tools;
  2342. })(BABYLON || (BABYLON = {}));
  2343. var BABYLON;
  2344. (function (BABYLON) {
  2345. var _DepthCullingState = (function () {
  2346. function _DepthCullingState() {
  2347. this._isDepthTestDirty = false;
  2348. this._isDepthMaskDirty = false;
  2349. this._isDepthFuncDirty = false;
  2350. this._isCullFaceDirty = false;
  2351. this._isCullDirty = false;
  2352. }
  2353. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2354. get: function () {
  2355. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2356. },
  2357. enumerable: true,
  2358. configurable: true
  2359. });
  2360. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2361. get: function () {
  2362. return this._cullFace;
  2363. },
  2364. set: function (value) {
  2365. if (this._cullFace === value) {
  2366. return;
  2367. }
  2368. this._cullFace = value;
  2369. this._isCullFaceDirty = true;
  2370. },
  2371. enumerable: true,
  2372. configurable: true
  2373. });
  2374. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2375. get: function () {
  2376. return this._cull;
  2377. },
  2378. set: function (value) {
  2379. if (this._cull === value) {
  2380. return;
  2381. }
  2382. this._cull = value;
  2383. this._isCullDirty = true;
  2384. },
  2385. enumerable: true,
  2386. configurable: true
  2387. });
  2388. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2389. get: function () {
  2390. return this._depthFunc;
  2391. },
  2392. set: function (value) {
  2393. if (this._depthFunc === value) {
  2394. return;
  2395. }
  2396. this._depthFunc = value;
  2397. this._isDepthFuncDirty = true;
  2398. },
  2399. enumerable: true,
  2400. configurable: true
  2401. });
  2402. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2403. get: function () {
  2404. return this._depthMask;
  2405. },
  2406. set: function (value) {
  2407. if (this._depthMask === value) {
  2408. return;
  2409. }
  2410. this._depthMask = value;
  2411. this._isDepthMaskDirty = true;
  2412. },
  2413. enumerable: true,
  2414. configurable: true
  2415. });
  2416. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  2417. get: function () {
  2418. return this._depthTest;
  2419. },
  2420. set: function (value) {
  2421. if (this._depthTest === value) {
  2422. return;
  2423. }
  2424. this._depthTest = value;
  2425. this._isDepthTestDirty = true;
  2426. },
  2427. enumerable: true,
  2428. configurable: true
  2429. });
  2430. _DepthCullingState.prototype.reset = function () {
  2431. this._depthMask = true;
  2432. this._depthTest = true;
  2433. this._depthFunc = null;
  2434. this._cull = null;
  2435. this._cullFace = null;
  2436. this._isDepthTestDirty = true;
  2437. this._isDepthMaskDirty = true;
  2438. this._isDepthFuncDirty = false;
  2439. this._isCullFaceDirty = false;
  2440. this._isCullDirty = false;
  2441. };
  2442. _DepthCullingState.prototype.apply = function (gl) {
  2443. if (!this.isDirty) {
  2444. return;
  2445. }
  2446. if (this._isCullDirty) {
  2447. if (this.cull === true) {
  2448. gl.enable(gl.CULL_FACE);
  2449. } else if (this.cull === false) {
  2450. gl.disable(gl.CULL_FACE);
  2451. }
  2452. this._isCullDirty = false;
  2453. }
  2454. if (this._isCullFaceDirty) {
  2455. gl.cullFace(this.cullFace);
  2456. this._isCullFaceDirty = false;
  2457. }
  2458. if (this._isDepthMaskDirty) {
  2459. gl.depthMask(this.depthMask);
  2460. this._isDepthMaskDirty = false;
  2461. }
  2462. if (this._isDepthTestDirty) {
  2463. if (this.depthTest === true) {
  2464. gl.enable(gl.DEPTH_TEST);
  2465. } else if (this.depthTest === false) {
  2466. gl.disable(gl.DEPTH_TEST);
  2467. }
  2468. this._isDepthTestDirty = false;
  2469. }
  2470. if (this._isDepthFuncDirty) {
  2471. gl.depthFunc(this.depthFunc);
  2472. this._isDepthFuncDirty = false;
  2473. }
  2474. };
  2475. return _DepthCullingState;
  2476. })();
  2477. BABYLON._DepthCullingState = _DepthCullingState;
  2478. var _AlphaState = (function () {
  2479. function _AlphaState() {
  2480. this._isAlphaBlendDirty = false;
  2481. this._isBlendFunctionParametersDirty = false;
  2482. this._alphaBlend = false;
  2483. this._blendFunctionParameters = new Array(4);
  2484. }
  2485. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  2486. get: function () {
  2487. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  2488. },
  2489. enumerable: true,
  2490. configurable: true
  2491. });
  2492. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  2493. get: function () {
  2494. return this._alphaBlend;
  2495. },
  2496. set: function (value) {
  2497. if (this._alphaBlend === value) {
  2498. return;
  2499. }
  2500. this._alphaBlend = value;
  2501. this._isAlphaBlendDirty = true;
  2502. },
  2503. enumerable: true,
  2504. configurable: true
  2505. });
  2506. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  2507. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  2508. return;
  2509. }
  2510. this._blendFunctionParameters[0] = value0;
  2511. this._blendFunctionParameters[1] = value1;
  2512. this._blendFunctionParameters[2] = value2;
  2513. this._blendFunctionParameters[3] = value3;
  2514. this._isBlendFunctionParametersDirty = true;
  2515. };
  2516. _AlphaState.prototype.reset = function () {
  2517. this._alphaBlend = false;
  2518. this._blendFunctionParameters[0] = null;
  2519. this._blendFunctionParameters[1] = null;
  2520. this._blendFunctionParameters[2] = null;
  2521. this._blendFunctionParameters[3] = null;
  2522. this._isAlphaBlendDirty = true;
  2523. this._isBlendFunctionParametersDirty = false;
  2524. };
  2525. _AlphaState.prototype.apply = function (gl) {
  2526. if (!this.isDirty) {
  2527. return;
  2528. }
  2529. if (this._isAlphaBlendDirty) {
  2530. if (this._alphaBlend === true) {
  2531. gl.enable(gl.BLEND);
  2532. } else if (this._alphaBlend === false) {
  2533. gl.disable(gl.BLEND);
  2534. }
  2535. this._isAlphaBlendDirty = false;
  2536. }
  2537. if (this._isBlendFunctionParametersDirty) {
  2538. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  2539. this._isBlendFunctionParametersDirty = false;
  2540. }
  2541. };
  2542. return _AlphaState;
  2543. })();
  2544. BABYLON._AlphaState = _AlphaState;
  2545. var compileShader = function (gl, source, type, defines) {
  2546. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2547. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  2548. gl.compileShader(shader);
  2549. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2550. throw new Error(gl.getShaderInfoLog(shader));
  2551. }
  2552. return shader;
  2553. };
  2554. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  2555. var magFilter = gl.NEAREST;
  2556. var minFilter = gl.NEAREST;
  2557. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  2558. magFilter = gl.LINEAR;
  2559. if (generateMipMaps) {
  2560. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2561. } else {
  2562. minFilter = gl.LINEAR;
  2563. }
  2564. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  2565. magFilter = gl.LINEAR;
  2566. if (generateMipMaps) {
  2567. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2568. } else {
  2569. minFilter = gl.LINEAR;
  2570. }
  2571. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  2572. magFilter = gl.NEAREST;
  2573. if (generateMipMaps) {
  2574. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2575. } else {
  2576. minFilter = gl.NEAREST;
  2577. }
  2578. }
  2579. return {
  2580. min: minFilter,
  2581. mag: magFilter
  2582. };
  2583. };
  2584. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  2585. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  2586. var engine = scene.getEngine();
  2587. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  2588. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  2589. gl.bindTexture(gl.TEXTURE_2D, texture);
  2590. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2591. processFunction(potWidth, potHeight);
  2592. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  2593. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2594. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2595. if (!noMipmap && !isCompressed) {
  2596. gl.generateMipmap(gl.TEXTURE_2D);
  2597. }
  2598. gl.bindTexture(gl.TEXTURE_2D, null);
  2599. engine._activeTexturesCache = [];
  2600. texture._baseWidth = width;
  2601. texture._baseHeight = height;
  2602. texture._width = potWidth;
  2603. texture._height = potHeight;
  2604. texture.isReady = true;
  2605. scene._removePendingData(texture);
  2606. };
  2607. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  2608. var img;
  2609. var onload = function () {
  2610. loadedImages[index] = img;
  2611. loadedImages._internalCount++;
  2612. scene._removePendingData(img);
  2613. if (loadedImages._internalCount == 6) {
  2614. onfinish(loadedImages);
  2615. }
  2616. };
  2617. var onerror = function () {
  2618. scene._removePendingData(img);
  2619. };
  2620. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  2621. scene._addPendingData(img);
  2622. };
  2623. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  2624. var loadedImages = [];
  2625. loadedImages._internalCount = 0;
  2626. for (var index = 0; index < 6; index++) {
  2627. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  2628. }
  2629. };
  2630. var EngineCapabilities = (function () {
  2631. function EngineCapabilities() {
  2632. }
  2633. return EngineCapabilities;
  2634. })();
  2635. BABYLON.EngineCapabilities = EngineCapabilities;
  2636. var Engine = (function () {
  2637. function Engine(canvas, antialias, options) {
  2638. var _this = this;
  2639. this.isFullscreen = false;
  2640. this.isPointerLock = false;
  2641. this.forceWireframe = false;
  2642. this.cullBackFaces = true;
  2643. this.renderEvenInBackground = true;
  2644. this.scenes = new Array();
  2645. this._windowIsBackground = false;
  2646. this._runningLoop = false;
  2647. this._loadingDivBackgroundColor = "black";
  2648. this._depthCullingState = new _DepthCullingState();
  2649. this._alphaState = new _AlphaState();
  2650. this._loadedTexturesCache = new Array();
  2651. this._activeTexturesCache = new Array();
  2652. this._compiledEffects = {};
  2653. this._renderingCanvas = canvas;
  2654. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2655. options = options || {};
  2656. options.antialias = antialias;
  2657. try {
  2658. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  2659. } catch (e) {
  2660. throw new Error("WebGL not supported");
  2661. }
  2662. if (!this._gl) {
  2663. throw new Error("WebGL not supported");
  2664. }
  2665. this._onBlur = function () {
  2666. _this._windowIsBackground = true;
  2667. };
  2668. this._onFocus = function () {
  2669. _this._windowIsBackground = false;
  2670. };
  2671. window.addEventListener("blur", this._onBlur);
  2672. window.addEventListener("focus", this._onFocus);
  2673. this._workingCanvas = document.createElement("canvas");
  2674. this._workingContext = this._workingCanvas.getContext("2d");
  2675. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  2676. this.resize();
  2677. this._caps = new EngineCapabilities();
  2678. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  2679. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  2680. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  2681. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  2682. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  2683. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  2684. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  2685. 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');
  2686. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  2687. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  2688. this.setDepthBuffer(true);
  2689. this.setDepthFunctionToLessOrEqual();
  2690. this.setDepthWrite(true);
  2691. this._onFullscreenChange = function () {
  2692. if (document.fullscreen !== undefined) {
  2693. _this.isFullscreen = document.fullscreen;
  2694. } else if (document.mozFullScreen !== undefined) {
  2695. _this.isFullscreen = document.mozFullScreen;
  2696. } else if (document.webkitIsFullScreen !== undefined) {
  2697. _this.isFullscreen = document.webkitIsFullScreen;
  2698. } else if (document.msIsFullScreen !== undefined) {
  2699. _this.isFullscreen = document.msIsFullScreen;
  2700. }
  2701. if (_this.isFullscreen && _this._pointerLockRequested) {
  2702. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  2703. if (canvas.requestPointerLock) {
  2704. canvas.requestPointerLock();
  2705. }
  2706. }
  2707. };
  2708. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  2709. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  2710. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  2711. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  2712. this._onPointerLockChange = function () {
  2713. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  2714. };
  2715. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  2716. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  2717. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  2718. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  2719. }
  2720. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  2721. get: function () {
  2722. return Engine._ALPHA_DISABLE;
  2723. },
  2724. enumerable: true,
  2725. configurable: true
  2726. });
  2727. Object.defineProperty(Engine, "ALPHA_ADD", {
  2728. get: function () {
  2729. return Engine._ALPHA_ADD;
  2730. },
  2731. enumerable: true,
  2732. configurable: true
  2733. });
  2734. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  2735. get: function () {
  2736. return Engine._ALPHA_COMBINE;
  2737. },
  2738. enumerable: true,
  2739. configurable: true
  2740. });
  2741. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  2742. get: function () {
  2743. return Engine._DELAYLOADSTATE_NONE;
  2744. },
  2745. enumerable: true,
  2746. configurable: true
  2747. });
  2748. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  2749. get: function () {
  2750. return Engine._DELAYLOADSTATE_LOADED;
  2751. },
  2752. enumerable: true,
  2753. configurable: true
  2754. });
  2755. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  2756. get: function () {
  2757. return Engine._DELAYLOADSTATE_LOADING;
  2758. },
  2759. enumerable: true,
  2760. configurable: true
  2761. });
  2762. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  2763. get: function () {
  2764. return Engine._DELAYLOADSTATE_NOTLOADED;
  2765. },
  2766. enumerable: true,
  2767. configurable: true
  2768. });
  2769. Object.defineProperty(Engine, "Version", {
  2770. get: function () {
  2771. return "2.0.0";
  2772. },
  2773. enumerable: true,
  2774. configurable: true
  2775. });
  2776. Engine.prototype.getAspectRatio = function (camera) {
  2777. var viewport = camera.viewport;
  2778. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  2779. };
  2780. Engine.prototype.getRenderWidth = function () {
  2781. if (this._currentRenderTarget) {
  2782. return this._currentRenderTarget._width;
  2783. }
  2784. return this._renderingCanvas.width;
  2785. };
  2786. Engine.prototype.getRenderHeight = function () {
  2787. if (this._currentRenderTarget) {
  2788. return this._currentRenderTarget._height;
  2789. }
  2790. return this._renderingCanvas.height;
  2791. };
  2792. Engine.prototype.getRenderingCanvas = function () {
  2793. return this._renderingCanvas;
  2794. };
  2795. Engine.prototype.getRenderingCanvasClientRect = function () {
  2796. return this._renderingCanvas.getBoundingClientRect();
  2797. };
  2798. Engine.prototype.setHardwareScalingLevel = function (level) {
  2799. this._hardwareScalingLevel = level;
  2800. this.resize();
  2801. };
  2802. Engine.prototype.getHardwareScalingLevel = function () {
  2803. return this._hardwareScalingLevel;
  2804. };
  2805. Engine.prototype.getLoadedTexturesCache = function () {
  2806. return this._loadedTexturesCache;
  2807. };
  2808. Engine.prototype.getCaps = function () {
  2809. return this._caps;
  2810. };
  2811. Engine.prototype.setDepthFunctionToGreater = function () {
  2812. this._depthCullingState.depthFunc = this._gl.GREATER;
  2813. };
  2814. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  2815. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  2816. };
  2817. Engine.prototype.setDepthFunctionToLess = function () {
  2818. this._depthCullingState.depthFunc = this._gl.LESS;
  2819. };
  2820. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  2821. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  2822. };
  2823. Engine.prototype.stopRenderLoop = function () {
  2824. this._renderFunction = null;
  2825. this._runningLoop = false;
  2826. };
  2827. Engine.prototype._renderLoop = function () {
  2828. var _this = this;
  2829. var shouldRender = true;
  2830. if (!this.renderEvenInBackground && this._windowIsBackground) {
  2831. shouldRender = false;
  2832. }
  2833. if (shouldRender) {
  2834. this.beginFrame();
  2835. if (this._renderFunction) {
  2836. this._renderFunction();
  2837. }
  2838. this.endFrame();
  2839. }
  2840. if (this._runningLoop) {
  2841. BABYLON.Tools.QueueNewFrame(function () {
  2842. _this._renderLoop();
  2843. });
  2844. }
  2845. };
  2846. Engine.prototype.runRenderLoop = function (renderFunction) {
  2847. var _this = this;
  2848. this._runningLoop = true;
  2849. this._renderFunction = renderFunction;
  2850. BABYLON.Tools.QueueNewFrame(function () {
  2851. _this._renderLoop();
  2852. });
  2853. };
  2854. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  2855. if (this.isFullscreen) {
  2856. BABYLON.Tools.ExitFullscreen();
  2857. } else {
  2858. this._pointerLockRequested = requestPointerLock;
  2859. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  2860. }
  2861. };
  2862. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  2863. this.applyStates();
  2864. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  2865. if (this._depthCullingState.depthMask) {
  2866. this._gl.clearDepth(1.0);
  2867. }
  2868. var mode = 0;
  2869. if (backBuffer)
  2870. mode |= this._gl.COLOR_BUFFER_BIT;
  2871. if (depthStencil && this._depthCullingState.depthMask)
  2872. mode |= this._gl.DEPTH_BUFFER_BIT;
  2873. this._gl.clear(mode);
  2874. };
  2875. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  2876. var width = requiredWidth || this._renderingCanvas.width;
  2877. var height = requiredHeight || this._renderingCanvas.height;
  2878. var x = viewport.x || 0;
  2879. var y = viewport.y || 0;
  2880. this._cachedViewport = viewport;
  2881. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  2882. };
  2883. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  2884. this._cachedViewport = null;
  2885. this._gl.viewport(x, y, width, height);
  2886. };
  2887. Engine.prototype.beginFrame = function () {
  2888. BABYLON.Tools._MeasureFps();
  2889. };
  2890. Engine.prototype.endFrame = function () {
  2891. this.flushFramebuffer();
  2892. };
  2893. Engine.prototype.resize = function () {
  2894. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  2895. };
  2896. Engine.prototype.setSize = function (width, height) {
  2897. this._renderingCanvas.width = width;
  2898. this._renderingCanvas.height = height;
  2899. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2900. };
  2901. Engine.prototype.bindFramebuffer = function (texture) {
  2902. this._currentRenderTarget = texture;
  2903. var gl = this._gl;
  2904. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  2905. this._gl.viewport(0, 0, texture._width, texture._height);
  2906. this.wipeCaches();
  2907. };
  2908. Engine.prototype.unBindFramebuffer = function (texture) {
  2909. this._currentRenderTarget = null;
  2910. if (texture.generateMipMaps) {
  2911. var gl = this._gl;
  2912. gl.bindTexture(gl.TEXTURE_2D, texture);
  2913. gl.generateMipmap(gl.TEXTURE_2D);
  2914. gl.bindTexture(gl.TEXTURE_2D, null);
  2915. }
  2916. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2917. };
  2918. Engine.prototype.flushFramebuffer = function () {
  2919. this._gl.flush();
  2920. };
  2921. Engine.prototype.restoreDefaultFramebuffer = function () {
  2922. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  2923. this.setViewport(this._cachedViewport);
  2924. this.wipeCaches();
  2925. };
  2926. Engine.prototype._resetVertexBufferBinding = function () {
  2927. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  2928. this._cachedVertexBuffers = null;
  2929. };
  2930. Engine.prototype.createVertexBuffer = function (vertices) {
  2931. var vbo = this._gl.createBuffer();
  2932. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2933. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  2934. this._resetVertexBufferBinding();
  2935. vbo.references = 1;
  2936. return vbo;
  2937. };
  2938. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  2939. var vbo = this._gl.createBuffer();
  2940. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  2941. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2942. this._resetVertexBufferBinding();
  2943. vbo.references = 1;
  2944. return vbo;
  2945. };
  2946. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, length) {
  2947. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2948. if (vertices instanceof Float32Array) {
  2949. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  2950. } else {
  2951. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  2952. }
  2953. this._resetVertexBufferBinding();
  2954. };
  2955. Engine.prototype._resetIndexBufferBinding = function () {
  2956. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  2957. this._cachedIndexBuffer = null;
  2958. };
  2959. Engine.prototype.createIndexBuffer = function (indices) {
  2960. var vbo = this._gl.createBuffer();
  2961. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  2962. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  2963. this._resetIndexBufferBinding();
  2964. vbo.references = 1;
  2965. return vbo;
  2966. };
  2967. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  2968. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  2969. this._cachedVertexBuffers = vertexBuffer;
  2970. this._cachedEffectForVertexBuffers = effect;
  2971. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  2972. var offset = 0;
  2973. for (var index = 0; index < vertexDeclaration.length; index++) {
  2974. var order = effect.getAttributeLocation(index);
  2975. if (order >= 0) {
  2976. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  2977. }
  2978. offset += vertexDeclaration[index] * 4;
  2979. }
  2980. }
  2981. if (this._cachedIndexBuffer !== indexBuffer) {
  2982. this._cachedIndexBuffer = indexBuffer;
  2983. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  2984. }
  2985. };
  2986. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  2987. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  2988. this._cachedVertexBuffers = vertexBuffers;
  2989. this._cachedEffectForVertexBuffers = effect;
  2990. var attributes = effect.getAttributesNames();
  2991. for (var index = 0; index < attributes.length; index++) {
  2992. var order = effect.getAttributeLocation(index);
  2993. if (order >= 0) {
  2994. var vertexBuffer = vertexBuffers[attributes[index]];
  2995. if (!vertexBuffer) {
  2996. continue;
  2997. }
  2998. var stride = vertexBuffer.getStrideSize();
  2999. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3000. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3001. }
  3002. }
  3003. }
  3004. if (this._cachedIndexBuffer !== indexBuffer) {
  3005. this._cachedIndexBuffer = indexBuffer;
  3006. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3007. }
  3008. };
  3009. Engine.prototype._releaseBuffer = function (buffer) {
  3010. buffer.references--;
  3011. if (buffer.references === 0) {
  3012. this._gl.deleteBuffer(buffer);
  3013. return true;
  3014. }
  3015. return false;
  3016. };
  3017. Engine.prototype.createInstancesBuffer = function (capacity) {
  3018. var buffer = this._gl.createBuffer();
  3019. buffer.capacity = capacity;
  3020. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3021. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3022. return buffer;
  3023. };
  3024. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3025. this._gl.deleteBuffer(buffer);
  3026. };
  3027. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3028. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3029. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3030. for (var index = 0; index < 4; index++) {
  3031. var offsetLocation = offsetLocations[index];
  3032. this._gl.enableVertexAttribArray(offsetLocation);
  3033. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3034. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3035. }
  3036. };
  3037. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3038. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3039. for (var index = 0; index < 4; index++) {
  3040. var offsetLocation = offsetLocations[index];
  3041. this._gl.disableVertexAttribArray(offsetLocation);
  3042. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3043. }
  3044. };
  3045. Engine.prototype.applyStates = function () {
  3046. this._depthCullingState.apply(this._gl);
  3047. this._alphaState.apply(this._gl);
  3048. };
  3049. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  3050. this.applyStates();
  3051. if (instancesCount) {
  3052. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2, instancesCount);
  3053. return;
  3054. }
  3055. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  3056. };
  3057. Engine.prototype._releaseEffect = function (effect) {
  3058. if (this._compiledEffects[effect._key]) {
  3059. delete this._compiledEffects[effect._key];
  3060. if (effect.getProgram()) {
  3061. this._gl.deleteProgram(effect.getProgram());
  3062. }
  3063. }
  3064. };
  3065. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3066. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3067. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  3068. var name = vertex + "+" + fragment + "@" + defines;
  3069. if (this._compiledEffects[name]) {
  3070. return this._compiledEffects[name];
  3071. }
  3072. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  3073. effect._key = name;
  3074. this._compiledEffects[name] = effect;
  3075. return effect;
  3076. };
  3077. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3078. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  3079. if (typeof samplers === "undefined") { samplers = []; }
  3080. if (typeof defines === "undefined") { defines = ""; }
  3081. return this.createEffect({
  3082. vertex: "particles",
  3083. fragmentElement: fragmentName
  3084. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  3085. };
  3086. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  3087. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  3088. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  3089. var shaderProgram = this._gl.createProgram();
  3090. this._gl.attachShader(shaderProgram, vertexShader);
  3091. this._gl.attachShader(shaderProgram, fragmentShader);
  3092. this._gl.linkProgram(shaderProgram);
  3093. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  3094. if (!linked) {
  3095. var error = this._gl.getProgramInfoLog(shaderProgram);
  3096. if (error) {
  3097. throw new Error(error);
  3098. }
  3099. }
  3100. this._gl.deleteShader(vertexShader);
  3101. this._gl.deleteShader(fragmentShader);
  3102. return shaderProgram;
  3103. };
  3104. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3105. var results = [];
  3106. for (var index = 0; index < uniformsNames.length; index++) {
  3107. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3108. }
  3109. return results;
  3110. };
  3111. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3112. var results = [];
  3113. for (var index = 0; index < attributesNames.length; index++) {
  3114. try {
  3115. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3116. } catch (e) {
  3117. results.push(-1);
  3118. }
  3119. }
  3120. return results;
  3121. };
  3122. Engine.prototype.enableEffect = function (effect) {
  3123. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3124. return;
  3125. }
  3126. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3127. this._gl.useProgram(effect.getProgram());
  3128. for (var i in this._vertexAttribArrays) {
  3129. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3130. continue;
  3131. }
  3132. this._vertexAttribArrays[i] = false;
  3133. this._gl.disableVertexAttribArray(i);
  3134. }
  3135. var attributesCount = effect.getAttributesCount();
  3136. for (var index = 0; index < attributesCount; index++) {
  3137. var order = effect.getAttributeLocation(index);
  3138. if (order >= 0) {
  3139. this._vertexAttribArrays[order] = true;
  3140. this._gl.enableVertexAttribArray(order);
  3141. }
  3142. }
  3143. this._currentEffect = effect;
  3144. };
  3145. Engine.prototype.setArray = function (uniform, array) {
  3146. if (!uniform)
  3147. return;
  3148. this._gl.uniform1fv(uniform, array);
  3149. };
  3150. Engine.prototype.setMatrices = function (uniform, matrices) {
  3151. if (!uniform)
  3152. return;
  3153. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3154. };
  3155. Engine.prototype.setMatrix = function (uniform, matrix) {
  3156. if (!uniform)
  3157. return;
  3158. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3159. };
  3160. Engine.prototype.setFloat = function (uniform, value) {
  3161. if (!uniform)
  3162. return;
  3163. this._gl.uniform1f(uniform, value);
  3164. };
  3165. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3166. if (!uniform)
  3167. return;
  3168. this._gl.uniform2f(uniform, x, y);
  3169. };
  3170. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3171. if (!uniform)
  3172. return;
  3173. this._gl.uniform3f(uniform, x, y, z);
  3174. };
  3175. Engine.prototype.setBool = function (uniform, bool) {
  3176. if (!uniform)
  3177. return;
  3178. this._gl.uniform1i(uniform, bool);
  3179. };
  3180. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3181. if (!uniform)
  3182. return;
  3183. this._gl.uniform4f(uniform, x, y, z, w);
  3184. };
  3185. Engine.prototype.setColor3 = function (uniform, color3) {
  3186. if (!uniform)
  3187. return;
  3188. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3189. };
  3190. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3191. if (!uniform)
  3192. return;
  3193. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3194. };
  3195. Engine.prototype.setState = function (culling, force) {
  3196. if (this._depthCullingState.cull !== culling || force) {
  3197. if (culling) {
  3198. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3199. this._depthCullingState.cull = true;
  3200. } else {
  3201. this._depthCullingState.cull = false;
  3202. }
  3203. }
  3204. };
  3205. Engine.prototype.setDepthBuffer = function (enable) {
  3206. this._depthCullingState.depthTest = enable;
  3207. };
  3208. Engine.prototype.getDepthWrite = function () {
  3209. return this._depthCullingState.depthMask;
  3210. };
  3211. Engine.prototype.setDepthWrite = function (enable) {
  3212. this._depthCullingState.depthMask = enable;
  3213. };
  3214. Engine.prototype.setColorWrite = function (enable) {
  3215. this._gl.colorMask(enable, enable, enable, enable);
  3216. };
  3217. Engine.prototype.setAlphaMode = function (mode) {
  3218. switch (mode) {
  3219. case BABYLON.Engine.ALPHA_DISABLE:
  3220. this.setDepthWrite(true);
  3221. this._alphaState.alphaBlend = false;
  3222. break;
  3223. case BABYLON.Engine.ALPHA_COMBINE:
  3224. this.setDepthWrite(false);
  3225. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3226. this._alphaState.alphaBlend = true;
  3227. break;
  3228. case BABYLON.Engine.ALPHA_ADD:
  3229. this.setDepthWrite(false);
  3230. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3231. this._alphaState.alphaBlend = true;
  3232. break;
  3233. }
  3234. };
  3235. Engine.prototype.setAlphaTesting = function (enable) {
  3236. this._alphaTest = enable;
  3237. };
  3238. Engine.prototype.getAlphaTesting = function () {
  3239. return this._alphaTest;
  3240. };
  3241. Engine.prototype.wipeCaches = function () {
  3242. this._activeTexturesCache = [];
  3243. this._currentEffect = null;
  3244. this._depthCullingState.reset();
  3245. this._alphaState.reset();
  3246. this._cachedVertexBuffers = null;
  3247. this._cachedIndexBuffer = null;
  3248. this._cachedEffectForVertexBuffers = null;
  3249. };
  3250. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3251. var gl = this._gl;
  3252. gl.bindTexture(gl.TEXTURE_2D, texture);
  3253. var magFilter = gl.NEAREST;
  3254. var minFilter = gl.NEAREST;
  3255. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3256. magFilter = gl.LINEAR;
  3257. minFilter = gl.LINEAR;
  3258. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3259. magFilter = gl.LINEAR;
  3260. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3261. }
  3262. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3263. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3264. gl.bindTexture(gl.TEXTURE_2D, null);
  3265. };
  3266. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  3267. var _this = this;
  3268. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3269. if (typeof onLoad === "undefined") { onLoad = null; }
  3270. if (typeof onError === "undefined") { onError = null; }
  3271. if (typeof buffer === "undefined") { buffer = null; }
  3272. var texture = this._gl.createTexture();
  3273. var extension;
  3274. var fromData = false;
  3275. if (url.substr(0, 5) === "data:") {
  3276. fromData = true;
  3277. }
  3278. if (!fromData)
  3279. extension = url.substr(url.length - 4, 4).toLowerCase();
  3280. else {
  3281. var oldUrl = url;
  3282. fromData = oldUrl.split(':');
  3283. url = oldUrl;
  3284. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  3285. }
  3286. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3287. var isTGA = (extension === ".tga");
  3288. scene._addPendingData(texture);
  3289. texture.url = url;
  3290. texture.noMipmap = noMipmap;
  3291. texture.references = 1;
  3292. this._loadedTexturesCache.push(texture);
  3293. var onerror = function () {
  3294. scene._removePendingData(texture);
  3295. if (onError) {
  3296. onError();
  3297. }
  3298. };
  3299. if (isTGA) {
  3300. var callback = function (arrayBuffer) {
  3301. var data = new Uint8Array(arrayBuffer);
  3302. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3303. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3304. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3305. if (onLoad) {
  3306. onLoad();
  3307. }
  3308. }, samplingMode);
  3309. };
  3310. if (!(fromData instanceof Array))
  3311. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3312. callback(arrayBuffer);
  3313. }, onerror, scene.database, true);
  3314. else
  3315. callback(buffer);
  3316. } else if (isDDS) {
  3317. callback = function (data) {
  3318. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3319. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3320. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3321. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3322. if (onLoad) {
  3323. onLoad();
  3324. }
  3325. }, samplingMode);
  3326. };
  3327. if (!(fromData instanceof Array))
  3328. BABYLON.Tools.LoadFile(url, function (data) {
  3329. callback(data);
  3330. }, onerror, scene.database, true);
  3331. else
  3332. callback(buffer);
  3333. } else {
  3334. var onload = function (img) {
  3335. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3336. var isPot = (img.width == potWidth && img.height == potHeight);
  3337. if (!isPot) {
  3338. _this._workingCanvas.width = potWidth;
  3339. _this._workingCanvas.height = potHeight;
  3340. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3341. }
  3342. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3343. if (onLoad) {
  3344. onLoad();
  3345. }
  3346. }, samplingMode);
  3347. };
  3348. if (!(fromData instanceof Array))
  3349. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3350. else
  3351. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  3352. }
  3353. return texture;
  3354. };
  3355. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  3356. var texture = this._gl.createTexture();
  3357. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  3358. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  3359. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3360. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3361. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3362. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3363. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3364. this._activeTexturesCache = [];
  3365. texture._baseWidth = width;
  3366. texture._baseHeight = height;
  3367. texture._width = width;
  3368. texture._height = height;
  3369. texture.isReady = false;
  3370. texture.generateMipMaps = generateMipMaps;
  3371. texture.references = 1;
  3372. this._loadedTexturesCache.push(texture);
  3373. return texture;
  3374. };
  3375. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  3376. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3377. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3378. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  3379. if (texture.generateMipMaps) {
  3380. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3381. }
  3382. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3383. this._activeTexturesCache = [];
  3384. texture.isReady = true;
  3385. };
  3386. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  3387. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3388. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1);
  3389. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  3390. if (!texture._workingCanvas) {
  3391. texture._workingCanvas = document.createElement("canvas");
  3392. texture._workingContext = texture._workingCanvas.getContext("2d");
  3393. texture._workingCanvas.width = texture._width;
  3394. texture._workingCanvas.height = texture._height;
  3395. }
  3396. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  3397. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3398. } else {
  3399. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3400. }
  3401. if (texture.generateMipMaps) {
  3402. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3403. }
  3404. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3405. this._activeTexturesCache = [];
  3406. texture.isReady = true;
  3407. };
  3408. Engine.prototype.createRenderTargetTexture = function (size, options) {
  3409. var generateMipMaps = false;
  3410. var generateDepthBuffer = true;
  3411. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3412. if (options !== undefined) {
  3413. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  3414. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3415. if (options.samplingMode !== undefined) {
  3416. samplingMode = options.samplingMode;
  3417. }
  3418. }
  3419. var gl = this._gl;
  3420. var texture = gl.createTexture();
  3421. gl.bindTexture(gl.TEXTURE_2D, texture);
  3422. var width = size.width || size;
  3423. var height = size.height || size;
  3424. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3425. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3426. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3427. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3428. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3429. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  3430. var depthBuffer;
  3431. if (generateDepthBuffer) {
  3432. depthBuffer = gl.createRenderbuffer();
  3433. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  3434. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3435. }
  3436. var framebuffer = gl.createFramebuffer();
  3437. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  3438. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3439. if (generateDepthBuffer) {
  3440. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  3441. }
  3442. gl.bindTexture(gl.TEXTURE_2D, null);
  3443. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3444. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3445. texture._framebuffer = framebuffer;
  3446. if (generateDepthBuffer) {
  3447. texture._depthBuffer = depthBuffer;
  3448. }
  3449. texture._width = width;
  3450. texture._height = height;
  3451. texture.isReady = true;
  3452. texture.generateMipMaps = generateMipMaps;
  3453. texture.references = 1;
  3454. this._activeTexturesCache = [];
  3455. this._loadedTexturesCache.push(texture);
  3456. return texture;
  3457. };
  3458. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  3459. var _this = this;
  3460. var gl = this._gl;
  3461. var texture = gl.createTexture();
  3462. texture.isCube = true;
  3463. texture.url = rootUrl;
  3464. texture.references = 1;
  3465. this._loadedTexturesCache.push(texture);
  3466. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  3467. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3468. if (isDDS) {
  3469. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  3470. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3471. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3472. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3473. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3474. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  3475. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  3476. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3477. }
  3478. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3479. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3480. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3481. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3482. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3483. _this._activeTexturesCache = [];
  3484. texture._width = info.width;
  3485. texture._height = info.height;
  3486. texture.isReady = true;
  3487. }, null, null, true);
  3488. } else {
  3489. cascadeLoad(rootUrl, scene, function (imgs) {
  3490. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  3491. var height = width;
  3492. _this._workingCanvas.width = width;
  3493. _this._workingCanvas.height = height;
  3494. var faces = [
  3495. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3496. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3497. ];
  3498. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3499. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3500. for (var index = 0; index < faces.length; index++) {
  3501. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3502. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  3503. }
  3504. if (!noMipmap) {
  3505. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3506. }
  3507. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3508. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  3509. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3510. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3511. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3512. _this._activeTexturesCache = [];
  3513. texture._width = width;
  3514. texture._height = height;
  3515. texture.isReady = true;
  3516. }, extensions);
  3517. }
  3518. return texture;
  3519. };
  3520. Engine.prototype._releaseTexture = function (texture) {
  3521. var gl = this._gl;
  3522. if (texture._framebuffer) {
  3523. gl.deleteFramebuffer(texture._framebuffer);
  3524. }
  3525. if (texture._depthBuffer) {
  3526. gl.deleteRenderbuffer(texture._depthBuffer);
  3527. }
  3528. gl.deleteTexture(texture);
  3529. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3530. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3531. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3532. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3533. this._activeTexturesCache[channel] = null;
  3534. }
  3535. var index = this._loadedTexturesCache.indexOf(texture);
  3536. if (index !== -1) {
  3537. this._loadedTexturesCache.splice(index, 1);
  3538. }
  3539. };
  3540. Engine.prototype.bindSamplers = function (effect) {
  3541. this._gl.useProgram(effect.getProgram());
  3542. var samplers = effect.getSamplers();
  3543. for (var index = 0; index < samplers.length; index++) {
  3544. var uniform = effect.getUniform(samplers[index]);
  3545. this._gl.uniform1i(uniform, index);
  3546. }
  3547. this._currentEffect = null;
  3548. };
  3549. Engine.prototype._bindTexture = function (channel, texture) {
  3550. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3551. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3552. this._activeTexturesCache[channel] = null;
  3553. };
  3554. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  3555. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3556. };
  3557. Engine.prototype.setTexture = function (channel, texture) {
  3558. if (channel < 0) {
  3559. return;
  3560. }
  3561. if (!texture || !texture.isReady()) {
  3562. if (this._activeTexturesCache[channel] != null) {
  3563. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3564. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3565. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3566. this._activeTexturesCache[channel] = null;
  3567. }
  3568. return;
  3569. }
  3570. if (texture instanceof BABYLON.VideoTexture) {
  3571. if (texture.update()) {
  3572. this._activeTexturesCache[channel] = null;
  3573. }
  3574. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  3575. texture.delayLoad();
  3576. return;
  3577. }
  3578. if (this._activeTexturesCache[channel] == texture) {
  3579. return;
  3580. }
  3581. this._activeTexturesCache[channel] = texture;
  3582. var internalTexture = texture.getInternalTexture();
  3583. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3584. if (internalTexture.isCube) {
  3585. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3586. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3587. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3588. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3589. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3590. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3591. }
  3592. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3593. } else {
  3594. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  3595. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3596. internalTexture._cachedWrapU = texture.wrapU;
  3597. switch (texture.wrapU) {
  3598. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3599. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3600. break;
  3601. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3602. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3603. break;
  3604. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3605. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3606. break;
  3607. }
  3608. }
  3609. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3610. internalTexture._cachedWrapV = texture.wrapV;
  3611. switch (texture.wrapV) {
  3612. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3613. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3614. break;
  3615. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3616. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  3617. break;
  3618. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3619. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  3620. break;
  3621. }
  3622. }
  3623. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3624. }
  3625. };
  3626. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  3627. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3628. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  3629. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  3630. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  3631. }
  3632. };
  3633. Engine.prototype.readPixels = function (x, y, width, height) {
  3634. var data = new Uint8Array(height * width * 4);
  3635. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  3636. return data;
  3637. };
  3638. Engine.prototype.dispose = function () {
  3639. this.hideLoadingUI();
  3640. this.stopRenderLoop();
  3641. while (this.scenes.length) {
  3642. this.scenes[0].dispose();
  3643. }
  3644. for (var name in this._compiledEffects) {
  3645. this._gl.deleteProgram(this._compiledEffects[name]._program);
  3646. }
  3647. for (var i in this._vertexAttribArrays) {
  3648. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3649. continue;
  3650. }
  3651. this._gl.disableVertexAttribArray(i);
  3652. }
  3653. window.removeEventListener("blur", this._onBlur);
  3654. window.removeEventListener("focus", this._onFocus);
  3655. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  3656. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  3657. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  3658. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  3659. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  3660. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  3661. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  3662. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  3663. };
  3664. Engine.prototype.displayLoadingUI = function () {
  3665. var _this = this;
  3666. this._loadingDiv = document.createElement("div");
  3667. this._loadingDiv.style.opacity = "0";
  3668. this._loadingDiv.style.transition = "opacity 1.5s ease";
  3669. this._loadingTextDiv = document.createElement("div");
  3670. this._loadingTextDiv.style.position = "absolute";
  3671. this._loadingTextDiv.style.left = "0";
  3672. this._loadingTextDiv.style.top = "50%";
  3673. this._loadingTextDiv.style.marginTop = "80px";
  3674. this._loadingTextDiv.style.width = "100%";
  3675. this._loadingTextDiv.style.height = "20px";
  3676. this._loadingTextDiv.style.fontFamily = "Arial";
  3677. this._loadingTextDiv.style.fontSize = "14px";
  3678. this._loadingTextDiv.style.color = "white";
  3679. this._loadingTextDiv.style.textAlign = "center";
  3680. this._loadingTextDiv.innerHTML = "Loading";
  3681. this._loadingDiv.appendChild(this._loadingTextDiv);
  3682. var imgBack = new Image();
  3683. 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==";
  3684. imgBack.style.position = "absolute";
  3685. imgBack.style.left = "50%";
  3686. imgBack.style.top = "50%";
  3687. imgBack.style.marginLeft = "-50px";
  3688. imgBack.style.marginTop = "-50px";
  3689. imgBack.style.transition = "transform 1.0s ease";
  3690. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  3691. var deg = 360;
  3692. var onTransitionEnd = function () {
  3693. deg += 360;
  3694. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  3695. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  3696. };
  3697. imgBack.addEventListener("transitionend", onTransitionEnd);
  3698. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  3699. this._loadingDiv.appendChild(imgBack);
  3700. var imgFront = new Image();
  3701. 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=";
  3702. imgFront.style.position = "absolute";
  3703. imgFront.style.left = "50%";
  3704. imgFront.style.top = "50%";
  3705. imgFront.style.marginLeft = "-50px";
  3706. imgFront.style.marginTop = "-50px";
  3707. this._loadingDiv.appendChild(imgFront);
  3708. this._resizeLoadingUI = function () {
  3709. var canvasRect = _this.getRenderingCanvasClientRect();
  3710. _this._loadingDiv.style.position = "absolute";
  3711. _this._loadingDiv.style.left = canvasRect.left + "px";
  3712. _this._loadingDiv.style.top = canvasRect.top + "px";
  3713. _this._loadingDiv.style.width = canvasRect.width + "px";
  3714. _this._loadingDiv.style.height = canvasRect.height + "px";
  3715. };
  3716. this._resizeLoadingUI();
  3717. window.addEventListener("resize", this._resizeLoadingUI);
  3718. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3719. document.body.appendChild(this._loadingDiv);
  3720. setTimeout(function () {
  3721. _this._loadingDiv.style.opacity = "1";
  3722. imgBack.style.transform = "rotateZ(360deg)";
  3723. imgBack.style.webkitTransform = "rotateZ(360deg)";
  3724. }, 0);
  3725. };
  3726. Object.defineProperty(Engine.prototype, "loadingUIText", {
  3727. set: function (text) {
  3728. if (!this._loadingDiv) {
  3729. return;
  3730. }
  3731. this._loadingTextDiv.innerHTML = text;
  3732. },
  3733. enumerable: true,
  3734. configurable: true
  3735. });
  3736. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  3737. get: function () {
  3738. return this._loadingDivBackgroundColor;
  3739. },
  3740. set: function (color) {
  3741. this._loadingDivBackgroundColor = color;
  3742. if (!this._loadingDiv) {
  3743. return;
  3744. }
  3745. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3746. },
  3747. enumerable: true,
  3748. configurable: true
  3749. });
  3750. Engine.prototype.hideLoadingUI = function () {
  3751. var _this = this;
  3752. if (!this._loadingDiv) {
  3753. return;
  3754. }
  3755. var onTransitionEnd = function () {
  3756. if (!_this._loadingDiv) {
  3757. return;
  3758. }
  3759. document.body.removeChild(_this._loadingDiv);
  3760. window.removeEventListener("resize", _this._resizeLoadingUI);
  3761. _this._loadingDiv = null;
  3762. };
  3763. this._loadingDiv.style.opacity = "0";
  3764. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  3765. };
  3766. Engine.isSupported = function () {
  3767. try {
  3768. if (navigator.isCocoonJS) {
  3769. return true;
  3770. }
  3771. var tempcanvas = document.createElement("canvas");
  3772. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  3773. return gl != null && !!window.WebGLRenderingContext;
  3774. } catch (e) {
  3775. return false;
  3776. }
  3777. };
  3778. Engine._ALPHA_DISABLE = 0;
  3779. Engine._ALPHA_ADD = 1;
  3780. Engine._ALPHA_COMBINE = 2;
  3781. Engine._DELAYLOADSTATE_NONE = 0;
  3782. Engine._DELAYLOADSTATE_LOADED = 1;
  3783. Engine._DELAYLOADSTATE_LOADING = 2;
  3784. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  3785. Engine.Epsilon = 0.001;
  3786. Engine.CollisionsEpsilon = 0.001;
  3787. Engine.ShadersRepository = "Babylon/Shaders/";
  3788. return Engine;
  3789. })();
  3790. BABYLON.Engine = Engine;
  3791. })(BABYLON || (BABYLON = {}));
  3792. var BABYLON;
  3793. (function (BABYLON) {
  3794. var Node = (function () {
  3795. function Node(name, scene) {
  3796. this.state = "";
  3797. this.animations = new Array();
  3798. this._childrenFlag = -1;
  3799. this._isEnabled = true;
  3800. this._isReady = true;
  3801. this._currentRenderId = -1;
  3802. this.name = name;
  3803. this.id = name;
  3804. this._scene = scene;
  3805. this._initCache();
  3806. }
  3807. Node.prototype.getScene = function () {
  3808. return this._scene;
  3809. };
  3810. Node.prototype.getEngine = function () {
  3811. return this._scene.getEngine();
  3812. };
  3813. Node.prototype.getWorldMatrix = function () {
  3814. return BABYLON.Matrix.Identity();
  3815. };
  3816. Node.prototype._initCache = function () {
  3817. this._cache = {};
  3818. this._cache.parent = undefined;
  3819. };
  3820. Node.prototype.updateCache = function (force) {
  3821. if (!force && this.isSynchronized())
  3822. return;
  3823. this._cache.parent = this.parent;
  3824. this._updateCache();
  3825. };
  3826. Node.prototype._updateCache = function (ignoreParentClass) {
  3827. };
  3828. Node.prototype._isSynchronized = function () {
  3829. return true;
  3830. };
  3831. Node.prototype.isSynchronizedWithParent = function () {
  3832. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  3833. };
  3834. Node.prototype.isSynchronized = function (updateCache) {
  3835. var check = this.hasNewParent();
  3836. check = check || !this.isSynchronizedWithParent();
  3837. check = check || !this._isSynchronized();
  3838. if (updateCache)
  3839. this.updateCache(true);
  3840. return !check;
  3841. };
  3842. Node.prototype.hasNewParent = function (update) {
  3843. if (this._cache.parent === this.parent)
  3844. return false;
  3845. if (update)
  3846. this._cache.parent = this.parent;
  3847. return true;
  3848. };
  3849. Node.prototype.isReady = function () {
  3850. return this._isReady;
  3851. };
  3852. Node.prototype.isEnabled = function () {
  3853. if (!this._isEnabled) {
  3854. return false;
  3855. }
  3856. if (this.parent) {
  3857. return this.parent.isEnabled();
  3858. }
  3859. return true;
  3860. };
  3861. Node.prototype.setEnabled = function (value) {
  3862. this._isEnabled = value;
  3863. };
  3864. Node.prototype.isDescendantOf = function (ancestor) {
  3865. if (this.parent) {
  3866. if (this.parent === ancestor) {
  3867. return true;
  3868. }
  3869. return this.parent.isDescendantOf(ancestor);
  3870. }
  3871. return false;
  3872. };
  3873. Node.prototype._getDescendants = function (list, results) {
  3874. for (var index = 0; index < list.length; index++) {
  3875. var item = list[index];
  3876. if (item.isDescendantOf(this)) {
  3877. results.push(item);
  3878. }
  3879. }
  3880. };
  3881. Node.prototype.getDescendants = function () {
  3882. var results = [];
  3883. this._getDescendants(this._scene.meshes, results);
  3884. this._getDescendants(this._scene.lights, results);
  3885. this._getDescendants(this._scene.cameras, results);
  3886. return results;
  3887. };
  3888. Node.prototype._setReady = function (state) {
  3889. if (state == this._isReady) {
  3890. return;
  3891. }
  3892. if (!state) {
  3893. this._isReady = false;
  3894. return;
  3895. }
  3896. this._isReady = true;
  3897. if (this.onReady) {
  3898. this.onReady(this);
  3899. }
  3900. };
  3901. return Node;
  3902. })();
  3903. BABYLON.Node = Node;
  3904. })(BABYLON || (BABYLON = {}));
  3905. var BABYLON;
  3906. (function (BABYLON) {
  3907. var BoundingSphere = (function () {
  3908. function BoundingSphere(minimum, maximum) {
  3909. this.minimum = minimum;
  3910. this.maximum = maximum;
  3911. this._tempRadiusVector = BABYLON.Vector3.Zero();
  3912. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  3913. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  3914. this.radius = distance * 0.5;
  3915. this.centerWorld = BABYLON.Vector3.Zero();
  3916. this._update(BABYLON.Matrix.Identity());
  3917. }
  3918. BoundingSphere.prototype._update = function (world) {
  3919. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  3920. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  3921. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  3922. };
  3923. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  3924. for (var i = 0; i < 6; i++) {
  3925. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  3926. return false;
  3927. }
  3928. return true;
  3929. };
  3930. BoundingSphere.prototype.intersectsPoint = function (point) {
  3931. var x = this.centerWorld.x - point.x;
  3932. var y = this.centerWorld.y - point.y;
  3933. var z = this.centerWorld.z - point.z;
  3934. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3935. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  3936. return false;
  3937. return true;
  3938. };
  3939. BoundingSphere.Intersects = function (sphere0, sphere1) {
  3940. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  3941. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  3942. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  3943. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  3944. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  3945. return false;
  3946. return true;
  3947. };
  3948. return BoundingSphere;
  3949. })();
  3950. BABYLON.BoundingSphere = BoundingSphere;
  3951. })(BABYLON || (BABYLON = {}));
  3952. var BABYLON;
  3953. (function (BABYLON) {
  3954. var BoundingBox = (function () {
  3955. function BoundingBox(minimum, maximum) {
  3956. this.minimum = minimum;
  3957. this.maximum = maximum;
  3958. this.vectors = new Array();
  3959. this.vectorsWorld = new Array();
  3960. this.vectors.push(this.minimum.clone());
  3961. this.vectors.push(this.maximum.clone());
  3962. this.vectors.push(this.minimum.clone());
  3963. this.vectors[2].x = this.maximum.x;
  3964. this.vectors.push(this.minimum.clone());
  3965. this.vectors[3].y = this.maximum.y;
  3966. this.vectors.push(this.minimum.clone());
  3967. this.vectors[4].z = this.maximum.z;
  3968. this.vectors.push(this.maximum.clone());
  3969. this.vectors[5].z = this.minimum.z;
  3970. this.vectors.push(this.maximum.clone());
  3971. this.vectors[6].x = this.minimum.x;
  3972. this.vectors.push(this.maximum.clone());
  3973. this.vectors[7].y = this.minimum.y;
  3974. this.center = this.maximum.add(this.minimum).scale(0.5);
  3975. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  3976. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  3977. for (var index = 0; index < this.vectors.length; index++) {
  3978. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  3979. }
  3980. this.minimumWorld = BABYLON.Vector3.Zero();
  3981. this.maximumWorld = BABYLON.Vector3.Zero();
  3982. this._update(BABYLON.Matrix.Identity());
  3983. }
  3984. BoundingBox.prototype.getWorldMatrix = function () {
  3985. return this._worldMatrix;
  3986. };
  3987. BoundingBox.prototype._update = function (world) {
  3988. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  3989. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  3990. for (var index = 0; index < this.vectors.length; index++) {
  3991. var v = this.vectorsWorld[index];
  3992. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  3993. if (v.x < this.minimumWorld.x)
  3994. this.minimumWorld.x = v.x;
  3995. if (v.y < this.minimumWorld.y)
  3996. this.minimumWorld.y = v.y;
  3997. if (v.z < this.minimumWorld.z)
  3998. this.minimumWorld.z = v.z;
  3999. if (v.x > this.maximumWorld.x)
  4000. this.maximumWorld.x = v.x;
  4001. if (v.y > this.maximumWorld.y)
  4002. this.maximumWorld.y = v.y;
  4003. if (v.z > this.maximumWorld.z)
  4004. this.maximumWorld.z = v.z;
  4005. }
  4006. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  4007. this.center.scaleInPlace(0.5);
  4008. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  4009. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  4010. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  4011. this._worldMatrix = world;
  4012. };
  4013. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  4014. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  4015. };
  4016. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4017. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  4018. };
  4019. BoundingBox.prototype.intersectsPoint = function (point) {
  4020. var delta = BABYLON.Engine.Epsilon;
  4021. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  4022. return false;
  4023. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  4024. return false;
  4025. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  4026. return false;
  4027. return true;
  4028. };
  4029. BoundingBox.prototype.intersectsSphere = function (sphere) {
  4030. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  4031. };
  4032. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  4033. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  4034. return false;
  4035. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  4036. return false;
  4037. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  4038. return false;
  4039. return true;
  4040. };
  4041. BoundingBox.Intersects = function (box0, box1) {
  4042. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  4043. return false;
  4044. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  4045. return false;
  4046. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  4047. return false;
  4048. return true;
  4049. };
  4050. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  4051. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  4052. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  4053. return (num <= (sphereRadius * sphereRadius));
  4054. };
  4055. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  4056. for (var p = 0; p < 6; p++) {
  4057. for (var i = 0; i < 8; i++) {
  4058. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4059. return false;
  4060. }
  4061. }
  4062. }
  4063. return true;
  4064. };
  4065. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  4066. for (var p = 0; p < 6; p++) {
  4067. var inCount = 8;
  4068. for (var i = 0; i < 8; i++) {
  4069. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4070. --inCount;
  4071. } else {
  4072. break;
  4073. }
  4074. }
  4075. if (inCount == 0)
  4076. return false;
  4077. }
  4078. return true;
  4079. };
  4080. return BoundingBox;
  4081. })();
  4082. BABYLON.BoundingBox = BoundingBox;
  4083. })(BABYLON || (BABYLON = {}));
  4084. var BABYLON;
  4085. (function (BABYLON) {
  4086. var computeBoxExtents = function (axis, box) {
  4087. var p = BABYLON.Vector3.Dot(box.center, axis);
  4088. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  4089. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  4090. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  4091. var r = r0 + r1 + r2;
  4092. return {
  4093. min: p - r,
  4094. max: p + r
  4095. };
  4096. };
  4097. var extentsOverlap = function (min0, max0, min1, max1) {
  4098. return !(min0 > max1 || min1 > max0);
  4099. };
  4100. var axisOverlap = function (axis, box0, box1) {
  4101. var result0 = computeBoxExtents(axis, box0);
  4102. var result1 = computeBoxExtents(axis, box1);
  4103. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  4104. };
  4105. var BoundingInfo = (function () {
  4106. function BoundingInfo(minimum, maximum) {
  4107. this.minimum = minimum;
  4108. this.maximum = maximum;
  4109. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  4110. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  4111. }
  4112. BoundingInfo.prototype._update = function (world) {
  4113. this.boundingBox._update(world);
  4114. this.boundingSphere._update(world);
  4115. };
  4116. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  4117. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  4118. return false;
  4119. return this.boundingBox.isInFrustum(frustumPlanes);
  4120. };
  4121. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4122. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  4123. };
  4124. BoundingInfo.prototype._checkCollision = function (collider) {
  4125. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  4126. };
  4127. BoundingInfo.prototype.intersectsPoint = function (point) {
  4128. if (!this.boundingSphere.centerWorld) {
  4129. return false;
  4130. }
  4131. if (!this.boundingSphere.intersectsPoint(point)) {
  4132. return false;
  4133. }
  4134. if (!this.boundingBox.intersectsPoint(point)) {
  4135. return false;
  4136. }
  4137. return true;
  4138. };
  4139. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  4140. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  4141. return false;
  4142. }
  4143. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  4144. return false;
  4145. }
  4146. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  4147. return false;
  4148. }
  4149. if (!precise) {
  4150. return true;
  4151. }
  4152. var box0 = this.boundingBox;
  4153. var box1 = boundingInfo.boundingBox;
  4154. if (!axisOverlap(box0.directions[0], box0, box1))
  4155. return false;
  4156. if (!axisOverlap(box0.directions[1], box0, box1))
  4157. return false;
  4158. if (!axisOverlap(box0.directions[2], box0, box1))
  4159. return false;
  4160. if (!axisOverlap(box1.directions[0], box0, box1))
  4161. return false;
  4162. if (!axisOverlap(box1.directions[1], box0, box1))
  4163. return false;
  4164. if (!axisOverlap(box1.directions[2], box0, box1))
  4165. return false;
  4166. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  4167. return false;
  4168. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  4169. return false;
  4170. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  4171. return false;
  4172. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  4173. return false;
  4174. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  4175. return false;
  4176. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  4177. return false;
  4178. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  4179. return false;
  4180. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  4181. return false;
  4182. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  4183. return false;
  4184. return true;
  4185. };
  4186. return BoundingInfo;
  4187. })();
  4188. BABYLON.BoundingInfo = BoundingInfo;
  4189. })(BABYLON || (BABYLON = {}));
  4190. var __extends = this.__extends || function (d, b) {
  4191. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4192. function __() { this.constructor = d; }
  4193. __.prototype = b.prototype;
  4194. d.prototype = new __();
  4195. };
  4196. var BABYLON;
  4197. (function (BABYLON) {
  4198. var Light = (function (_super) {
  4199. __extends(Light, _super);
  4200. function Light(name, scene) {
  4201. _super.call(this, name, scene);
  4202. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  4203. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  4204. this.intensity = 1.0;
  4205. this.range = Number.MAX_VALUE;
  4206. this.includedOnlyMeshes = new Array();
  4207. this.excludedMeshes = new Array();
  4208. this._excludedMeshesIds = new Array();
  4209. this._includedOnlyMeshesIds = new Array();
  4210. scene.lights.push(this);
  4211. }
  4212. Light.prototype.getShadowGenerator = function () {
  4213. return this._shadowGenerator;
  4214. };
  4215. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4216. };
  4217. Light.prototype._getWorldMatrix = function () {
  4218. return BABYLON.Matrix.Identity();
  4219. };
  4220. Light.prototype.canAffectMesh = function (mesh) {
  4221. if (!mesh) {
  4222. return true;
  4223. }
  4224. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4225. return false;
  4226. }
  4227. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4228. return false;
  4229. }
  4230. return true;
  4231. };
  4232. Light.prototype.getWorldMatrix = function () {
  4233. this._currentRenderId = this.getScene().getRenderId();
  4234. var worldMatrix = this._getWorldMatrix();
  4235. if (this.parent && this.parent.getWorldMatrix) {
  4236. if (!this._parentedWorldMatrix) {
  4237. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4238. }
  4239. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4240. return this._parentedWorldMatrix;
  4241. }
  4242. return worldMatrix;
  4243. };
  4244. Light.prototype.dispose = function () {
  4245. if (this._shadowGenerator) {
  4246. this._shadowGenerator.dispose();
  4247. this._shadowGenerator = null;
  4248. }
  4249. var index = this.getScene().lights.indexOf(this);
  4250. this.getScene().lights.splice(index, 1);
  4251. };
  4252. return Light;
  4253. })(BABYLON.Node);
  4254. BABYLON.Light = Light;
  4255. })(BABYLON || (BABYLON = {}));
  4256. var __extends = this.__extends || function (d, b) {
  4257. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4258. function __() { this.constructor = d; }
  4259. __.prototype = b.prototype;
  4260. d.prototype = new __();
  4261. };
  4262. var BABYLON;
  4263. (function (BABYLON) {
  4264. var PointLight = (function (_super) {
  4265. __extends(PointLight, _super);
  4266. function PointLight(name, position, scene) {
  4267. _super.call(this, name, scene);
  4268. this.position = position;
  4269. }
  4270. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  4271. if (this.parent && this.parent.getWorldMatrix) {
  4272. if (!this._transformedPosition) {
  4273. this._transformedPosition = BABYLON.Vector3.Zero();
  4274. }
  4275. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4276. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  4277. return;
  4278. }
  4279. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  4280. };
  4281. PointLight.prototype.getShadowGenerator = function () {
  4282. return null;
  4283. };
  4284. PointLight.prototype._getWorldMatrix = function () {
  4285. if (!this._worldMatrix) {
  4286. this._worldMatrix = BABYLON.Matrix.Identity();
  4287. }
  4288. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4289. return this._worldMatrix;
  4290. };
  4291. return PointLight;
  4292. })(BABYLON.Light);
  4293. BABYLON.PointLight = PointLight;
  4294. })(BABYLON || (BABYLON = {}));
  4295. var __extends = this.__extends || function (d, b) {
  4296. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4297. function __() { this.constructor = d; }
  4298. __.prototype = b.prototype;
  4299. d.prototype = new __();
  4300. };
  4301. var BABYLON;
  4302. (function (BABYLON) {
  4303. var SpotLight = (function (_super) {
  4304. __extends(SpotLight, _super);
  4305. function SpotLight(name, position, direction, angle, exponent, scene) {
  4306. _super.call(this, name, scene);
  4307. this.position = position;
  4308. this.direction = direction;
  4309. this.angle = angle;
  4310. this.exponent = exponent;
  4311. }
  4312. SpotLight.prototype.setDirectionToTarget = function (target) {
  4313. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4314. return this.direction;
  4315. };
  4316. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  4317. var normalizeDirection;
  4318. if (this.parent && this.parent.getWorldMatrix) {
  4319. if (!this._transformedDirection) {
  4320. this._transformedDirection = BABYLON.Vector3.Zero();
  4321. }
  4322. if (!this._transformedPosition) {
  4323. this._transformedPosition = BABYLON.Vector3.Zero();
  4324. }
  4325. var parentWorldMatrix = this.parent.getWorldMatrix();
  4326. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  4327. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  4328. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  4329. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  4330. } else {
  4331. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  4332. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4333. }
  4334. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  4335. };
  4336. SpotLight.prototype._getWorldMatrix = function () {
  4337. if (!this._worldMatrix) {
  4338. this._worldMatrix = BABYLON.Matrix.Identity();
  4339. }
  4340. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4341. return this._worldMatrix;
  4342. };
  4343. return SpotLight;
  4344. })(BABYLON.Light);
  4345. BABYLON.SpotLight = SpotLight;
  4346. })(BABYLON || (BABYLON = {}));
  4347. var __extends = this.__extends || function (d, b) {
  4348. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4349. function __() { this.constructor = d; }
  4350. __.prototype = b.prototype;
  4351. d.prototype = new __();
  4352. };
  4353. var BABYLON;
  4354. (function (BABYLON) {
  4355. var DirectionalLight = (function (_super) {
  4356. __extends(DirectionalLight, _super);
  4357. function DirectionalLight(name, direction, scene) {
  4358. _super.call(this, name, scene);
  4359. this.direction = direction;
  4360. this.position = direction.scale(-1);
  4361. }
  4362. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  4363. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4364. return this.direction;
  4365. };
  4366. DirectionalLight.prototype._computeTransformedPosition = function () {
  4367. if (this.parent && this.parent.getWorldMatrix) {
  4368. if (!this._transformedPosition) {
  4369. this._transformedPosition = BABYLON.Vector3.Zero();
  4370. }
  4371. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4372. return true;
  4373. }
  4374. return false;
  4375. };
  4376. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  4377. if (this.parent && this.parent.getWorldMatrix) {
  4378. if (!this._transformedDirection) {
  4379. this._transformedDirection = BABYLON.Vector3.Zero();
  4380. }
  4381. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  4382. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  4383. return;
  4384. }
  4385. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  4386. };
  4387. DirectionalLight.prototype._getWorldMatrix = function () {
  4388. if (!this._worldMatrix) {
  4389. this._worldMatrix = BABYLON.Matrix.Identity();
  4390. }
  4391. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4392. return this._worldMatrix;
  4393. };
  4394. return DirectionalLight;
  4395. })(BABYLON.Light);
  4396. BABYLON.DirectionalLight = DirectionalLight;
  4397. })(BABYLON || (BABYLON = {}));
  4398. var BABYLON;
  4399. (function (BABYLON) {
  4400. var ShadowGenerator = (function () {
  4401. function ShadowGenerator(mapSize, light) {
  4402. var _this = this;
  4403. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4404. this._darkness = 0;
  4405. this._transparencyShadow = false;
  4406. this._viewMatrix = BABYLON.Matrix.Zero();
  4407. this._projectionMatrix = BABYLON.Matrix.Zero();
  4408. this._transformMatrix = BABYLON.Matrix.Zero();
  4409. this._worldViewProjection = BABYLON.Matrix.Zero();
  4410. this._light = light;
  4411. this._scene = light.getScene();
  4412. light._shadowGenerator = this;
  4413. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  4414. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4415. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4416. this._shadowMap.renderParticles = false;
  4417. var renderSubMesh = function (subMesh) {
  4418. var mesh = subMesh.getRenderingMesh();
  4419. var scene = _this._scene;
  4420. var engine = scene.getEngine();
  4421. engine.setState(subMesh.getMaterial().backFaceCulling);
  4422. var batch = mesh._getInstancesRenderList(subMesh._id);
  4423. if (batch.mustReturn) {
  4424. return;
  4425. }
  4426. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  4427. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  4428. engine.enableEffect(_this._effect);
  4429. mesh._bind(subMesh, _this._effect, false);
  4430. var material = subMesh.getMaterial();
  4431. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  4432. if (material && material.needAlphaTesting()) {
  4433. var alphaTexture = material.getAlphaTestTexture();
  4434. _this._effect.setTexture("diffuseSampler", alphaTexture);
  4435. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  4436. }
  4437. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  4438. if (useBones) {
  4439. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  4440. }
  4441. if (hardwareInstancedRendering) {
  4442. mesh._renderWithInstances(subMesh, false, batch, _this._effect, engine);
  4443. } else {
  4444. if (batch.renderSelf[subMesh._id]) {
  4445. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  4446. mesh._draw(subMesh, true);
  4447. }
  4448. if (batch.visibleInstances[subMesh._id]) {
  4449. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  4450. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  4451. _this._effect.setMatrix("world", instance.getWorldMatrix());
  4452. mesh._draw(subMesh, true);
  4453. }
  4454. }
  4455. }
  4456. } else {
  4457. _this._shadowMap.resetRefreshCounter();
  4458. }
  4459. };
  4460. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  4461. var index;
  4462. for (index = 0; index < opaqueSubMeshes.length; index++) {
  4463. renderSubMesh(opaqueSubMeshes.data[index]);
  4464. }
  4465. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  4466. renderSubMesh(alphaTestSubMeshes.data[index]);
  4467. }
  4468. if (_this._transparencyShadow) {
  4469. for (index = 0; index < transparentSubMeshes.length; index++) {
  4470. renderSubMesh(transparentSubMeshes.data[index]);
  4471. }
  4472. }
  4473. };
  4474. }
  4475. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  4476. get: function () {
  4477. return ShadowGenerator._FILTER_NONE;
  4478. },
  4479. enumerable: true,
  4480. configurable: true
  4481. });
  4482. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  4483. get: function () {
  4484. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  4485. },
  4486. enumerable: true,
  4487. configurable: true
  4488. });
  4489. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  4490. get: function () {
  4491. return ShadowGenerator._FILTER_POISSONSAMPLING;
  4492. },
  4493. enumerable: true,
  4494. configurable: true
  4495. });
  4496. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  4497. get: function () {
  4498. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4499. },
  4500. set: function (value) {
  4501. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  4502. },
  4503. enumerable: true,
  4504. configurable: true
  4505. });
  4506. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  4507. get: function () {
  4508. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  4509. },
  4510. set: function (value) {
  4511. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  4512. },
  4513. enumerable: true,
  4514. configurable: true
  4515. });
  4516. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  4517. var defines = [];
  4518. if (this.useVarianceShadowMap) {
  4519. defines.push("#define VSM");
  4520. }
  4521. var attribs = [BABYLON.VertexBuffer.PositionKind];
  4522. var mesh = subMesh.getMesh();
  4523. var material = subMesh.getMaterial();
  4524. if (material && material.needAlphaTesting()) {
  4525. defines.push("#define ALPHATEST");
  4526. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  4527. attribs.push(BABYLON.VertexBuffer.UVKind);
  4528. defines.push("#define UV1");
  4529. }
  4530. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  4531. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  4532. defines.push("#define UV2");
  4533. }
  4534. }
  4535. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  4536. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  4537. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  4538. defines.push("#define BONES");
  4539. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  4540. }
  4541. if (useInstances) {
  4542. defines.push("#define INSTANCES");
  4543. attribs.push("world0");
  4544. attribs.push("world1");
  4545. attribs.push("world2");
  4546. attribs.push("world3");
  4547. }
  4548. var join = defines.join("\n");
  4549. if (this._cachedDefines != join) {
  4550. this._cachedDefines = join;
  4551. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  4552. }
  4553. return this._effect.isReady();
  4554. };
  4555. ShadowGenerator.prototype.getShadowMap = function () {
  4556. return this._shadowMap;
  4557. };
  4558. ShadowGenerator.prototype.getLight = function () {
  4559. return this._light;
  4560. };
  4561. ShadowGenerator.prototype.getTransformMatrix = function () {
  4562. var lightPosition = this._light.position;
  4563. var lightDirection = this._light.direction;
  4564. if (this._light._computeTransformedPosition()) {
  4565. lightPosition = this._light._transformedPosition;
  4566. }
  4567. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  4568. this._cachedPosition = lightPosition.clone();
  4569. this._cachedDirection = lightDirection.clone();
  4570. var activeCamera = this._scene.activeCamera;
  4571. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  4572. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  4573. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  4574. }
  4575. return this._transformMatrix;
  4576. };
  4577. ShadowGenerator.prototype.getDarkness = function () {
  4578. return this._darkness;
  4579. };
  4580. ShadowGenerator.prototype.setDarkness = function (darkness) {
  4581. if (darkness >= 1.0)
  4582. this._darkness = 1.0;
  4583. else if (darkness <= 0.0)
  4584. this._darkness = 0.0;
  4585. else
  4586. this._darkness = darkness;
  4587. };
  4588. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  4589. this._transparencyShadow = hasShadow;
  4590. };
  4591. ShadowGenerator.prototype.dispose = function () {
  4592. this._shadowMap.dispose();
  4593. };
  4594. ShadowGenerator._FILTER_NONE = 0;
  4595. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  4596. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  4597. return ShadowGenerator;
  4598. })();
  4599. BABYLON.ShadowGenerator = ShadowGenerator;
  4600. })(BABYLON || (BABYLON = {}));
  4601. var __extends = this.__extends || function (d, b) {
  4602. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4603. function __() { this.constructor = d; }
  4604. __.prototype = b.prototype;
  4605. d.prototype = new __();
  4606. };
  4607. var BABYLON;
  4608. (function (BABYLON) {
  4609. var HemisphericLight = (function (_super) {
  4610. __extends(HemisphericLight, _super);
  4611. function HemisphericLight(name, direction, scene) {
  4612. _super.call(this, name, scene);
  4613. this.direction = direction;
  4614. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  4615. }
  4616. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  4617. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  4618. return this.direction;
  4619. };
  4620. HemisphericLight.prototype.getShadowGenerator = function () {
  4621. return null;
  4622. };
  4623. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  4624. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4625. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  4626. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  4627. };
  4628. HemisphericLight.prototype._getWorldMatrix = function () {
  4629. if (!this._worldMatrix) {
  4630. this._worldMatrix = BABYLON.Matrix.Identity();
  4631. }
  4632. return this._worldMatrix;
  4633. };
  4634. return HemisphericLight;
  4635. })(BABYLON.Light);
  4636. BABYLON.HemisphericLight = HemisphericLight;
  4637. })(BABYLON || (BABYLON = {}));
  4638. var BABYLON;
  4639. (function (BABYLON) {
  4640. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  4641. if (boxMin.x > sphereCenter.x + sphereRadius)
  4642. return false;
  4643. if (sphereCenter.x - sphereRadius > boxMax.x)
  4644. return false;
  4645. if (boxMin.y > sphereCenter.y + sphereRadius)
  4646. return false;
  4647. if (sphereCenter.y - sphereRadius > boxMax.y)
  4648. return false;
  4649. if (boxMin.z > sphereCenter.z + sphereRadius)
  4650. return false;
  4651. if (sphereCenter.z - sphereRadius > boxMax.z)
  4652. return false;
  4653. return true;
  4654. };
  4655. var getLowestRoot = function (a, b, c, maxR) {
  4656. var determinant = b * b - 4.0 * a * c;
  4657. var result = { root: 0, found: false };
  4658. if (determinant < 0)
  4659. return result;
  4660. var sqrtD = Math.sqrt(determinant);
  4661. var r1 = (-b - sqrtD) / (2.0 * a);
  4662. var r2 = (-b + sqrtD) / (2.0 * a);
  4663. if (r1 > r2) {
  4664. var temp = r2;
  4665. r2 = r1;
  4666. r1 = temp;
  4667. }
  4668. if (r1 > 0 && r1 < maxR) {
  4669. result.root = r1;
  4670. result.found = true;
  4671. return result;
  4672. }
  4673. if (r2 > 0 && r2 < maxR) {
  4674. result.root = r2;
  4675. result.found = true;
  4676. return result;
  4677. }
  4678. return result;
  4679. };
  4680. var Collider = (function () {
  4681. function Collider() {
  4682. this.radius = new BABYLON.Vector3(1, 1, 1);
  4683. this.retry = 0;
  4684. this.basePointWorld = BABYLON.Vector3.Zero();
  4685. this.velocityWorld = BABYLON.Vector3.Zero();
  4686. this.normalizedVelocity = BABYLON.Vector3.Zero();
  4687. this._collisionPoint = BABYLON.Vector3.Zero();
  4688. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  4689. this._tempVector = BABYLON.Vector3.Zero();
  4690. this._tempVector2 = BABYLON.Vector3.Zero();
  4691. this._tempVector3 = BABYLON.Vector3.Zero();
  4692. this._tempVector4 = BABYLON.Vector3.Zero();
  4693. this._edge = BABYLON.Vector3.Zero();
  4694. this._baseToVertex = BABYLON.Vector3.Zero();
  4695. this._destinationPoint = BABYLON.Vector3.Zero();
  4696. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  4697. this._displacementVector = BABYLON.Vector3.Zero();
  4698. }
  4699. Collider.prototype._initialize = function (source, dir, e) {
  4700. this.velocity = dir;
  4701. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  4702. this.basePoint = source;
  4703. source.multiplyToRef(this.radius, this.basePointWorld);
  4704. dir.multiplyToRef(this.radius, this.velocityWorld);
  4705. this.velocityWorldLength = this.velocityWorld.length();
  4706. this.epsilon = e;
  4707. this.collisionFound = false;
  4708. };
  4709. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  4710. pa.subtractToRef(point, this._tempVector);
  4711. pb.subtractToRef(point, this._tempVector2);
  4712. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  4713. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4714. if (d < 0)
  4715. return false;
  4716. pc.subtractToRef(point, this._tempVector3);
  4717. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  4718. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4719. if (d < 0)
  4720. return false;
  4721. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  4722. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4723. return d >= 0;
  4724. };
  4725. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  4726. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  4727. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  4728. if (distance > this.velocityWorldLength + max + sphereRadius) {
  4729. return false;
  4730. }
  4731. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  4732. return false;
  4733. return true;
  4734. };
  4735. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  4736. var t0;
  4737. var embeddedInPlane = false;
  4738. if (!subMesh._trianglePlanes) {
  4739. subMesh._trianglePlanes = [];
  4740. }
  4741. if (!subMesh._trianglePlanes[faceIndex]) {
  4742. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  4743. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  4744. }
  4745. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  4746. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  4747. return;
  4748. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  4749. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  4750. if (normalDotVelocity == 0) {
  4751. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  4752. return;
  4753. embeddedInPlane = true;
  4754. t0 = 0;
  4755. } else {
  4756. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4757. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  4758. if (t0 > t1) {
  4759. var temp = t1;
  4760. t1 = t0;
  4761. t0 = temp;
  4762. }
  4763. if (t0 > 1.0 || t1 < 0.0)
  4764. return;
  4765. if (t0 < 0)
  4766. t0 = 0;
  4767. if (t0 > 1.0)
  4768. t0 = 1.0;
  4769. }
  4770. this._collisionPoint.copyFromFloats(0, 0, 0);
  4771. var found = false;
  4772. var t = 1.0;
  4773. if (!embeddedInPlane) {
  4774. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  4775. this.velocity.scaleToRef(t0, this._tempVector);
  4776. this._planeIntersectionPoint.addInPlace(this._tempVector);
  4777. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  4778. found = true;
  4779. t = t0;
  4780. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  4781. }
  4782. }
  4783. if (!found) {
  4784. var velocitySquaredLength = this.velocity.lengthSquared();
  4785. var a = velocitySquaredLength;
  4786. this.basePoint.subtractToRef(p1, this._tempVector);
  4787. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4788. var c = this._tempVector.lengthSquared() - 1.0;
  4789. var lowestRoot = getLowestRoot(a, b, c, t);
  4790. if (lowestRoot.found) {
  4791. t = lowestRoot.root;
  4792. found = true;
  4793. this._collisionPoint.copyFrom(p1);
  4794. }
  4795. this.basePoint.subtractToRef(p2, this._tempVector);
  4796. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4797. c = this._tempVector.lengthSquared() - 1.0;
  4798. lowestRoot = getLowestRoot(a, b, c, t);
  4799. if (lowestRoot.found) {
  4800. t = lowestRoot.root;
  4801. found = true;
  4802. this._collisionPoint.copyFrom(p2);
  4803. }
  4804. this.basePoint.subtractToRef(p3, this._tempVector);
  4805. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  4806. c = this._tempVector.lengthSquared() - 1.0;
  4807. lowestRoot = getLowestRoot(a, b, c, t);
  4808. if (lowestRoot.found) {
  4809. t = lowestRoot.root;
  4810. found = true;
  4811. this._collisionPoint.copyFrom(p3);
  4812. }
  4813. p2.subtractToRef(p1, this._edge);
  4814. p1.subtractToRef(this.basePoint, this._baseToVertex);
  4815. var edgeSquaredLength = this._edge.lengthSquared();
  4816. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4817. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4818. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4819. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4820. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4821. lowestRoot = getLowestRoot(a, b, c, t);
  4822. if (lowestRoot.found) {
  4823. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4824. if (f >= 0.0 && f <= 1.0) {
  4825. t = lowestRoot.root;
  4826. found = true;
  4827. this._edge.scaleInPlace(f);
  4828. p1.addToRef(this._edge, this._collisionPoint);
  4829. }
  4830. }
  4831. p3.subtractToRef(p2, this._edge);
  4832. p2.subtractToRef(this.basePoint, this._baseToVertex);
  4833. edgeSquaredLength = this._edge.lengthSquared();
  4834. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4835. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4836. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4837. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4838. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4839. lowestRoot = getLowestRoot(a, b, c, t);
  4840. if (lowestRoot.found) {
  4841. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4842. if (f >= 0.0 && f <= 1.0) {
  4843. t = lowestRoot.root;
  4844. found = true;
  4845. this._edge.scaleInPlace(f);
  4846. p2.addToRef(this._edge, this._collisionPoint);
  4847. }
  4848. }
  4849. p1.subtractToRef(p3, this._edge);
  4850. p3.subtractToRef(this.basePoint, this._baseToVertex);
  4851. edgeSquaredLength = this._edge.lengthSquared();
  4852. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  4853. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  4854. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  4855. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  4856. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  4857. lowestRoot = getLowestRoot(a, b, c, t);
  4858. if (lowestRoot.found) {
  4859. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  4860. if (f >= 0.0 && f <= 1.0) {
  4861. t = lowestRoot.root;
  4862. found = true;
  4863. this._edge.scaleInPlace(f);
  4864. p3.addToRef(this._edge, this._collisionPoint);
  4865. }
  4866. }
  4867. }
  4868. if (found) {
  4869. var distToCollision = t * this.velocity.length();
  4870. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  4871. if (!this.intersectionPoint) {
  4872. this.intersectionPoint = this._collisionPoint.clone();
  4873. } else {
  4874. this.intersectionPoint.copyFrom(this._collisionPoint);
  4875. }
  4876. this.nearestDistance = distToCollision;
  4877. this.collisionFound = true;
  4878. this.collidedMesh = subMesh.getMesh();
  4879. }
  4880. }
  4881. };
  4882. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  4883. for (var i = indexStart; i < indexEnd; i += 3) {
  4884. var p1 = pts[indices[i] - decal];
  4885. var p2 = pts[indices[i + 1] - decal];
  4886. var p3 = pts[indices[i + 2] - decal];
  4887. this._testTriangle(i, subMesh, p3, p2, p1);
  4888. }
  4889. };
  4890. Collider.prototype._getResponse = function (pos, vel) {
  4891. pos.addToRef(vel, this._destinationPoint);
  4892. vel.scaleInPlace((this.nearestDistance / vel.length()));
  4893. this.basePoint.addToRef(vel, pos);
  4894. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  4895. this._slidePlaneNormal.normalize();
  4896. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  4897. pos.addInPlace(this._displacementVector);
  4898. this.intersectionPoint.addInPlace(this._displacementVector);
  4899. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  4900. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  4901. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  4902. };
  4903. return Collider;
  4904. })();
  4905. BABYLON.Collider = Collider;
  4906. })(BABYLON || (BABYLON = {}));
  4907. var __extends = this.__extends || function (d, b) {
  4908. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4909. function __() { this.constructor = d; }
  4910. __.prototype = b.prototype;
  4911. d.prototype = new __();
  4912. };
  4913. var BABYLON;
  4914. (function (BABYLON) {
  4915. var Camera = (function (_super) {
  4916. __extends(Camera, _super);
  4917. function Camera(name, position, scene) {
  4918. _super.call(this, name, scene);
  4919. this.position = position;
  4920. this.upVector = BABYLON.Vector3.Up();
  4921. this.orthoLeft = null;
  4922. this.orthoRight = null;
  4923. this.orthoBottom = null;
  4924. this.orthoTop = null;
  4925. this.fov = 0.8;
  4926. this.minZ = 1.0;
  4927. this.maxZ = 10000.0;
  4928. this.inertia = 0.9;
  4929. this.mode = Camera.PERSPECTIVE_CAMERA;
  4930. this.isIntermediate = false;
  4931. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  4932. this.subCameras = [];
  4933. this.layerMask = 0xFFFFFFFF;
  4934. this._computedViewMatrix = BABYLON.Matrix.Identity();
  4935. this._projectionMatrix = new BABYLON.Matrix();
  4936. this._postProcesses = new Array();
  4937. this._postProcessesTakenIndices = [];
  4938. scene.cameras.push(this);
  4939. if (!scene.activeCamera) {
  4940. scene.activeCamera = this;
  4941. }
  4942. }
  4943. Camera.prototype._initCache = function () {
  4944. _super.prototype._initCache.call(this);
  4945. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4946. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4947. this._cache.mode = undefined;
  4948. this._cache.minZ = undefined;
  4949. this._cache.maxZ = undefined;
  4950. this._cache.fov = undefined;
  4951. this._cache.aspectRatio = undefined;
  4952. this._cache.orthoLeft = undefined;
  4953. this._cache.orthoRight = undefined;
  4954. this._cache.orthoBottom = undefined;
  4955. this._cache.orthoTop = undefined;
  4956. this._cache.renderWidth = undefined;
  4957. this._cache.renderHeight = undefined;
  4958. };
  4959. Camera.prototype._updateCache = function (ignoreParentClass) {
  4960. if (!ignoreParentClass) {
  4961. _super.prototype._updateCache.call(this);
  4962. }
  4963. var engine = this.getEngine();
  4964. this._cache.position.copyFrom(this.position);
  4965. this._cache.upVector.copyFrom(this.upVector);
  4966. this._cache.mode = this.mode;
  4967. this._cache.minZ = this.minZ;
  4968. this._cache.maxZ = this.maxZ;
  4969. this._cache.fov = this.fov;
  4970. this._cache.aspectRatio = engine.getAspectRatio(this);
  4971. this._cache.orthoLeft = this.orthoLeft;
  4972. this._cache.orthoRight = this.orthoRight;
  4973. this._cache.orthoBottom = this.orthoBottom;
  4974. this._cache.orthoTop = this.orthoTop;
  4975. this._cache.renderWidth = engine.getRenderWidth();
  4976. this._cache.renderHeight = engine.getRenderHeight();
  4977. };
  4978. Camera.prototype._updateFromScene = function () {
  4979. this.updateCache();
  4980. this._update();
  4981. };
  4982. Camera.prototype._isSynchronized = function () {
  4983. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  4984. };
  4985. Camera.prototype._isSynchronizedViewMatrix = function () {
  4986. if (!_super.prototype._isSynchronized.call(this))
  4987. return false;
  4988. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  4989. };
  4990. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  4991. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  4992. if (!check) {
  4993. return false;
  4994. }
  4995. var engine = this.getEngine();
  4996. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  4997. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  4998. } else {
  4999. 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();
  5000. }
  5001. return check;
  5002. };
  5003. Camera.prototype.attachControl = function (element) {
  5004. };
  5005. Camera.prototype.detachControl = function (element) {
  5006. };
  5007. Camera.prototype._update = function () {
  5008. };
  5009. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  5010. if (typeof insertAt === "undefined") { insertAt = null; }
  5011. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  5012. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  5013. return 0;
  5014. }
  5015. if (insertAt == null || insertAt < 0) {
  5016. this._postProcesses.push(postProcess);
  5017. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  5018. return this._postProcesses.length - 1;
  5019. }
  5020. var add = 0;
  5021. if (this._postProcesses[insertAt]) {
  5022. var start = this._postProcesses.length - 1;
  5023. for (var i = start; i >= insertAt + 1; --i) {
  5024. this._postProcesses[i + 1] = this._postProcesses[i];
  5025. }
  5026. add = 1;
  5027. }
  5028. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5029. if (this._postProcessesTakenIndices[i] < insertAt) {
  5030. continue;
  5031. }
  5032. start = this._postProcessesTakenIndices.length - 1;
  5033. for (var j = start; j >= i; --j) {
  5034. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  5035. }
  5036. this._postProcessesTakenIndices[i] = insertAt;
  5037. break;
  5038. }
  5039. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  5040. this._postProcessesTakenIndices.push(insertAt);
  5041. }
  5042. var result = insertAt + add;
  5043. this._postProcesses[result] = postProcess;
  5044. return result;
  5045. };
  5046. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  5047. if (typeof atIndices === "undefined") { atIndices = null; }
  5048. var result = [];
  5049. if (!atIndices) {
  5050. var length = this._postProcesses.length;
  5051. for (var i = 0; i < length; i++) {
  5052. if (this._postProcesses[i] !== postProcess) {
  5053. continue;
  5054. }
  5055. delete this._postProcesses[i];
  5056. var index = this._postProcessesTakenIndices.indexOf(i);
  5057. this._postProcessesTakenIndices.splice(index, 1);
  5058. }
  5059. } else {
  5060. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  5061. for (i = 0; i < atIndices.length; i++) {
  5062. var foundPostProcess = this._postProcesses[atIndices[i]];
  5063. if (foundPostProcess !== postProcess) {
  5064. result.push(i);
  5065. continue;
  5066. }
  5067. delete this._postProcesses[atIndices[i]];
  5068. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  5069. this._postProcessesTakenIndices.splice(index, 1);
  5070. }
  5071. }
  5072. return result;
  5073. };
  5074. Camera.prototype.getWorldMatrix = function () {
  5075. if (!this._worldMatrix) {
  5076. this._worldMatrix = BABYLON.Matrix.Identity();
  5077. }
  5078. var viewMatrix = this.getViewMatrix();
  5079. viewMatrix.invertToRef(this._worldMatrix);
  5080. return this._worldMatrix;
  5081. };
  5082. Camera.prototype._getViewMatrix = function () {
  5083. return BABYLON.Matrix.Identity();
  5084. };
  5085. Camera.prototype.getViewMatrix = function () {
  5086. this._computedViewMatrix = this._computeViewMatrix();
  5087. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  5088. return this._computedViewMatrix;
  5089. }
  5090. if (!this._worldMatrix) {
  5091. this._worldMatrix = BABYLON.Matrix.Identity();
  5092. }
  5093. this._computedViewMatrix.invertToRef(this._worldMatrix);
  5094. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  5095. this._computedViewMatrix.invert();
  5096. this._currentRenderId = this.getScene().getRenderId();
  5097. return this._computedViewMatrix;
  5098. };
  5099. Camera.prototype._computeViewMatrix = function (force) {
  5100. if (!force && this._isSynchronizedViewMatrix()) {
  5101. return this._computedViewMatrix;
  5102. }
  5103. this._computedViewMatrix = this._getViewMatrix();
  5104. if (!this.parent || !this.parent.getWorldMatrix) {
  5105. this._currentRenderId = this.getScene().getRenderId();
  5106. }
  5107. return this._computedViewMatrix;
  5108. };
  5109. Camera.prototype.getProjectionMatrix = function (force) {
  5110. if (!force && this._isSynchronizedProjectionMatrix()) {
  5111. return this._projectionMatrix;
  5112. }
  5113. var engine = this.getEngine();
  5114. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5115. if (this.minZ <= 0) {
  5116. this.minZ = 0.1;
  5117. }
  5118. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  5119. return this._projectionMatrix;
  5120. }
  5121. var halfWidth = engine.getRenderWidth() / 2.0;
  5122. var halfHeight = engine.getRenderHeight() / 2.0;
  5123. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  5124. return this._projectionMatrix;
  5125. };
  5126. Camera.prototype.dispose = function () {
  5127. var index = this.getScene().cameras.indexOf(this);
  5128. this.getScene().cameras.splice(index, 1);
  5129. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5130. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  5131. }
  5132. };
  5133. Camera.PERSPECTIVE_CAMERA = 0;
  5134. Camera.ORTHOGRAPHIC_CAMERA = 1;
  5135. return Camera;
  5136. })(BABYLON.Node);
  5137. BABYLON.Camera = Camera;
  5138. })(BABYLON || (BABYLON = {}));
  5139. var __extends = this.__extends || function (d, b) {
  5140. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5141. function __() { this.constructor = d; }
  5142. __.prototype = b.prototype;
  5143. d.prototype = new __();
  5144. };
  5145. var BABYLON;
  5146. (function (BABYLON) {
  5147. var TargetCamera = (function (_super) {
  5148. __extends(TargetCamera, _super);
  5149. function TargetCamera(name, position, scene) {
  5150. _super.call(this, name, position, scene);
  5151. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5152. this.cameraRotation = new BABYLON.Vector2(0, 0);
  5153. this.rotation = new BABYLON.Vector3(0, 0, 0);
  5154. this.speed = 2.0;
  5155. this.noRotationConstraint = false;
  5156. this.lockedTarget = null;
  5157. this._currentTarget = BABYLON.Vector3.Zero();
  5158. this._viewMatrix = BABYLON.Matrix.Zero();
  5159. this._camMatrix = BABYLON.Matrix.Zero();
  5160. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  5161. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  5162. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  5163. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  5164. this._lookAtTemp = BABYLON.Matrix.Zero();
  5165. this._tempMatrix = BABYLON.Matrix.Zero();
  5166. }
  5167. TargetCamera.prototype._getLockedTargetPosition = function () {
  5168. if (!this.lockedTarget) {
  5169. return null;
  5170. }
  5171. return this.lockedTarget.position || this.lockedTarget;
  5172. };
  5173. TargetCamera.prototype._initCache = function () {
  5174. _super.prototype._initCache.call(this);
  5175. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5176. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5177. };
  5178. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  5179. if (!ignoreParentClass) {
  5180. _super.prototype._updateCache.call(this);
  5181. }
  5182. var lockedTargetPosition = this._getLockedTargetPosition();
  5183. if (!lockedTargetPosition) {
  5184. this._cache.lockedTarget = null;
  5185. } else {
  5186. if (!this._cache.lockedTarget) {
  5187. this._cache.lockedTarget = lockedTargetPosition.clone();
  5188. } else {
  5189. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  5190. }
  5191. }
  5192. this._cache.rotation.copyFrom(this.rotation);
  5193. };
  5194. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  5195. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  5196. return false;
  5197. }
  5198. var lockedTargetPosition = this._getLockedTargetPosition();
  5199. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  5200. };
  5201. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  5202. return this.speed * ((BABYLON.Tools.GetDeltaTime() / (BABYLON.Tools.GetFps() * 10.0)));
  5203. };
  5204. TargetCamera.prototype.setTarget = function (target) {
  5205. this.upVector.normalize();
  5206. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  5207. this._camMatrix.invert();
  5208. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  5209. var vDir = target.subtract(this.position);
  5210. if (vDir.x >= 0.0) {
  5211. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5212. } else {
  5213. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5214. }
  5215. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5216. if (isNaN(this.rotation.x)) {
  5217. this.rotation.x = 0;
  5218. }
  5219. if (isNaN(this.rotation.y)) {
  5220. this.rotation.y = 0;
  5221. }
  5222. if (isNaN(this.rotation.z)) {
  5223. this.rotation.z = 0;
  5224. }
  5225. };
  5226. TargetCamera.prototype.getTarget = function () {
  5227. return this._currentTarget;
  5228. };
  5229. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5230. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5231. };
  5232. TargetCamera.prototype._updatePosition = function () {
  5233. this.position.addInPlace(this.cameraDirection);
  5234. };
  5235. TargetCamera.prototype._update = function () {
  5236. var needToMove = this._decideIfNeedsToMove();
  5237. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5238. if (needToMove) {
  5239. this._updatePosition();
  5240. }
  5241. if (needToRotate) {
  5242. this.rotation.x += this.cameraRotation.x;
  5243. this.rotation.y += this.cameraRotation.y;
  5244. if (!this.noRotationConstraint) {
  5245. var limit = (Math.PI / 2) * 0.95;
  5246. if (this.rotation.x > limit)
  5247. this.rotation.x = limit;
  5248. if (this.rotation.x < -limit)
  5249. this.rotation.x = -limit;
  5250. }
  5251. }
  5252. if (needToMove) {
  5253. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  5254. this.cameraDirection.x = 0;
  5255. }
  5256. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  5257. this.cameraDirection.y = 0;
  5258. }
  5259. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  5260. this.cameraDirection.z = 0;
  5261. }
  5262. this.cameraDirection.scaleInPlace(this.inertia);
  5263. }
  5264. if (needToRotate) {
  5265. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  5266. this.cameraRotation.x = 0;
  5267. }
  5268. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  5269. this.cameraRotation.y = 0;
  5270. }
  5271. this.cameraRotation.scaleInPlace(this.inertia);
  5272. }
  5273. };
  5274. TargetCamera.prototype._getViewMatrix = function () {
  5275. if (!this.lockedTarget) {
  5276. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  5277. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  5278. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5279. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  5280. this._lookAtTemp.invert();
  5281. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  5282. } else {
  5283. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5284. }
  5285. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  5286. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  5287. } else {
  5288. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  5289. }
  5290. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  5291. return this._viewMatrix;
  5292. };
  5293. return TargetCamera;
  5294. })(BABYLON.Camera);
  5295. BABYLON.TargetCamera = TargetCamera;
  5296. })(BABYLON || (BABYLON = {}));
  5297. var __extends = this.__extends || function (d, b) {
  5298. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5299. function __() { this.constructor = d; }
  5300. __.prototype = b.prototype;
  5301. d.prototype = new __();
  5302. };
  5303. var BABYLON;
  5304. (function (BABYLON) {
  5305. var FollowCamera = (function (_super) {
  5306. __extends(FollowCamera, _super);
  5307. function FollowCamera(name, position, scene) {
  5308. _super.call(this, name, position, scene);
  5309. this.radius = 12;
  5310. this.rotationOffset = 0;
  5311. this.heightOffset = 4;
  5312. this.cameraAcceleration = 0.05;
  5313. this.maxCameraSpeed = 20;
  5314. }
  5315. FollowCamera.prototype.getRadians = function (degrees) {
  5316. return degrees * Math.PI / 180;
  5317. };
  5318. FollowCamera.prototype.follow = function (cameraTarget) {
  5319. if (!cameraTarget)
  5320. return;
  5321. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  5322. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  5323. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  5324. var dx = targetX - this.position.x;
  5325. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  5326. var dz = (targetZ) - this.position.z;
  5327. var vx = dx * this.cameraAcceleration * 2;
  5328. var vy = dy * this.cameraAcceleration;
  5329. var vz = dz * this.cameraAcceleration * 2;
  5330. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  5331. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5332. }
  5333. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  5334. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5335. }
  5336. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  5337. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5338. }
  5339. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  5340. this.setTarget(cameraTarget.position);
  5341. };
  5342. FollowCamera.prototype._update = function () {
  5343. _super.prototype._update.call(this);
  5344. this.follow(this.target);
  5345. };
  5346. return FollowCamera;
  5347. })(BABYLON.TargetCamera);
  5348. BABYLON.FollowCamera = FollowCamera;
  5349. })(BABYLON || (BABYLON = {}));
  5350. var __extends = this.__extends || function (d, b) {
  5351. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5352. function __() { this.constructor = d; }
  5353. __.prototype = b.prototype;
  5354. d.prototype = new __();
  5355. };
  5356. var BABYLON;
  5357. (function (BABYLON) {
  5358. var FreeCamera = (function (_super) {
  5359. __extends(FreeCamera, _super);
  5360. function FreeCamera(name, position, scene) {
  5361. _super.call(this, name, position, scene);
  5362. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  5363. this.keysUp = [38];
  5364. this.keysDown = [40];
  5365. this.keysLeft = [37];
  5366. this.keysRight = [39];
  5367. this.checkCollisions = false;
  5368. this.applyGravity = false;
  5369. this.angularSensibility = 2000.0;
  5370. this._keys = [];
  5371. this._collider = new BABYLON.Collider();
  5372. this._needMoveForGravity = true;
  5373. this._oldPosition = BABYLON.Vector3.Zero();
  5374. this._diffPosition = BABYLON.Vector3.Zero();
  5375. this._newPosition = BABYLON.Vector3.Zero();
  5376. }
  5377. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  5378. var _this = this;
  5379. var previousPosition;
  5380. var engine = this.getEngine();
  5381. if (this._attachedElement) {
  5382. return;
  5383. }
  5384. this._attachedElement = element;
  5385. if (this._onMouseDown === undefined) {
  5386. this._onMouseDown = function (evt) {
  5387. previousPosition = {
  5388. x: evt.clientX,
  5389. y: evt.clientY
  5390. };
  5391. if (!noPreventDefault) {
  5392. evt.preventDefault();
  5393. }
  5394. };
  5395. this._onMouseUp = function (evt) {
  5396. previousPosition = null;
  5397. if (!noPreventDefault) {
  5398. evt.preventDefault();
  5399. }
  5400. };
  5401. this._onMouseOut = function (evt) {
  5402. previousPosition = null;
  5403. _this._keys = [];
  5404. if (!noPreventDefault) {
  5405. evt.preventDefault();
  5406. }
  5407. };
  5408. this._onMouseMove = function (evt) {
  5409. if (!previousPosition && !engine.isPointerLock) {
  5410. return;
  5411. }
  5412. var offsetX;
  5413. var offsetY;
  5414. if (!engine.isPointerLock) {
  5415. offsetX = evt.clientX - previousPosition.x;
  5416. offsetY = evt.clientY - previousPosition.y;
  5417. } else {
  5418. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5419. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5420. }
  5421. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  5422. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  5423. previousPosition = {
  5424. x: evt.clientX,
  5425. y: evt.clientY
  5426. };
  5427. if (!noPreventDefault) {
  5428. evt.preventDefault();
  5429. }
  5430. };
  5431. this._onKeyDown = function (evt) {
  5432. 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) {
  5433. var index = _this._keys.indexOf(evt.keyCode);
  5434. if (index === -1) {
  5435. _this._keys.push(evt.keyCode);
  5436. }
  5437. if (!noPreventDefault) {
  5438. evt.preventDefault();
  5439. }
  5440. }
  5441. };
  5442. this._onKeyUp = function (evt) {
  5443. 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) {
  5444. var index = _this._keys.indexOf(evt.keyCode);
  5445. if (index >= 0) {
  5446. _this._keys.splice(index, 1);
  5447. }
  5448. if (!noPreventDefault) {
  5449. evt.preventDefault();
  5450. }
  5451. }
  5452. };
  5453. this._onLostFocus = function () {
  5454. _this._keys = [];
  5455. };
  5456. this._reset = function () {
  5457. _this._keys = [];
  5458. previousPosition = null;
  5459. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5460. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  5461. };
  5462. }
  5463. element.addEventListener("mousedown", this._onMouseDown, false);
  5464. element.addEventListener("mouseup", this._onMouseUp, false);
  5465. element.addEventListener("mouseout", this._onMouseOut, false);
  5466. element.addEventListener("mousemove", this._onMouseMove, false);
  5467. BABYLON.Tools.RegisterTopRootEvents([
  5468. { name: "keydown", handler: this._onKeyDown },
  5469. { name: "keyup", handler: this._onKeyUp },
  5470. { name: "blur", handler: this._onLostFocus }
  5471. ]);
  5472. };
  5473. FreeCamera.prototype.detachControl = function (element) {
  5474. if (this._attachedElement != element) {
  5475. return;
  5476. }
  5477. element.removeEventListener("mousedown", this._onMouseDown);
  5478. element.removeEventListener("mouseup", this._onMouseUp);
  5479. element.removeEventListener("mouseout", this._onMouseOut);
  5480. element.removeEventListener("mousemove", this._onMouseMove);
  5481. BABYLON.Tools.UnregisterTopRootEvents([
  5482. { name: "keydown", handler: this._onKeyDown },
  5483. { name: "keyup", handler: this._onKeyUp },
  5484. { name: "blur", handler: this._onLostFocus }
  5485. ]);
  5486. this._attachedElement = null;
  5487. if (this._reset) {
  5488. this._reset();
  5489. }
  5490. };
  5491. FreeCamera.prototype._collideWithWorld = function (velocity) {
  5492. var globalPosition;
  5493. if (this.parent) {
  5494. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  5495. } else {
  5496. globalPosition = this.position;
  5497. }
  5498. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  5499. this._collider.radius = this.ellipsoid;
  5500. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  5501. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  5502. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  5503. this.position.addInPlace(this._diffPosition);
  5504. if (this.onCollide) {
  5505. this.onCollide(this._collider.collidedMesh);
  5506. }
  5507. }
  5508. };
  5509. FreeCamera.prototype._checkInputs = function () {
  5510. if (!this._localDirection) {
  5511. this._localDirection = BABYLON.Vector3.Zero();
  5512. this._transformedDirection = BABYLON.Vector3.Zero();
  5513. }
  5514. for (var index = 0; index < this._keys.length; index++) {
  5515. var keyCode = this._keys[index];
  5516. var speed = this._computeLocalCameraSpeed();
  5517. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5518. this._localDirection.copyFromFloats(-speed, 0, 0);
  5519. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5520. this._localDirection.copyFromFloats(0, 0, speed);
  5521. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5522. this._localDirection.copyFromFloats(speed, 0, 0);
  5523. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5524. this._localDirection.copyFromFloats(0, 0, -speed);
  5525. }
  5526. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  5527. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  5528. this.cameraDirection.addInPlace(this._transformedDirection);
  5529. }
  5530. };
  5531. FreeCamera.prototype._decideIfNeedsToMove = function () {
  5532. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5533. };
  5534. FreeCamera.prototype._updatePosition = function () {
  5535. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  5536. this._collideWithWorld(this.cameraDirection);
  5537. if (this.applyGravity) {
  5538. var oldPosition = this.position;
  5539. this._collideWithWorld(this.getScene().gravity);
  5540. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  5541. }
  5542. } else {
  5543. this.position.addInPlace(this.cameraDirection);
  5544. }
  5545. };
  5546. FreeCamera.prototype._update = function () {
  5547. this._checkInputs();
  5548. _super.prototype._update.call(this);
  5549. };
  5550. return FreeCamera;
  5551. })(BABYLON.TargetCamera);
  5552. BABYLON.FreeCamera = FreeCamera;
  5553. })(BABYLON || (BABYLON = {}));
  5554. var __extends = this.__extends || function (d, b) {
  5555. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5556. function __() { this.constructor = d; }
  5557. __.prototype = b.prototype;
  5558. d.prototype = new __();
  5559. };
  5560. var BABYLON;
  5561. (function (BABYLON) {
  5562. var TouchCamera = (function (_super) {
  5563. __extends(TouchCamera, _super);
  5564. function TouchCamera(name, position, scene) {
  5565. _super.call(this, name, position, scene);
  5566. this._offsetX = null;
  5567. this._offsetY = null;
  5568. this._pointerCount = 0;
  5569. this._pointerPressed = [];
  5570. this.angularSensibility = 200000.0;
  5571. this.moveSensibility = 500.0;
  5572. }
  5573. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5574. var _this = this;
  5575. var previousPosition;
  5576. if (this._attachedCanvas) {
  5577. return;
  5578. }
  5579. this._attachedCanvas = canvas;
  5580. if (this._onPointerDown === undefined) {
  5581. this._onPointerDown = function (evt) {
  5582. if (!noPreventDefault) {
  5583. evt.preventDefault();
  5584. }
  5585. _this._pointerPressed.push(evt.pointerId);
  5586. if (_this._pointerPressed.length !== 1) {
  5587. return;
  5588. }
  5589. previousPosition = {
  5590. x: evt.clientX,
  5591. y: evt.clientY
  5592. };
  5593. };
  5594. this._onPointerUp = function (evt) {
  5595. if (!noPreventDefault) {
  5596. evt.preventDefault();
  5597. }
  5598. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5599. if (index === -1) {
  5600. return;
  5601. }
  5602. _this._pointerPressed.splice(index, 1);
  5603. if (index != 0) {
  5604. return;
  5605. }
  5606. previousPosition = null;
  5607. _this._offsetX = null;
  5608. _this._offsetY = null;
  5609. };
  5610. this._onPointerMove = function (evt) {
  5611. if (!noPreventDefault) {
  5612. evt.preventDefault();
  5613. }
  5614. if (!previousPosition) {
  5615. return;
  5616. }
  5617. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5618. if (index != 0) {
  5619. return;
  5620. }
  5621. _this._offsetX = evt.clientX - previousPosition.x;
  5622. _this._offsetY = -(evt.clientY - previousPosition.y);
  5623. };
  5624. this._onLostFocus = function () {
  5625. _this._offsetX = null;
  5626. _this._offsetY = null;
  5627. };
  5628. }
  5629. canvas.addEventListener("pointerdown", this._onPointerDown);
  5630. canvas.addEventListener("pointerup", this._onPointerUp);
  5631. canvas.addEventListener("pointerout", this._onPointerUp);
  5632. canvas.addEventListener("pointermove", this._onPointerMove);
  5633. BABYLON.Tools.RegisterTopRootEvents([
  5634. { name: "blur", handler: this._onLostFocus }
  5635. ]);
  5636. };
  5637. TouchCamera.prototype.detachControl = function (canvas) {
  5638. if (this._attachedCanvas != canvas) {
  5639. return;
  5640. }
  5641. canvas.removeEventListener("pointerdown", this._onPointerDown);
  5642. canvas.removeEventListener("pointerup", this._onPointerUp);
  5643. canvas.removeEventListener("pointerout", this._onPointerUp);
  5644. canvas.removeEventListener("pointermove", this._onPointerMove);
  5645. BABYLON.Tools.UnregisterTopRootEvents([
  5646. { name: "blur", handler: this._onLostFocus }
  5647. ]);
  5648. this._attachedCanvas = null;
  5649. };
  5650. TouchCamera.prototype._checkInputs = function () {
  5651. if (!this._offsetX) {
  5652. return;
  5653. }
  5654. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  5655. if (this._pointerPressed.length > 1) {
  5656. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  5657. } else {
  5658. var speed = this._computeLocalCameraSpeed();
  5659. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5660. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5661. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5662. }
  5663. };
  5664. return TouchCamera;
  5665. })(BABYLON.FreeCamera);
  5666. BABYLON.TouchCamera = TouchCamera;
  5667. })(BABYLON || (BABYLON = {}));
  5668. var __extends = this.__extends || function (d, b) {
  5669. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5670. function __() { this.constructor = d; }
  5671. __.prototype = b.prototype;
  5672. d.prototype = new __();
  5673. };
  5674. var BABYLON;
  5675. (function (BABYLON) {
  5676. var DeviceOrientationCamera = (function (_super) {
  5677. __extends(DeviceOrientationCamera, _super);
  5678. function DeviceOrientationCamera(name, position, scene) {
  5679. var _this = this;
  5680. _super.call(this, name, position, scene);
  5681. this._offsetX = null;
  5682. this._offsetY = null;
  5683. this._orientationGamma = 0;
  5684. this._orientationBeta = 0;
  5685. this._initialOrientationGamma = 0;
  5686. this._initialOrientationBeta = 0;
  5687. this.angularSensibility = 10000.0;
  5688. this.moveSensibility = 50.0;
  5689. window.addEventListener("resize", function () {
  5690. _this._initialOrientationGamma = null;
  5691. }, false);
  5692. }
  5693. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5694. var _this = this;
  5695. if (this._attachedCanvas) {
  5696. return;
  5697. }
  5698. this._attachedCanvas = canvas;
  5699. if (!this._orientationChanged) {
  5700. this._orientationChanged = function (evt) {
  5701. if (!_this._initialOrientationGamma) {
  5702. _this._initialOrientationGamma = evt.gamma;
  5703. _this._initialOrientationBeta = evt.beta;
  5704. }
  5705. _this._orientationGamma = evt.gamma;
  5706. _this._orientationBeta = evt.beta;
  5707. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  5708. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  5709. };
  5710. }
  5711. window.addEventListener("deviceorientation", this._orientationChanged);
  5712. };
  5713. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  5714. if (this._attachedCanvas != canvas) {
  5715. return;
  5716. }
  5717. window.removeEventListener("deviceorientation", this._orientationChanged);
  5718. this._attachedCanvas = null;
  5719. this._orientationGamma = 0;
  5720. this._orientationBeta = 0;
  5721. this._initialOrientationGamma = 0;
  5722. this._initialOrientationBeta = 0;
  5723. };
  5724. DeviceOrientationCamera.prototype._checkInputs = function () {
  5725. if (!this._offsetX) {
  5726. return;
  5727. }
  5728. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  5729. var speed = this._computeLocalCameraSpeed();
  5730. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5731. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5732. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5733. };
  5734. return DeviceOrientationCamera;
  5735. })(BABYLON.FreeCamera);
  5736. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  5737. })(BABYLON || (BABYLON = {}));
  5738. var __extends = this.__extends || function (d, b) {
  5739. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5740. function __() { this.constructor = d; }
  5741. __.prototype = b.prototype;
  5742. d.prototype = new __();
  5743. };
  5744. var BABYLON;
  5745. (function (BABYLON) {
  5746. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  5747. var ArcRotateCamera = (function (_super) {
  5748. __extends(ArcRotateCamera, _super);
  5749. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  5750. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  5751. this.alpha = alpha;
  5752. this.beta = beta;
  5753. this.radius = radius;
  5754. this.target = target;
  5755. this.inertialAlphaOffset = 0;
  5756. this.inertialBetaOffset = 0;
  5757. this.inertialRadiusOffset = 0;
  5758. this.lowerAlphaLimit = null;
  5759. this.upperAlphaLimit = null;
  5760. this.lowerBetaLimit = 0.01;
  5761. this.upperBetaLimit = Math.PI;
  5762. this.lowerRadiusLimit = null;
  5763. this.upperRadiusLimit = null;
  5764. this.angularSensibility = 1000.0;
  5765. this.wheelPrecision = 3.0;
  5766. this.keysUp = [38];
  5767. this.keysDown = [40];
  5768. this.keysLeft = [37];
  5769. this.keysRight = [39];
  5770. this.zoomOnFactor = 1;
  5771. this.targetScreenOffset = BABYLON.Vector2.Zero();
  5772. this._keys = [];
  5773. this._viewMatrix = new BABYLON.Matrix();
  5774. this.checkCollisions = false;
  5775. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  5776. this._collider = new BABYLON.Collider();
  5777. this._previousPosition = BABYLON.Vector3.Zero();
  5778. this._collisionVelocity = BABYLON.Vector3.Zero();
  5779. this._newPosition = BABYLON.Vector3.Zero();
  5780. this.pinchPrecision = 20;
  5781. this.getViewMatrix();
  5782. }
  5783. ArcRotateCamera.prototype._getTargetPosition = function () {
  5784. return this.target.position || this.target;
  5785. };
  5786. ArcRotateCamera.prototype._initCache = function () {
  5787. _super.prototype._initCache.call(this);
  5788. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5789. this._cache.alpha = undefined;
  5790. this._cache.beta = undefined;
  5791. this._cache.radius = undefined;
  5792. this._cache.targetScreenOffset = undefined;
  5793. };
  5794. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  5795. if (!ignoreParentClass) {
  5796. _super.prototype._updateCache.call(this);
  5797. }
  5798. this._cache.target.copyFrom(this._getTargetPosition());
  5799. this._cache.alpha = this.alpha;
  5800. this._cache.beta = this.beta;
  5801. this._cache.radius = this.radius;
  5802. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  5803. };
  5804. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  5805. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  5806. return false;
  5807. 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);
  5808. };
  5809. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  5810. var _this = this;
  5811. var previousPosition;
  5812. var pointerId;
  5813. var pinchStarted = false;
  5814. var pinchPointX1, pinchPointX2;
  5815. if (this._attachedElement) {
  5816. return;
  5817. }
  5818. this._attachedElement = element;
  5819. var engine = this.getEngine();
  5820. if (this._onPointerDown === undefined) {
  5821. this._onPointerDown = function (evt) {
  5822. if (pointerId) {
  5823. return;
  5824. }
  5825. pointerId = evt.pointerId;
  5826. previousPosition = {
  5827. x: evt.clientX,
  5828. y: evt.clientY
  5829. };
  5830. if (!noPreventDefault) {
  5831. evt.preventDefault();
  5832. }
  5833. };
  5834. this._onPointerUp = function (evt) {
  5835. previousPosition = null;
  5836. pointerId = null;
  5837. if (!noPreventDefault) {
  5838. evt.preventDefault();
  5839. }
  5840. };
  5841. this._onPointerMove = function (evt) {
  5842. if (!previousPosition) {
  5843. return;
  5844. }
  5845. if (pointerId !== evt.pointerId) {
  5846. return;
  5847. }
  5848. if (pinchStarted) {
  5849. return;
  5850. }
  5851. var offsetX = evt.clientX - previousPosition.x;
  5852. var offsetY = evt.clientY - previousPosition.y;
  5853. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5854. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5855. previousPosition = {
  5856. x: evt.clientX,
  5857. y: evt.clientY
  5858. };
  5859. if (!noPreventDefault) {
  5860. evt.preventDefault();
  5861. }
  5862. };
  5863. this._onMouseMove = function (evt) {
  5864. if (!engine.isPointerLock) {
  5865. return;
  5866. }
  5867. if (pinchStarted) {
  5868. return;
  5869. }
  5870. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5871. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5872. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  5873. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  5874. if (!noPreventDefault) {
  5875. evt.preventDefault();
  5876. }
  5877. };
  5878. this._wheel = function (event) {
  5879. var delta = 0;
  5880. if (event.wheelDelta) {
  5881. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  5882. } else if (event.detail) {
  5883. delta = -event.detail / _this.wheelPrecision;
  5884. }
  5885. if (delta)
  5886. _this.inertialRadiusOffset += delta;
  5887. if (event.preventDefault) {
  5888. if (!noPreventDefault) {
  5889. event.preventDefault();
  5890. }
  5891. }
  5892. };
  5893. this._onKeyDown = function (evt) {
  5894. 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) {
  5895. var index = _this._keys.indexOf(evt.keyCode);
  5896. if (index === -1) {
  5897. _this._keys.push(evt.keyCode);
  5898. }
  5899. if (evt.preventDefault) {
  5900. if (!noPreventDefault) {
  5901. evt.preventDefault();
  5902. }
  5903. }
  5904. }
  5905. };
  5906. this._onKeyUp = function (evt) {
  5907. 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) {
  5908. var index = _this._keys.indexOf(evt.keyCode);
  5909. if (index >= 0) {
  5910. _this._keys.splice(index, 1);
  5911. }
  5912. if (evt.preventDefault) {
  5913. if (!noPreventDefault) {
  5914. evt.preventDefault();
  5915. }
  5916. }
  5917. }
  5918. };
  5919. this._onLostFocus = function () {
  5920. _this._keys = [];
  5921. pointerId = null;
  5922. };
  5923. this._onGestureStart = function (e) {
  5924. if (window.MSGesture === undefined) {
  5925. return;
  5926. }
  5927. if (!_this._MSGestureHandler) {
  5928. _this._MSGestureHandler = new MSGesture();
  5929. _this._MSGestureHandler.target = element;
  5930. }
  5931. _this._MSGestureHandler.addPointer(e.pointerId);
  5932. };
  5933. this._onGesture = function (e) {
  5934. _this.radius *= e.scale;
  5935. if (e.preventDefault) {
  5936. if (!noPreventDefault) {
  5937. e.stopPropagation();
  5938. e.preventDefault();
  5939. }
  5940. }
  5941. };
  5942. this._reset = function () {
  5943. _this._keys = [];
  5944. _this.inertialAlphaOffset = 0;
  5945. _this.inertialBetaOffset = 0;
  5946. _this.inertialRadiusOffset = 0;
  5947. previousPosition = null;
  5948. pointerId = null;
  5949. };
  5950. this._touchStart = function (event) {
  5951. if (event.touches.length == 2) {
  5952. pinchStarted = true;
  5953. _this._pinchStart(event);
  5954. }
  5955. };
  5956. this._touchMove = function (event) {
  5957. if (pinchStarted) {
  5958. _this._pinchMove(event);
  5959. }
  5960. };
  5961. this._touchEnd = function (event) {
  5962. if (pinchStarted) {
  5963. _this._pinchEnd(event);
  5964. }
  5965. };
  5966. this._pinchStart = function (event) {
  5967. pinchPointX1 = event.touches[0].clientX;
  5968. pinchPointX2 = event.touches[1].clientX;
  5969. pinchStarted = true;
  5970. };
  5971. this._pinchMove = function (event) {
  5972. var delta = 0;
  5973. var direction = 1;
  5974. var distanceXOrigine, distanceXNow;
  5975. if (event.touches.length != 2)
  5976. return;
  5977. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  5978. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  5979. if (distanceXNow < distanceXOrigine) {
  5980. direction = -1;
  5981. }
  5982. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  5983. _this.inertialRadiusOffset += delta;
  5984. pinchPointX1 = event.touches[0].clientX;
  5985. pinchPointX2 = event.touches[1].clientX;
  5986. };
  5987. this._pinchEnd = function (event) {
  5988. pinchStarted = false;
  5989. };
  5990. }
  5991. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  5992. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  5993. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  5994. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  5995. element.addEventListener("mousemove", this._onMouseMove, false);
  5996. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  5997. element.addEventListener("MSGestureChange", this._onGesture, false);
  5998. element.addEventListener('mousewheel', this._wheel, false);
  5999. element.addEventListener('DOMMouseScroll', this._wheel, false);
  6000. element.addEventListener('touchstart', this._touchStart, false);
  6001. element.addEventListener('touchmove', this._touchMove, false);
  6002. element.addEventListener('touchend', this._touchEnd, false);
  6003. BABYLON.Tools.RegisterTopRootEvents([
  6004. { name: "keydown", handler: this._onKeyDown },
  6005. { name: "keyup", handler: this._onKeyUp },
  6006. { name: "blur", handler: this._onLostFocus }
  6007. ]);
  6008. };
  6009. ArcRotateCamera.prototype.detachControl = function (element) {
  6010. if (this._attachedElement != element) {
  6011. return;
  6012. }
  6013. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  6014. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  6015. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  6016. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  6017. element.removeEventListener("mousemove", this._onMouseMove);
  6018. element.removeEventListener("MSPointerDown", this._onGestureStart);
  6019. element.removeEventListener("MSGestureChange", this._onGesture);
  6020. element.removeEventListener('mousewheel', this._wheel);
  6021. element.removeEventListener('DOMMouseScroll', this._wheel);
  6022. element.removeEventListener('touchstart', this._touchStart);
  6023. element.removeEventListener('touchmove', this._touchMove);
  6024. element.removeEventListener('touchend', this._touchEnd);
  6025. BABYLON.Tools.UnregisterTopRootEvents([
  6026. { name: "keydown", handler: this._onKeyDown },
  6027. { name: "keyup", handler: this._onKeyUp },
  6028. { name: "blur", handler: this._onLostFocus }
  6029. ]);
  6030. this._MSGestureHandler = null;
  6031. this._attachedElement = null;
  6032. if (this._reset) {
  6033. this._reset();
  6034. }
  6035. };
  6036. ArcRotateCamera.prototype._update = function () {
  6037. for (var index = 0; index < this._keys.length; index++) {
  6038. var keyCode = this._keys[index];
  6039. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6040. this.inertialAlphaOffset -= 0.01;
  6041. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6042. this.inertialBetaOffset -= 0.01;
  6043. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6044. this.inertialAlphaOffset += 0.01;
  6045. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6046. this.inertialBetaOffset += 0.01;
  6047. }
  6048. }
  6049. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  6050. this.alpha += this.inertialAlphaOffset;
  6051. this.beta += this.inertialBetaOffset;
  6052. this.radius -= this.inertialRadiusOffset;
  6053. this.inertialAlphaOffset *= this.inertia;
  6054. this.inertialBetaOffset *= this.inertia;
  6055. this.inertialRadiusOffset *= this.inertia;
  6056. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  6057. this.inertialAlphaOffset = 0;
  6058. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  6059. this.inertialBetaOffset = 0;
  6060. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  6061. this.inertialRadiusOffset = 0;
  6062. }
  6063. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  6064. this.alpha = this.lowerAlphaLimit;
  6065. }
  6066. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  6067. this.alpha = this.upperAlphaLimit;
  6068. }
  6069. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  6070. this.beta = this.lowerBetaLimit;
  6071. }
  6072. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  6073. this.beta = this.upperBetaLimit;
  6074. }
  6075. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  6076. this.radius = this.lowerRadiusLimit;
  6077. }
  6078. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  6079. this.radius = this.upperRadiusLimit;
  6080. }
  6081. };
  6082. ArcRotateCamera.prototype.setPosition = function (position) {
  6083. var radiusv3 = position.subtract(this._getTargetPosition());
  6084. this.radius = radiusv3.length();
  6085. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  6086. if (radiusv3.z < 0) {
  6087. this.alpha = 2 * Math.PI - this.alpha;
  6088. }
  6089. this.beta = Math.acos(radiusv3.y / this.radius);
  6090. };
  6091. ArcRotateCamera.prototype._getViewMatrix = function () {
  6092. var cosa = Math.cos(this.alpha);
  6093. var sina = Math.sin(this.alpha);
  6094. var cosb = Math.cos(this.beta);
  6095. var sinb = Math.sin(this.beta);
  6096. var target = this._getTargetPosition();
  6097. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  6098. if (this.checkCollisions) {
  6099. this._collider.radius = this.collisionRadius;
  6100. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  6101. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  6102. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  6103. this.position.copyFrom(this._previousPosition);
  6104. this.alpha = this._previousAlpha;
  6105. this.beta = this._previousBeta;
  6106. this.radius = this._previousRadius;
  6107. if (this.onCollide) {
  6108. this.onCollide(this._collider.collidedMesh);
  6109. }
  6110. }
  6111. }
  6112. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  6113. this._previousAlpha = this.alpha;
  6114. this._previousBeta = this.beta;
  6115. this._previousRadius = this.radius;
  6116. this._previousPosition.copyFrom(this.position);
  6117. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  6118. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  6119. return this._viewMatrix;
  6120. };
  6121. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  6122. meshes = meshes || this.getScene().meshes;
  6123. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  6124. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  6125. this.radius = distance * this.zoomOnFactor;
  6126. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  6127. };
  6128. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  6129. var meshesOrMinMaxVector;
  6130. var distance;
  6131. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  6132. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  6133. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  6134. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  6135. } else {
  6136. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  6137. distance = meshesOrMinMaxVectorAndDistance.distance;
  6138. }
  6139. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  6140. this.maxZ = distance * 2;
  6141. };
  6142. return ArcRotateCamera;
  6143. })(BABYLON.Camera);
  6144. BABYLON.ArcRotateCamera = ArcRotateCamera;
  6145. })(BABYLON || (BABYLON = {}));
  6146. var BABYLON;
  6147. (function (BABYLON) {
  6148. var Scene = (function () {
  6149. function Scene(engine) {
  6150. this.autoClear = true;
  6151. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6152. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  6153. this.forceWireframe = false;
  6154. this.cameraToUseForPointers = null;
  6155. this.fogMode = BABYLON.Scene.FOGMODE_NONE;
  6156. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6157. this.fogDensity = 0.1;
  6158. this.fogStart = 0;
  6159. this.fogEnd = 1000.0;
  6160. this.shadowsEnabled = true;
  6161. this.lightsEnabled = true;
  6162. this.lights = new Array();
  6163. this.cameras = new Array();
  6164. this.activeCameras = new Array();
  6165. this.meshes = new Array();
  6166. this._geometries = new Array();
  6167. this.materials = new Array();
  6168. this.multiMaterials = new Array();
  6169. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  6170. this.texturesEnabled = true;
  6171. this.textures = new Array();
  6172. this.particlesEnabled = true;
  6173. this.particleSystems = new Array();
  6174. this.spriteManagers = new Array();
  6175. this.layers = new Array();
  6176. this.skeletons = new Array();
  6177. this.lensFlaresEnabled = true;
  6178. this.lensFlareSystems = new Array();
  6179. this.collisionsEnabled = true;
  6180. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  6181. this.postProcessesEnabled = true;
  6182. this.renderTargetsEnabled = true;
  6183. this.customRenderTargets = new Array();
  6184. this.importedMeshesFiles = new Array();
  6185. this._actionManagers = new Array();
  6186. this._meshesForIntersections = new BABYLON.SmartArray(256);
  6187. this.proceduralTexturesEnabled = true;
  6188. this._proceduralTextures = new Array();
  6189. this._totalVertices = 0;
  6190. this._activeVertices = 0;
  6191. this._activeParticles = 0;
  6192. this._lastFrameDuration = 0;
  6193. this._evaluateActiveMeshesDuration = 0;
  6194. this._renderTargetsDuration = 0;
  6195. this._particlesDuration = 0;
  6196. this._renderDuration = 0;
  6197. this._spritesDuration = 0;
  6198. this._animationRatio = 0;
  6199. this._renderId = 0;
  6200. this._executeWhenReadyTimeoutId = -1;
  6201. this._toBeDisposed = new BABYLON.SmartArray(256);
  6202. this._onReadyCallbacks = new Array();
  6203. this._pendingData = [];
  6204. this._onBeforeRenderCallbacks = new Array();
  6205. this._activeMeshes = new BABYLON.SmartArray(256);
  6206. this._processedMaterials = new BABYLON.SmartArray(256);
  6207. this._renderTargets = new BABYLON.SmartArray(256);
  6208. this._activeParticleSystems = new BABYLON.SmartArray(256);
  6209. this._activeSkeletons = new BABYLON.SmartArray(32);
  6210. this._activeAnimatables = new Array();
  6211. this._transformMatrix = BABYLON.Matrix.Zero();
  6212. this._scaledPosition = BABYLON.Vector3.Zero();
  6213. this._scaledVelocity = BABYLON.Vector3.Zero();
  6214. this._engine = engine;
  6215. engine.scenes.push(this);
  6216. this._renderingManager = new BABYLON.RenderingManager(this);
  6217. this.postProcessManager = new BABYLON.PostProcessManager(this);
  6218. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  6219. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  6220. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  6221. this.attachControl();
  6222. }
  6223. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  6224. get: function () {
  6225. return this._meshUnderPointer;
  6226. },
  6227. enumerable: true,
  6228. configurable: true
  6229. });
  6230. Object.defineProperty(Scene.prototype, "pointerX", {
  6231. get: function () {
  6232. return this._pointerX;
  6233. },
  6234. enumerable: true,
  6235. configurable: true
  6236. });
  6237. Object.defineProperty(Scene.prototype, "pointerY", {
  6238. get: function () {
  6239. return this._pointerY;
  6240. },
  6241. enumerable: true,
  6242. configurable: true
  6243. });
  6244. Scene.prototype.getBoundingBoxRenderer = function () {
  6245. return this._boundingBoxRenderer;
  6246. };
  6247. Scene.prototype.getOutlineRenderer = function () {
  6248. return this._outlineRenderer;
  6249. };
  6250. Scene.prototype.getEngine = function () {
  6251. return this._engine;
  6252. };
  6253. Scene.prototype.getTotalVertices = function () {
  6254. return this._totalVertices;
  6255. };
  6256. Scene.prototype.getActiveVertices = function () {
  6257. return this._activeVertices;
  6258. };
  6259. Scene.prototype.getActiveParticles = function () {
  6260. return this._activeParticles;
  6261. };
  6262. Scene.prototype.getLastFrameDuration = function () {
  6263. return this._lastFrameDuration;
  6264. };
  6265. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  6266. return this._evaluateActiveMeshesDuration;
  6267. };
  6268. Scene.prototype.getActiveMeshes = function () {
  6269. return this._activeMeshes;
  6270. };
  6271. Scene.prototype.getRenderTargetsDuration = function () {
  6272. return this._renderTargetsDuration;
  6273. };
  6274. Scene.prototype.getRenderDuration = function () {
  6275. return this._renderDuration;
  6276. };
  6277. Scene.prototype.getParticlesDuration = function () {
  6278. return this._particlesDuration;
  6279. };
  6280. Scene.prototype.getSpritesDuration = function () {
  6281. return this._spritesDuration;
  6282. };
  6283. Scene.prototype.getAnimationRatio = function () {
  6284. return this._animationRatio;
  6285. };
  6286. Scene.prototype.getRenderId = function () {
  6287. return this._renderId;
  6288. };
  6289. Scene.prototype._updatePointerPosition = function (evt) {
  6290. var canvasRect = this._engine.getRenderingCanvasClientRect();
  6291. this._pointerX = evt.clientX - canvasRect.left;
  6292. this._pointerY = evt.clientY - canvasRect.top;
  6293. if (this.cameraToUseForPointers) {
  6294. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  6295. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  6296. }
  6297. };
  6298. Scene.prototype.attachControl = function () {
  6299. var _this = this;
  6300. this._onPointerMove = function (evt) {
  6301. var canvas = _this._engine.getRenderingCanvas();
  6302. _this._updatePointerPosition(evt);
  6303. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  6304. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  6305. }, false, _this.cameraToUseForPointers);
  6306. if (pickResult.hit) {
  6307. _this._meshUnderPointer = pickResult.pickedMesh;
  6308. _this.setPointerOverMesh(pickResult.pickedMesh);
  6309. canvas.style.cursor = "pointer";
  6310. } else {
  6311. _this.setPointerOverMesh(null);
  6312. canvas.style.cursor = "";
  6313. _this._meshUnderPointer = null;
  6314. }
  6315. };
  6316. this._onPointerDown = function (evt) {
  6317. var predicate = null;
  6318. if (!_this.onPointerDown) {
  6319. predicate = function (mesh) {
  6320. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  6321. };
  6322. }
  6323. _this._updatePointerPosition(evt);
  6324. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  6325. if (pickResult.hit) {
  6326. if (pickResult.pickedMesh.actionManager) {
  6327. switch (evt.button) {
  6328. case 0:
  6329. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6330. break;
  6331. case 1:
  6332. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6333. break;
  6334. case 2:
  6335. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6336. break;
  6337. }
  6338. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6339. }
  6340. }
  6341. if (_this.onPointerDown) {
  6342. _this.onPointerDown(evt, pickResult);
  6343. }
  6344. };
  6345. this._onKeyDown = function (evt) {
  6346. if (_this.actionManager) {
  6347. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6348. }
  6349. };
  6350. this._onKeyUp = function (evt) {
  6351. if (_this.actionManager) {
  6352. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6353. }
  6354. };
  6355. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6356. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6357. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6358. window.addEventListener("keydown", this._onKeyDown, false);
  6359. window.addEventListener("keyup", this._onKeyUp, false);
  6360. };
  6361. Scene.prototype.detachControl = function () {
  6362. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6363. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  6364. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  6365. window.removeEventListener("keydown", this._onKeyDown);
  6366. window.removeEventListener("keyup", this._onKeyUp);
  6367. };
  6368. Scene.prototype.isReady = function () {
  6369. if (this._pendingData.length > 0) {
  6370. return false;
  6371. }
  6372. for (var index = 0; index < this._geometries.length; index++) {
  6373. var geometry = this._geometries[index];
  6374. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  6375. return false;
  6376. }
  6377. }
  6378. for (index = 0; index < this.meshes.length; index++) {
  6379. var mesh = this.meshes[index];
  6380. if (!mesh.isReady()) {
  6381. return false;
  6382. }
  6383. var mat = mesh.material;
  6384. if (mat) {
  6385. if (!mat.isReady(mesh)) {
  6386. return false;
  6387. }
  6388. }
  6389. }
  6390. return true;
  6391. };
  6392. Scene.prototype.registerBeforeRender = function (func) {
  6393. this._onBeforeRenderCallbacks.push(func);
  6394. };
  6395. Scene.prototype.unregisterBeforeRender = function (func) {
  6396. var index = this._onBeforeRenderCallbacks.indexOf(func);
  6397. if (index > -1) {
  6398. this._onBeforeRenderCallbacks.splice(index, 1);
  6399. }
  6400. };
  6401. Scene.prototype._addPendingData = function (data) {
  6402. this._pendingData.push(data);
  6403. };
  6404. Scene.prototype._removePendingData = function (data) {
  6405. var index = this._pendingData.indexOf(data);
  6406. if (index !== -1) {
  6407. this._pendingData.splice(index, 1);
  6408. }
  6409. };
  6410. Scene.prototype.getWaitingItemsCount = function () {
  6411. return this._pendingData.length;
  6412. };
  6413. Scene.prototype.executeWhenReady = function (func) {
  6414. var _this = this;
  6415. this._onReadyCallbacks.push(func);
  6416. if (this._executeWhenReadyTimeoutId !== -1) {
  6417. return;
  6418. }
  6419. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6420. _this._checkIsReady();
  6421. }, 150);
  6422. };
  6423. Scene.prototype._checkIsReady = function () {
  6424. var _this = this;
  6425. if (this.isReady()) {
  6426. this._onReadyCallbacks.forEach(function (func) {
  6427. func();
  6428. });
  6429. this._onReadyCallbacks = [];
  6430. this._executeWhenReadyTimeoutId = -1;
  6431. return;
  6432. }
  6433. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6434. _this._checkIsReady();
  6435. }, 150);
  6436. };
  6437. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  6438. if (speedRatio === undefined) {
  6439. speedRatio = 1.0;
  6440. }
  6441. this.stopAnimation(target);
  6442. if (!animatable) {
  6443. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  6444. }
  6445. if (target.animations) {
  6446. animatable.appendAnimations(target, target.animations);
  6447. }
  6448. if (target.getAnimatables) {
  6449. var animatables = target.getAnimatables();
  6450. for (var index = 0; index < animatables.length; index++) {
  6451. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  6452. }
  6453. }
  6454. return animatable;
  6455. };
  6456. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  6457. if (speedRatio === undefined) {
  6458. speedRatio = 1.0;
  6459. }
  6460. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  6461. return animatable;
  6462. };
  6463. Scene.prototype.getAnimatableByTarget = function (target) {
  6464. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6465. if (this._activeAnimatables[index].target === target) {
  6466. return this._activeAnimatables[index];
  6467. }
  6468. }
  6469. return null;
  6470. };
  6471. Scene.prototype.stopAnimation = function (target) {
  6472. var animatable = this.getAnimatableByTarget(target);
  6473. if (animatable) {
  6474. animatable.stop();
  6475. }
  6476. };
  6477. Scene.prototype._animate = function () {
  6478. if (!this._animationStartDate) {
  6479. this._animationStartDate = BABYLON.Tools.Now;
  6480. }
  6481. var now = BABYLON.Tools.Now;
  6482. var delay = now - this._animationStartDate;
  6483. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6484. if (!this._activeAnimatables[index]._animate(delay)) {
  6485. this._activeAnimatables.splice(index, 1);
  6486. index--;
  6487. }
  6488. }
  6489. };
  6490. Scene.prototype.getViewMatrix = function () {
  6491. return this._viewMatrix;
  6492. };
  6493. Scene.prototype.getProjectionMatrix = function () {
  6494. return this._projectionMatrix;
  6495. };
  6496. Scene.prototype.getTransformMatrix = function () {
  6497. return this._transformMatrix;
  6498. };
  6499. Scene.prototype.setTransformMatrix = function (view, projection) {
  6500. this._viewMatrix = view;
  6501. this._projectionMatrix = projection;
  6502. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6503. };
  6504. Scene.prototype.setActiveCameraByID = function (id) {
  6505. var camera = this.getCameraByID(id);
  6506. if (camera) {
  6507. this.activeCamera = camera;
  6508. return camera;
  6509. }
  6510. return null;
  6511. };
  6512. Scene.prototype.setActiveCameraByName = function (name) {
  6513. var camera = this.getCameraByName(name);
  6514. if (camera) {
  6515. this.activeCamera = camera;
  6516. return camera;
  6517. }
  6518. return null;
  6519. };
  6520. Scene.prototype.getMaterialByID = function (id) {
  6521. for (var index = 0; index < this.materials.length; index++) {
  6522. if (this.materials[index].id === id) {
  6523. return this.materials[index];
  6524. }
  6525. }
  6526. return null;
  6527. };
  6528. Scene.prototype.getMaterialByName = function (name) {
  6529. for (var index = 0; index < this.materials.length; index++) {
  6530. if (this.materials[index].name === name) {
  6531. return this.materials[index];
  6532. }
  6533. }
  6534. return null;
  6535. };
  6536. Scene.prototype.getCameraByID = function (id) {
  6537. for (var index = 0; index < this.cameras.length; index++) {
  6538. if (this.cameras[index].id === id) {
  6539. return this.cameras[index];
  6540. }
  6541. }
  6542. return null;
  6543. };
  6544. Scene.prototype.getCameraByName = function (name) {
  6545. for (var index = 0; index < this.cameras.length; index++) {
  6546. if (this.cameras[index].name === name) {
  6547. return this.cameras[index];
  6548. }
  6549. }
  6550. return null;
  6551. };
  6552. Scene.prototype.getLightByName = function (name) {
  6553. for (var index = 0; index < this.lights.length; index++) {
  6554. if (this.lights[index].name === name) {
  6555. return this.lights[index];
  6556. }
  6557. }
  6558. return null;
  6559. };
  6560. Scene.prototype.getLightByID = function (id) {
  6561. for (var index = 0; index < this.lights.length; index++) {
  6562. if (this.lights[index].id === id) {
  6563. return this.lights[index];
  6564. }
  6565. }
  6566. return null;
  6567. };
  6568. Scene.prototype.getGeometryByID = function (id) {
  6569. for (var index = 0; index < this._geometries.length; index++) {
  6570. if (this._geometries[index].id === id) {
  6571. return this._geometries[index];
  6572. }
  6573. }
  6574. return null;
  6575. };
  6576. Scene.prototype.pushGeometry = function (geometry, force) {
  6577. if (!force && this.getGeometryByID(geometry.id)) {
  6578. return false;
  6579. }
  6580. this._geometries.push(geometry);
  6581. return true;
  6582. };
  6583. Scene.prototype.getGeometries = function () {
  6584. return this._geometries;
  6585. };
  6586. Scene.prototype.getMeshByID = function (id) {
  6587. for (var index = 0; index < this.meshes.length; index++) {
  6588. if (this.meshes[index].id === id) {
  6589. return this.meshes[index];
  6590. }
  6591. }
  6592. return null;
  6593. };
  6594. Scene.prototype.getLastMeshByID = function (id) {
  6595. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6596. if (this.meshes[index].id === id) {
  6597. return this.meshes[index];
  6598. }
  6599. }
  6600. return null;
  6601. };
  6602. Scene.prototype.getLastEntryByID = function (id) {
  6603. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6604. if (this.meshes[index].id === id) {
  6605. return this.meshes[index];
  6606. }
  6607. }
  6608. for (index = this.cameras.length - 1; index >= 0; index--) {
  6609. if (this.cameras[index].id === id) {
  6610. return this.cameras[index];
  6611. }
  6612. }
  6613. for (index = this.lights.length - 1; index >= 0; index--) {
  6614. if (this.lights[index].id === id) {
  6615. return this.lights[index];
  6616. }
  6617. }
  6618. return null;
  6619. };
  6620. Scene.prototype.getMeshByName = function (name) {
  6621. for (var index = 0; index < this.meshes.length; index++) {
  6622. if (this.meshes[index].name === name) {
  6623. return this.meshes[index];
  6624. }
  6625. }
  6626. return null;
  6627. };
  6628. Scene.prototype.getLastSkeletonByID = function (id) {
  6629. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  6630. if (this.skeletons[index].id === id) {
  6631. return this.skeletons[index];
  6632. }
  6633. }
  6634. return null;
  6635. };
  6636. Scene.prototype.getSkeletonById = function (id) {
  6637. for (var index = 0; index < this.skeletons.length; index++) {
  6638. if (this.skeletons[index].id === id) {
  6639. return this.skeletons[index];
  6640. }
  6641. }
  6642. return null;
  6643. };
  6644. Scene.prototype.getSkeletonByName = function (name) {
  6645. for (var index = 0; index < this.skeletons.length; index++) {
  6646. if (this.skeletons[index].name === name) {
  6647. return this.skeletons[index];
  6648. }
  6649. }
  6650. return null;
  6651. };
  6652. Scene.prototype.isActiveMesh = function (mesh) {
  6653. return (this._activeMeshes.indexOf(mesh) !== -1);
  6654. };
  6655. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  6656. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  6657. var material = subMesh.getMaterial();
  6658. if (mesh.showSubMeshesBoundingBox) {
  6659. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  6660. }
  6661. if (material) {
  6662. if (material.getRenderTargetTextures) {
  6663. if (this._processedMaterials.indexOf(material) === -1) {
  6664. this._processedMaterials.push(material);
  6665. this._renderTargets.concat(material.getRenderTargetTextures());
  6666. }
  6667. }
  6668. this._activeVertices += subMesh.verticesCount;
  6669. this._renderingManager.dispatch(subMesh);
  6670. }
  6671. }
  6672. };
  6673. Scene.prototype._evaluateActiveMeshes = function () {
  6674. this._activeMeshes.reset();
  6675. this._renderingManager.reset();
  6676. this._processedMaterials.reset();
  6677. this._activeParticleSystems.reset();
  6678. this._activeSkeletons.reset();
  6679. this._boundingBoxRenderer.reset();
  6680. if (!this._frustumPlanes) {
  6681. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  6682. } else {
  6683. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  6684. }
  6685. var meshes;
  6686. var len;
  6687. if (this._selectionOctree) {
  6688. var selection = this._selectionOctree.select(this._frustumPlanes);
  6689. meshes = selection.data;
  6690. len = selection.length;
  6691. } else {
  6692. len = this.meshes.length;
  6693. meshes = this.meshes;
  6694. }
  6695. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  6696. var mesh = meshes[meshIndex];
  6697. this._totalVertices += mesh.getTotalVertices();
  6698. if (!mesh.isReady()) {
  6699. continue;
  6700. }
  6701. mesh.computeWorldMatrix();
  6702. mesh._preActivate();
  6703. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  6704. this._meshesForIntersections.pushNoDuplicate(mesh);
  6705. }
  6706. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) != 0) && mesh.isInFrustum(this._frustumPlanes)) {
  6707. this._activeMeshes.push(mesh);
  6708. mesh._activate(this._renderId);
  6709. this._activeMesh(mesh);
  6710. }
  6711. }
  6712. var beforeParticlesDate = BABYLON.Tools.Now;
  6713. if (this.particlesEnabled) {
  6714. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  6715. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  6716. var particleSystem = this.particleSystems[particleIndex];
  6717. if (!particleSystem.isStarted()) {
  6718. continue;
  6719. }
  6720. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  6721. this._activeParticleSystems.push(particleSystem);
  6722. particleSystem.animate();
  6723. }
  6724. }
  6725. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  6726. }
  6727. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  6728. };
  6729. Scene.prototype._activeMesh = function (mesh) {
  6730. if (mesh.skeleton) {
  6731. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  6732. }
  6733. if (mesh.showBoundingBox) {
  6734. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  6735. }
  6736. if (mesh.subMeshes) {
  6737. var len;
  6738. var subMeshes;
  6739. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  6740. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  6741. len = intersections.length;
  6742. subMeshes = intersections.data;
  6743. } else {
  6744. subMeshes = mesh.subMeshes;
  6745. len = subMeshes.length;
  6746. }
  6747. for (var subIndex = 0; subIndex < len; subIndex++) {
  6748. var subMesh = subMeshes[subIndex];
  6749. this._evaluateSubMesh(subMesh, mesh);
  6750. }
  6751. }
  6752. };
  6753. Scene.prototype.updateTransformMatrix = function (force) {
  6754. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  6755. };
  6756. Scene.prototype._renderForCamera = function (camera) {
  6757. var engine = this._engine;
  6758. this.activeCamera = camera;
  6759. if (!this.activeCamera)
  6760. throw new Error("Active camera not set");
  6761. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  6762. engine.setViewport(this.activeCamera.viewport);
  6763. this._renderId++;
  6764. this.updateTransformMatrix();
  6765. if (this.beforeCameraRender) {
  6766. this.beforeCameraRender(this.activeCamera);
  6767. }
  6768. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  6769. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  6770. this._evaluateActiveMeshes();
  6771. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  6772. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  6773. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  6774. var skeleton = this._activeSkeletons.data[skeletonIndex];
  6775. skeleton.prepare();
  6776. }
  6777. var beforeRenderTargetDate = BABYLON.Tools.Now;
  6778. if (this.renderTargetsEnabled) {
  6779. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  6780. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  6781. var renderTarget = this._renderTargets.data[renderIndex];
  6782. if (renderTarget._shouldRender()) {
  6783. this._renderId++;
  6784. renderTarget.render();
  6785. }
  6786. }
  6787. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  6788. this._renderId++;
  6789. }
  6790. if (this._renderTargets.length > 0) {
  6791. engine.restoreDefaultFramebuffer();
  6792. }
  6793. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  6794. this.postProcessManager._prepareFrame();
  6795. var beforeRenderDate = BABYLON.Tools.Now;
  6796. if (this.layers.length) {
  6797. engine.setDepthBuffer(false);
  6798. var layerIndex;
  6799. var layer;
  6800. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6801. layer = this.layers[layerIndex];
  6802. if (layer.isBackground) {
  6803. layer.render();
  6804. }
  6805. }
  6806. engine.setDepthBuffer(true);
  6807. }
  6808. BABYLON.Tools.StartPerformanceCounter("Main render");
  6809. this._renderingManager.render(null, null, true, true);
  6810. BABYLON.Tools.EndPerformanceCounter("Main render");
  6811. this._boundingBoxRenderer.render();
  6812. if (this.lensFlaresEnabled) {
  6813. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  6814. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  6815. this.lensFlareSystems[lensFlareSystemIndex].render();
  6816. }
  6817. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  6818. }
  6819. if (this.layers.length) {
  6820. engine.setDepthBuffer(false);
  6821. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  6822. layer = this.layers[layerIndex];
  6823. if (!layer.isBackground) {
  6824. layer.render();
  6825. }
  6826. }
  6827. engine.setDepthBuffer(true);
  6828. }
  6829. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  6830. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  6831. this.activeCamera._updateFromScene();
  6832. this._renderTargets.reset();
  6833. if (this.afterCameraRender) {
  6834. this.afterCameraRender(this.activeCamera);
  6835. }
  6836. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  6837. };
  6838. Scene.prototype._processSubCameras = function (camera) {
  6839. if (camera.subCameras.length == 0) {
  6840. this._renderForCamera(camera);
  6841. return;
  6842. }
  6843. for (var index = 0; index < camera.subCameras.length; index++) {
  6844. this._renderForCamera(camera.subCameras[index]);
  6845. }
  6846. this.activeCamera = camera;
  6847. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  6848. this.activeCamera._updateFromScene();
  6849. };
  6850. Scene.prototype._checkIntersections = function () {
  6851. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  6852. var sourceMesh = this._meshesForIntersections.data[index];
  6853. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  6854. var action = sourceMesh.actionManager.actions[actionIndex];
  6855. if (action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6856. var otherMesh = action.getTriggerParameter();
  6857. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  6858. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6859. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  6860. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6861. sourceMesh._intersectionsInProgress.push(otherMesh);
  6862. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  6863. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  6864. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  6865. if (indexOfOther > -1) {
  6866. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  6867. }
  6868. }
  6869. }
  6870. }
  6871. }
  6872. };
  6873. Scene.prototype.render = function () {
  6874. var startDate = BABYLON.Tools.Now;
  6875. this._particlesDuration = 0;
  6876. this._spritesDuration = 0;
  6877. this._activeParticles = 0;
  6878. this._renderDuration = 0;
  6879. this._evaluateActiveMeshesDuration = 0;
  6880. this._totalVertices = 0;
  6881. this._activeVertices = 0;
  6882. this._meshesForIntersections.reset();
  6883. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  6884. if (this.actionManager) {
  6885. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  6886. }
  6887. if (this.beforeRender) {
  6888. this.beforeRender();
  6889. }
  6890. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  6891. this._onBeforeRenderCallbacks[callbackIndex]();
  6892. }
  6893. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  6894. this._animationRatio = deltaTime * (60.0 / 1000.0);
  6895. this._animate();
  6896. if (this._physicsEngine) {
  6897. BABYLON.Tools.StartPerformanceCounter("Physics");
  6898. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  6899. BABYLON.Tools.EndPerformanceCounter("Physics");
  6900. }
  6901. var beforeRenderTargetDate = BABYLON.Tools.Now;
  6902. var engine = this.getEngine();
  6903. if (this.renderTargetsEnabled) {
  6904. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  6905. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  6906. var renderTarget = this.customRenderTargets[customIndex];
  6907. if (renderTarget._shouldRender()) {
  6908. this._renderId++;
  6909. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  6910. if (!this.activeCamera)
  6911. throw new Error("Active camera not set");
  6912. engine.setViewport(this.activeCamera.viewport);
  6913. this.updateTransformMatrix();
  6914. renderTarget.render();
  6915. }
  6916. }
  6917. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  6918. this._renderId++;
  6919. }
  6920. if (this.customRenderTargets.length > 0) {
  6921. engine.restoreDefaultFramebuffer();
  6922. }
  6923. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  6924. if (this.proceduralTexturesEnabled) {
  6925. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  6926. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  6927. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  6928. if (proceduralTexture._shouldRender()) {
  6929. proceduralTexture.render();
  6930. }
  6931. }
  6932. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  6933. }
  6934. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  6935. if (this.shadowsEnabled) {
  6936. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  6937. var light = this.lights[lightIndex];
  6938. var shadowGenerator = light.getShadowGenerator();
  6939. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  6940. this._renderTargets.push(shadowGenerator.getShadowMap());
  6941. }
  6942. }
  6943. }
  6944. this.postProcessRenderPipelineManager.update();
  6945. if (this.activeCameras.length > 0) {
  6946. var currentRenderId = this._renderId;
  6947. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  6948. this._renderId = currentRenderId;
  6949. this._processSubCameras(this.activeCameras[cameraIndex]);
  6950. }
  6951. } else {
  6952. if (!this.activeCamera) {
  6953. throw new Error("No camera defined");
  6954. }
  6955. this._processSubCameras(this.activeCamera);
  6956. }
  6957. this._checkIntersections();
  6958. if (this.afterRender) {
  6959. this.afterRender();
  6960. }
  6961. for (var index = 0; index < this._toBeDisposed.length; index++) {
  6962. this._toBeDisposed.data[index].dispose();
  6963. this._toBeDisposed[index] = null;
  6964. }
  6965. this._toBeDisposed.reset();
  6966. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  6967. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  6968. };
  6969. Scene.prototype.dispose = function () {
  6970. this.beforeRender = null;
  6971. this.afterRender = null;
  6972. this.skeletons = [];
  6973. this._boundingBoxRenderer.dispose();
  6974. if (this.onDispose) {
  6975. this.onDispose();
  6976. }
  6977. this.detachControl();
  6978. var canvas = this._engine.getRenderingCanvas();
  6979. var index;
  6980. for (index = 0; index < this.cameras.length; index++) {
  6981. this.cameras[index].detachControl(canvas);
  6982. }
  6983. while (this.lights.length) {
  6984. this.lights[0].dispose();
  6985. }
  6986. while (this.meshes.length) {
  6987. this.meshes[0].dispose(true);
  6988. }
  6989. while (this.cameras.length) {
  6990. this.cameras[0].dispose();
  6991. }
  6992. while (this.materials.length) {
  6993. this.materials[0].dispose();
  6994. }
  6995. while (this.particleSystems.length) {
  6996. this.particleSystems[0].dispose();
  6997. }
  6998. while (this.spriteManagers.length) {
  6999. this.spriteManagers[0].dispose();
  7000. }
  7001. while (this.layers.length) {
  7002. this.layers[0].dispose();
  7003. }
  7004. while (this.textures.length) {
  7005. this.textures[0].dispose();
  7006. }
  7007. this.postProcessManager.dispose();
  7008. if (this._physicsEngine) {
  7009. this.disablePhysicsEngine();
  7010. }
  7011. index = this._engine.scenes.indexOf(this);
  7012. if (index > -1) {
  7013. this._engine.scenes.splice(index, 1);
  7014. }
  7015. this._engine.wipeCaches();
  7016. };
  7017. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7018. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7019. position.divideToRef(collider.radius, this._scaledPosition);
  7020. velocity.divideToRef(collider.radius, this._scaledVelocity);
  7021. collider.retry = 0;
  7022. collider.initialVelocity = this._scaledVelocity;
  7023. collider.initialPosition = this._scaledPosition;
  7024. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  7025. finalPosition.multiplyInPlace(collider.radius);
  7026. };
  7027. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7028. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7029. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  7030. if (collider.retry >= maximumRetry) {
  7031. finalPosition.copyFrom(position);
  7032. return;
  7033. }
  7034. collider._initialize(position, velocity, closeDistance);
  7035. for (var index = 0; index < this.meshes.length; index++) {
  7036. var mesh = this.meshes[index];
  7037. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  7038. mesh._checkCollision(collider);
  7039. }
  7040. }
  7041. if (!collider.collisionFound) {
  7042. position.addToRef(velocity, finalPosition);
  7043. return;
  7044. }
  7045. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  7046. collider._getResponse(position, velocity);
  7047. }
  7048. if (velocity.length() <= closeDistance) {
  7049. finalPosition.copyFrom(position);
  7050. return;
  7051. }
  7052. collider.retry++;
  7053. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  7054. };
  7055. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  7056. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7057. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7058. if (!this._selectionOctree) {
  7059. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  7060. }
  7061. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7062. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7063. for (var index = 0; index < this.meshes.length; index++) {
  7064. var mesh = this.meshes[index];
  7065. mesh.computeWorldMatrix(true);
  7066. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  7067. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  7068. BABYLON.Tools.CheckExtends(minBox, min, max);
  7069. BABYLON.Tools.CheckExtends(maxBox, min, max);
  7070. }
  7071. this._selectionOctree.update(min, max, this.meshes);
  7072. return this._selectionOctree;
  7073. };
  7074. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  7075. var engine = this._engine;
  7076. if (!camera) {
  7077. if (!this.activeCamera)
  7078. throw new Error("Active camera not set");
  7079. camera = this.activeCamera;
  7080. }
  7081. var cameraViewport = camera.viewport;
  7082. var viewport = cameraViewport.toGlobal(engine);
  7083. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  7084. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  7085. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  7086. };
  7087. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  7088. var pickingInfo = null;
  7089. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  7090. var mesh = this.meshes[meshIndex];
  7091. if (predicate) {
  7092. if (!predicate(mesh)) {
  7093. continue;
  7094. }
  7095. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  7096. continue;
  7097. }
  7098. var world = mesh.getWorldMatrix();
  7099. var ray = rayFunction(world);
  7100. var result = mesh.intersects(ray, fastCheck);
  7101. if (!result || !result.hit)
  7102. continue;
  7103. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  7104. continue;
  7105. pickingInfo = result;
  7106. if (fastCheck) {
  7107. break;
  7108. }
  7109. }
  7110. return pickingInfo || new BABYLON.PickingInfo();
  7111. };
  7112. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  7113. var _this = this;
  7114. return this._internalPick(function (world) {
  7115. return _this.createPickingRay(x, y, world, camera);
  7116. }, predicate, fastCheck);
  7117. };
  7118. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  7119. var _this = this;
  7120. return this._internalPick(function (world) {
  7121. if (!_this._pickWithRayInverseMatrix) {
  7122. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  7123. }
  7124. world.invertToRef(_this._pickWithRayInverseMatrix);
  7125. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  7126. }, predicate, fastCheck);
  7127. };
  7128. Scene.prototype.setPointerOverMesh = function (mesh) {
  7129. if (this._pointerOverMesh === mesh) {
  7130. return;
  7131. }
  7132. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  7133. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  7134. }
  7135. this._pointerOverMesh = mesh;
  7136. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  7137. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  7138. }
  7139. };
  7140. Scene.prototype.getPointerOverMesh = function () {
  7141. return this._pointerOverMesh;
  7142. };
  7143. Scene.prototype.getPhysicsEngine = function () {
  7144. return this._physicsEngine;
  7145. };
  7146. Scene.prototype.enablePhysics = function (gravity, plugin) {
  7147. if (this._physicsEngine) {
  7148. return true;
  7149. }
  7150. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  7151. if (!this._physicsEngine.isSupported()) {
  7152. this._physicsEngine = null;
  7153. return false;
  7154. }
  7155. this._physicsEngine._initialize(gravity);
  7156. return true;
  7157. };
  7158. Scene.prototype.disablePhysicsEngine = function () {
  7159. if (!this._physicsEngine) {
  7160. return;
  7161. }
  7162. this._physicsEngine.dispose();
  7163. this._physicsEngine = undefined;
  7164. };
  7165. Scene.prototype.isPhysicsEnabled = function () {
  7166. return this._physicsEngine !== undefined;
  7167. };
  7168. Scene.prototype.setGravity = function (gravity) {
  7169. if (!this._physicsEngine) {
  7170. return;
  7171. }
  7172. this._physicsEngine._setGravity(gravity);
  7173. };
  7174. Scene.prototype.createCompoundImpostor = function (parts, options) {
  7175. if (parts.parts) {
  7176. options = parts;
  7177. parts = parts.parts;
  7178. }
  7179. if (!this._physicsEngine) {
  7180. return null;
  7181. }
  7182. for (var index = 0; index < parts.length; index++) {
  7183. var mesh = parts[index].mesh;
  7184. mesh._physicImpostor = parts[index].impostor;
  7185. mesh._physicsMass = options.mass / parts.length;
  7186. mesh._physicsFriction = options.friction;
  7187. mesh._physicRestitution = options.restitution;
  7188. }
  7189. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  7190. };
  7191. Scene.prototype.deleteCompoundImpostor = function (compound) {
  7192. for (var index = 0; index < compound.parts.length; index++) {
  7193. var mesh = compound.parts[index].mesh;
  7194. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7195. this._physicsEngine._unregisterMesh(mesh);
  7196. }
  7197. };
  7198. Scene.prototype._getByTags = function (list, tagsQuery) {
  7199. if (tagsQuery === undefined) {
  7200. return list;
  7201. }
  7202. var listByTags = [];
  7203. for (var i in list) {
  7204. var item = list[i];
  7205. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  7206. listByTags.push(item);
  7207. }
  7208. }
  7209. return listByTags;
  7210. };
  7211. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  7212. return this._getByTags(this.meshes, tagsQuery);
  7213. };
  7214. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  7215. return this._getByTags(this.cameras, tagsQuery);
  7216. };
  7217. Scene.prototype.getLightsByTags = function (tagsQuery) {
  7218. return this._getByTags(this.lights, tagsQuery);
  7219. };
  7220. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  7221. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  7222. };
  7223. Scene.FOGMODE_NONE = 0;
  7224. Scene.FOGMODE_EXP = 1;
  7225. Scene.FOGMODE_EXP2 = 2;
  7226. Scene.FOGMODE_LINEAR = 3;
  7227. Scene.MinDeltaTime = 1.0;
  7228. Scene.MaxDeltaTime = 1000.0;
  7229. return Scene;
  7230. })();
  7231. BABYLON.Scene = Scene;
  7232. })(BABYLON || (BABYLON = {}));
  7233. var BABYLON;
  7234. (function (BABYLON) {
  7235. var VertexBuffer = (function () {
  7236. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation) {
  7237. if (engine instanceof BABYLON.Mesh) {
  7238. this._engine = engine.getScene().getEngine();
  7239. } else {
  7240. this._engine = engine;
  7241. }
  7242. this._updatable = updatable;
  7243. this._data = data;
  7244. if (!postponeInternalCreation) {
  7245. this.create();
  7246. }
  7247. this._kind = kind;
  7248. switch (kind) {
  7249. case VertexBuffer.PositionKind:
  7250. this._strideSize = 3;
  7251. break;
  7252. case VertexBuffer.NormalKind:
  7253. this._strideSize = 3;
  7254. break;
  7255. case VertexBuffer.UVKind:
  7256. this._strideSize = 2;
  7257. break;
  7258. case VertexBuffer.UV2Kind:
  7259. this._strideSize = 2;
  7260. break;
  7261. case VertexBuffer.ColorKind:
  7262. this._strideSize = 3;
  7263. break;
  7264. case VertexBuffer.MatricesIndicesKind:
  7265. this._strideSize = 4;
  7266. break;
  7267. case VertexBuffer.MatricesWeightsKind:
  7268. this._strideSize = 4;
  7269. break;
  7270. }
  7271. }
  7272. VertexBuffer.prototype.isUpdatable = function () {
  7273. return this._updatable;
  7274. };
  7275. VertexBuffer.prototype.getData = function () {
  7276. return this._data;
  7277. };
  7278. VertexBuffer.prototype.getBuffer = function () {
  7279. return this._buffer;
  7280. };
  7281. VertexBuffer.prototype.getStrideSize = function () {
  7282. return this._strideSize;
  7283. };
  7284. VertexBuffer.prototype.create = function (data) {
  7285. if (!data && this._buffer) {
  7286. return;
  7287. }
  7288. data = data || this._data;
  7289. if (!this._buffer) {
  7290. if (this._updatable) {
  7291. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  7292. } else {
  7293. this._buffer = this._engine.createVertexBuffer(data);
  7294. }
  7295. }
  7296. if (this._updatable) {
  7297. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7298. this._data = data;
  7299. }
  7300. };
  7301. VertexBuffer.prototype.update = function (data) {
  7302. this.create(data);
  7303. };
  7304. VertexBuffer.prototype.updateDirectly = function (data) {
  7305. if (!this._buffer) {
  7306. return;
  7307. }
  7308. if (this._updatable) {
  7309. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7310. this._data = null;
  7311. }
  7312. };
  7313. VertexBuffer.prototype.dispose = function () {
  7314. if (!this._buffer) {
  7315. return;
  7316. }
  7317. if (this._engine._releaseBuffer(this._buffer)) {
  7318. this._buffer = null;
  7319. }
  7320. };
  7321. Object.defineProperty(VertexBuffer, "PositionKind", {
  7322. get: function () {
  7323. return VertexBuffer._PositionKind;
  7324. },
  7325. enumerable: true,
  7326. configurable: true
  7327. });
  7328. Object.defineProperty(VertexBuffer, "NormalKind", {
  7329. get: function () {
  7330. return VertexBuffer._NormalKind;
  7331. },
  7332. enumerable: true,
  7333. configurable: true
  7334. });
  7335. Object.defineProperty(VertexBuffer, "UVKind", {
  7336. get: function () {
  7337. return VertexBuffer._UVKind;
  7338. },
  7339. enumerable: true,
  7340. configurable: true
  7341. });
  7342. Object.defineProperty(VertexBuffer, "UV2Kind", {
  7343. get: function () {
  7344. return VertexBuffer._UV2Kind;
  7345. },
  7346. enumerable: true,
  7347. configurable: true
  7348. });
  7349. Object.defineProperty(VertexBuffer, "ColorKind", {
  7350. get: function () {
  7351. return VertexBuffer._ColorKind;
  7352. },
  7353. enumerable: true,
  7354. configurable: true
  7355. });
  7356. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  7357. get: function () {
  7358. return VertexBuffer._MatricesIndicesKind;
  7359. },
  7360. enumerable: true,
  7361. configurable: true
  7362. });
  7363. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  7364. get: function () {
  7365. return VertexBuffer._MatricesWeightsKind;
  7366. },
  7367. enumerable: true,
  7368. configurable: true
  7369. });
  7370. VertexBuffer._PositionKind = "position";
  7371. VertexBuffer._NormalKind = "normal";
  7372. VertexBuffer._UVKind = "uv";
  7373. VertexBuffer._UV2Kind = "uv2";
  7374. VertexBuffer._ColorKind = "color";
  7375. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  7376. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  7377. return VertexBuffer;
  7378. })();
  7379. BABYLON.VertexBuffer = VertexBuffer;
  7380. })(BABYLON || (BABYLON = {}));
  7381. var __extends = this.__extends || function (d, b) {
  7382. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7383. function __() { this.constructor = d; }
  7384. __.prototype = b.prototype;
  7385. d.prototype = new __();
  7386. };
  7387. var BABYLON;
  7388. (function (BABYLON) {
  7389. var AbstractMesh = (function (_super) {
  7390. __extends(AbstractMesh, _super);
  7391. function AbstractMesh(name, scene) {
  7392. _super.call(this, name, scene);
  7393. this.position = new BABYLON.Vector3(0, 0, 0);
  7394. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7395. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7396. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  7397. this.visibility = 1.0;
  7398. this.infiniteDistance = false;
  7399. this.isVisible = true;
  7400. this.isPickable = true;
  7401. this.showBoundingBox = false;
  7402. this.showSubMeshesBoundingBox = false;
  7403. this.onDispose = null;
  7404. this.checkCollisions = false;
  7405. this.isBlocker = false;
  7406. this.renderingGroupId = 0;
  7407. this.receiveShadows = false;
  7408. this.renderOutline = false;
  7409. this.outlineColor = BABYLON.Color3.Red();
  7410. this.outlineWidth = 0.02;
  7411. this.useOctreeForRenderingSelection = true;
  7412. this.useOctreeForPicking = true;
  7413. this.useOctreeForCollisions = true;
  7414. this.layerMask = 0xFFFFFFFF;
  7415. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7416. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7417. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7418. this._collider = new BABYLON.Collider();
  7419. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7420. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7421. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7422. this._localScaling = BABYLON.Matrix.Zero();
  7423. this._localRotation = BABYLON.Matrix.Zero();
  7424. this._localTranslation = BABYLON.Matrix.Zero();
  7425. this._localBillboard = BABYLON.Matrix.Zero();
  7426. this._localPivotScaling = BABYLON.Matrix.Zero();
  7427. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7428. this._localWorld = BABYLON.Matrix.Zero();
  7429. this._worldMatrix = BABYLON.Matrix.Zero();
  7430. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7431. this._absolutePosition = BABYLON.Vector3.Zero();
  7432. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7433. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7434. this._isDirty = false;
  7435. this._pivotMatrix = BABYLON.Matrix.Identity();
  7436. this._isDisposed = false;
  7437. this._renderId = 0;
  7438. this._intersectionsInProgress = new Array();
  7439. scene.meshes.push(this);
  7440. }
  7441. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7442. get: function () {
  7443. return AbstractMesh._BILLBOARDMODE_NONE;
  7444. },
  7445. enumerable: true,
  7446. configurable: true
  7447. });
  7448. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7449. get: function () {
  7450. return AbstractMesh._BILLBOARDMODE_X;
  7451. },
  7452. enumerable: true,
  7453. configurable: true
  7454. });
  7455. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7456. get: function () {
  7457. return AbstractMesh._BILLBOARDMODE_Y;
  7458. },
  7459. enumerable: true,
  7460. configurable: true
  7461. });
  7462. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7463. get: function () {
  7464. return AbstractMesh._BILLBOARDMODE_Z;
  7465. },
  7466. enumerable: true,
  7467. configurable: true
  7468. });
  7469. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7470. get: function () {
  7471. return AbstractMesh._BILLBOARDMODE_ALL;
  7472. },
  7473. enumerable: true,
  7474. configurable: true
  7475. });
  7476. AbstractMesh.prototype.getTotalVertices = function () {
  7477. return 0;
  7478. };
  7479. AbstractMesh.prototype.getIndices = function () {
  7480. return null;
  7481. };
  7482. AbstractMesh.prototype.getVerticesData = function (kind) {
  7483. return null;
  7484. };
  7485. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7486. return false;
  7487. };
  7488. AbstractMesh.prototype.getBoundingInfo = function () {
  7489. if (!this._boundingInfo) {
  7490. this._updateBoundingInfo();
  7491. }
  7492. return this._boundingInfo;
  7493. };
  7494. AbstractMesh.prototype._preActivate = function () {
  7495. };
  7496. AbstractMesh.prototype._activate = function (renderId) {
  7497. this._renderId = renderId;
  7498. };
  7499. AbstractMesh.prototype.getWorldMatrix = function () {
  7500. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7501. this.computeWorldMatrix();
  7502. }
  7503. return this._worldMatrix;
  7504. };
  7505. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7506. get: function () {
  7507. return this._worldMatrix;
  7508. },
  7509. enumerable: true,
  7510. configurable: true
  7511. });
  7512. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7513. get: function () {
  7514. return this._absolutePosition;
  7515. },
  7516. enumerable: true,
  7517. configurable: true
  7518. });
  7519. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7520. if (!this.rotationQuaternion) {
  7521. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7522. this.rotation = BABYLON.Vector3.Zero();
  7523. }
  7524. if (!space || space == 0 /* LOCAL */) {
  7525. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7526. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7527. } else {
  7528. if (this.parent) {
  7529. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7530. invertParentWorldMatrix.invert();
  7531. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7532. }
  7533. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7534. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7535. }
  7536. };
  7537. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7538. var displacementVector = axis.scale(distance);
  7539. if (!space || space == 0 /* LOCAL */) {
  7540. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7541. this.setPositionWithLocalVector(tempV3);
  7542. } else {
  7543. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7544. }
  7545. };
  7546. AbstractMesh.prototype.getAbsolutePosition = function () {
  7547. this.computeWorldMatrix();
  7548. return this._absolutePosition;
  7549. };
  7550. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7551. if (!absolutePosition) {
  7552. return;
  7553. }
  7554. var absolutePositionX;
  7555. var absolutePositionY;
  7556. var absolutePositionZ;
  7557. if (absolutePosition.x === undefined) {
  7558. if (arguments.length < 3) {
  7559. return;
  7560. }
  7561. absolutePositionX = arguments[0];
  7562. absolutePositionY = arguments[1];
  7563. absolutePositionZ = arguments[2];
  7564. } else {
  7565. absolutePositionX = absolutePosition.x;
  7566. absolutePositionY = absolutePosition.y;
  7567. absolutePositionZ = absolutePosition.z;
  7568. }
  7569. if (this.parent) {
  7570. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7571. invertParentWorldMatrix.invert();
  7572. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7573. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7574. } else {
  7575. this.position.x = absolutePositionX;
  7576. this.position.y = absolutePositionY;
  7577. this.position.z = absolutePositionZ;
  7578. }
  7579. };
  7580. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7581. this._pivotMatrix = matrix;
  7582. this._cache.pivotMatrixUpdated = true;
  7583. };
  7584. AbstractMesh.prototype.getPivotMatrix = function () {
  7585. return this._pivotMatrix;
  7586. };
  7587. AbstractMesh.prototype._isSynchronized = function () {
  7588. if (this._isDirty) {
  7589. return false;
  7590. }
  7591. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7592. return false;
  7593. if (this._cache.pivotMatrixUpdated) {
  7594. return false;
  7595. }
  7596. if (this.infiniteDistance) {
  7597. return false;
  7598. }
  7599. if (!this._cache.position.equals(this.position))
  7600. return false;
  7601. if (this.rotationQuaternion) {
  7602. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7603. return false;
  7604. } else {
  7605. if (!this._cache.rotation.equals(this.rotation))
  7606. return false;
  7607. }
  7608. if (!this._cache.scaling.equals(this.scaling))
  7609. return false;
  7610. return true;
  7611. };
  7612. AbstractMesh.prototype._initCache = function () {
  7613. _super.prototype._initCache.call(this);
  7614. this._cache.localMatrixUpdated = false;
  7615. this._cache.position = BABYLON.Vector3.Zero();
  7616. this._cache.scaling = BABYLON.Vector3.Zero();
  7617. this._cache.rotation = BABYLON.Vector3.Zero();
  7618. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7619. };
  7620. AbstractMesh.prototype.markAsDirty = function (property) {
  7621. if (property === "rotation") {
  7622. this.rotationQuaternion = null;
  7623. }
  7624. this._currentRenderId = Number.MAX_VALUE;
  7625. this._isDirty = true;
  7626. };
  7627. AbstractMesh.prototype._updateBoundingInfo = function () {
  7628. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7629. this._boundingInfo._update(this.worldMatrixFromCache);
  7630. if (!this.subMeshes) {
  7631. return;
  7632. }
  7633. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7634. var subMesh = this.subMeshes[subIndex];
  7635. subMesh.updateBoundingInfo(this.worldMatrixFromCache);
  7636. }
  7637. };
  7638. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7639. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  7640. return this._worldMatrix;
  7641. }
  7642. this._cache.position.copyFrom(this.position);
  7643. this._cache.scaling.copyFrom(this.scaling);
  7644. this._cache.pivotMatrixUpdated = false;
  7645. this._currentRenderId = this.getScene().getRenderId();
  7646. this._isDirty = false;
  7647. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7648. if (this.rotationQuaternion) {
  7649. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7650. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7651. } else {
  7652. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7653. this._cache.rotation.copyFrom(this.rotation);
  7654. }
  7655. if (this.infiniteDistance && !this.parent) {
  7656. var camera = this.getScene().activeCamera;
  7657. var cameraWorldMatrix = camera.getWorldMatrix();
  7658. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7659. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7660. } else {
  7661. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7662. }
  7663. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7664. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7665. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7666. var localPosition = this.position.clone();
  7667. var zero = this.getScene().activeCamera.position.clone();
  7668. if (this.parent && this.parent.position) {
  7669. localPosition.addInPlace(this.parent.position);
  7670. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7671. }
  7672. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  7673. zero = this.getScene().activeCamera.position;
  7674. } else {
  7675. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  7676. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7677. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  7678. zero.y = localPosition.y + 0.001;
  7679. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  7680. zero.z = localPosition.z + 0.001;
  7681. }
  7682. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7683. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7684. this._localBillboard.invert();
  7685. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7686. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7687. }
  7688. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7689. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  7690. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7691. } else {
  7692. this._worldMatrix.copyFrom(this._localWorld);
  7693. }
  7694. this._updateBoundingInfo();
  7695. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7696. return this._worldMatrix;
  7697. };
  7698. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7699. this.computeWorldMatrix();
  7700. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7701. };
  7702. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7703. this.computeWorldMatrix();
  7704. var invLocalWorldMatrix = this._localWorld.clone();
  7705. invLocalWorldMatrix.invert();
  7706. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7707. };
  7708. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7709. this.computeWorldMatrix();
  7710. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7711. };
  7712. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7713. yawCor = yawCor || 0;
  7714. pitchCor = pitchCor || 0;
  7715. rollCor = rollCor || 0;
  7716. var dv = targetPoint.subtract(this.position);
  7717. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7718. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7719. var pitch = Math.atan2(dv.y, len);
  7720. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7721. };
  7722. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7723. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  7724. return false;
  7725. }
  7726. return true;
  7727. };
  7728. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  7729. if (!camera) {
  7730. camera = this.getScene().activeCamera;
  7731. }
  7732. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  7733. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  7734. return false;
  7735. }
  7736. return true;
  7737. };
  7738. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7739. if (!this._boundingInfo || !mesh._boundingInfo) {
  7740. return false;
  7741. }
  7742. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7743. };
  7744. AbstractMesh.prototype.intersectsPoint = function (point) {
  7745. if (!this._boundingInfo) {
  7746. return false;
  7747. }
  7748. return this._boundingInfo.intersectsPoint(point);
  7749. };
  7750. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  7751. var physicsEngine = this.getScene().getPhysicsEngine();
  7752. if (!physicsEngine) {
  7753. return;
  7754. }
  7755. if (impostor.impostor) {
  7756. options = impostor;
  7757. impostor = impostor.impostor;
  7758. }
  7759. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  7760. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  7761. physicsEngine._unregisterMesh(this);
  7762. return;
  7763. }
  7764. options.mass = options.mass || 0;
  7765. options.friction = options.friction || 0.2;
  7766. options.restitution = options.restitution || 0.2;
  7767. this._physicImpostor = impostor;
  7768. this._physicsMass = options.mass;
  7769. this._physicsFriction = options.friction;
  7770. this._physicRestitution = options.restitution;
  7771. physicsEngine._registerMesh(this, impostor, options);
  7772. };
  7773. AbstractMesh.prototype.getPhysicsImpostor = function () {
  7774. if (!this._physicImpostor) {
  7775. return BABYLON.PhysicsEngine.NoImpostor;
  7776. }
  7777. return this._physicImpostor;
  7778. };
  7779. AbstractMesh.prototype.getPhysicsMass = function () {
  7780. if (!this._physicsMass) {
  7781. return 0;
  7782. }
  7783. return this._physicsMass;
  7784. };
  7785. AbstractMesh.prototype.getPhysicsFriction = function () {
  7786. if (!this._physicsFriction) {
  7787. return 0;
  7788. }
  7789. return this._physicsFriction;
  7790. };
  7791. AbstractMesh.prototype.getPhysicsRestitution = function () {
  7792. if (!this._physicRestitution) {
  7793. return 0;
  7794. }
  7795. return this._physicRestitution;
  7796. };
  7797. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  7798. if (!this._physicImpostor) {
  7799. return;
  7800. }
  7801. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  7802. };
  7803. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  7804. if (!this._physicImpostor) {
  7805. return;
  7806. }
  7807. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  7808. };
  7809. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  7810. if (!this._physicImpostor) {
  7811. return;
  7812. }
  7813. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  7814. };
  7815. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  7816. var globalPosition = this.getAbsolutePosition();
  7817. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  7818. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  7819. this._collider.radius = this.ellipsoid;
  7820. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  7821. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  7822. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7823. this.position.addInPlace(this._diffPositionForCollisions);
  7824. }
  7825. };
  7826. /**
  7827. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  7828. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  7829. */
  7830. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  7831. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7832. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7833. if (!this._submeshesOctree) {
  7834. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  7835. }
  7836. this.computeWorldMatrix(true);
  7837. var bbox = this.getBoundingInfo().boundingBox;
  7838. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  7839. return this._submeshesOctree;
  7840. };
  7841. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  7842. this._generatePointsArray();
  7843. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  7844. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  7845. subMesh._lastColliderWorldVertices = [];
  7846. subMesh._trianglePlanes = [];
  7847. var start = subMesh.verticesStart;
  7848. var end = (subMesh.verticesStart + subMesh.verticesCount);
  7849. for (var i = start; i < end; i++) {
  7850. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  7851. }
  7852. }
  7853. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  7854. };
  7855. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  7856. var subMeshes;
  7857. var len;
  7858. if (this._submeshesOctree && this.useOctreeForCollisions) {
  7859. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  7860. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  7861. len = intersections.length;
  7862. subMeshes = intersections.data;
  7863. } else {
  7864. subMeshes = this.subMeshes;
  7865. len = subMeshes.length;
  7866. }
  7867. for (var index = 0; index < len; index++) {
  7868. var subMesh = subMeshes[index];
  7869. if (len > 1 && !subMesh._checkCollision(collider))
  7870. continue;
  7871. this._collideForSubMesh(subMesh, transformMatrix, collider);
  7872. }
  7873. };
  7874. AbstractMesh.prototype._checkCollision = function (collider) {
  7875. if (!this._boundingInfo._checkCollision(collider))
  7876. return;
  7877. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  7878. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  7879. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  7880. };
  7881. AbstractMesh.prototype._generatePointsArray = function () {
  7882. return false;
  7883. };
  7884. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  7885. var pickingInfo = new BABYLON.PickingInfo();
  7886. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  7887. return pickingInfo;
  7888. }
  7889. if (!this._generatePointsArray()) {
  7890. return pickingInfo;
  7891. }
  7892. var intersectInfo = null;
  7893. var subMeshes;
  7894. var len;
  7895. if (this._submeshesOctree && this.useOctreeForPicking) {
  7896. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  7897. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  7898. len = intersections.length;
  7899. subMeshes = intersections.data;
  7900. } else {
  7901. subMeshes = this.subMeshes;
  7902. len = subMeshes.length;
  7903. }
  7904. for (var index = 0; index < len; index++) {
  7905. var subMesh = subMeshes[index];
  7906. if (len > 1 && !subMesh.canIntersects(ray))
  7907. continue;
  7908. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  7909. if (currentIntersectInfo) {
  7910. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  7911. intersectInfo = currentIntersectInfo;
  7912. if (fastCheck) {
  7913. break;
  7914. }
  7915. }
  7916. }
  7917. }
  7918. if (intersectInfo) {
  7919. var world = this.getWorldMatrix();
  7920. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  7921. var direction = ray.direction.clone();
  7922. direction.normalize();
  7923. direction = direction.scale(intersectInfo.distance);
  7924. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  7925. var pickedPoint = worldOrigin.add(worldDirection);
  7926. pickingInfo.hit = true;
  7927. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  7928. pickingInfo.pickedPoint = pickedPoint;
  7929. pickingInfo.pickedMesh = this;
  7930. pickingInfo.bu = intersectInfo.bu;
  7931. pickingInfo.bv = intersectInfo.bv;
  7932. pickingInfo.faceId = intersectInfo.faceId;
  7933. return pickingInfo;
  7934. }
  7935. return pickingInfo;
  7936. };
  7937. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  7938. return null;
  7939. };
  7940. AbstractMesh.prototype.releaseSubMeshes = function () {
  7941. if (this.subMeshes) {
  7942. while (this.subMeshes.length) {
  7943. this.subMeshes[0].dispose();
  7944. }
  7945. } else {
  7946. this.subMeshes = new Array();
  7947. }
  7948. };
  7949. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  7950. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  7951. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  7952. }
  7953. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  7954. var other = this._intersectionsInProgress[index];
  7955. var pos = other._intersectionsInProgress.indexOf(this);
  7956. other._intersectionsInProgress.splice(pos, 1);
  7957. }
  7958. this._intersectionsInProgress = [];
  7959. this.releaseSubMeshes();
  7960. var index = this.getScene().meshes.indexOf(this);
  7961. if (index != -1) {
  7962. this.getScene().meshes.splice(index, 1);
  7963. }
  7964. if (!doNotRecurse) {
  7965. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  7966. if (this.getScene().particleSystems[index].emitter == this) {
  7967. this.getScene().particleSystems[index].dispose();
  7968. index--;
  7969. }
  7970. }
  7971. var objects = this.getScene().meshes.slice(0);
  7972. for (index = 0; index < objects.length; index++) {
  7973. if (objects[index].parent == this) {
  7974. objects[index].dispose();
  7975. }
  7976. }
  7977. } else {
  7978. for (index = 0; index < this.getScene().meshes.length; index++) {
  7979. var obj = this.getScene().meshes[index];
  7980. if (obj.parent === this) {
  7981. obj.parent = null;
  7982. obj.computeWorldMatrix(true);
  7983. }
  7984. }
  7985. }
  7986. this._isDisposed = true;
  7987. if (this.onDispose) {
  7988. this.onDispose();
  7989. }
  7990. };
  7991. AbstractMesh._BILLBOARDMODE_NONE = 0;
  7992. AbstractMesh._BILLBOARDMODE_X = 1;
  7993. AbstractMesh._BILLBOARDMODE_Y = 2;
  7994. AbstractMesh._BILLBOARDMODE_Z = 4;
  7995. AbstractMesh._BILLBOARDMODE_ALL = 7;
  7996. return AbstractMesh;
  7997. })(BABYLON.Node);
  7998. BABYLON.AbstractMesh = AbstractMesh;
  7999. })(BABYLON || (BABYLON = {}));
  8000. var __extends = this.__extends || function (d, b) {
  8001. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8002. function __() { this.constructor = d; }
  8003. __.prototype = b.prototype;
  8004. d.prototype = new __();
  8005. };
  8006. var BABYLON;
  8007. (function (BABYLON) {
  8008. var _InstancesBatch = (function () {
  8009. function _InstancesBatch() {
  8010. this.mustReturn = false;
  8011. this.visibleInstances = new Array();
  8012. this.renderSelf = new Array();
  8013. }
  8014. return _InstancesBatch;
  8015. })();
  8016. BABYLON._InstancesBatch = _InstancesBatch;
  8017. var Mesh = (function (_super) {
  8018. __extends(Mesh, _super);
  8019. function Mesh(name, scene) {
  8020. _super.call(this, name, scene);
  8021. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  8022. this.instances = new Array();
  8023. this._onBeforeRenderCallbacks = new Array();
  8024. this._onAfterRenderCallbacks = new Array();
  8025. this._visibleInstances = {};
  8026. this._renderIdForInstances = new Array();
  8027. this._batchCache = new _InstancesBatch();
  8028. this._instancesBufferSize = 32 * 16 * 4;
  8029. }
  8030. Mesh.prototype.getTotalVertices = function () {
  8031. if (!this._geometry) {
  8032. return 0;
  8033. }
  8034. return this._geometry.getTotalVertices();
  8035. };
  8036. Mesh.prototype.getVerticesData = function (kind) {
  8037. if (!this._geometry) {
  8038. return null;
  8039. }
  8040. return this._geometry.getVerticesData(kind);
  8041. };
  8042. Mesh.prototype.getVertexBuffer = function (kind) {
  8043. if (!this._geometry) {
  8044. return undefined;
  8045. }
  8046. return this._geometry.getVertexBuffer(kind);
  8047. };
  8048. Mesh.prototype.isVerticesDataPresent = function (kind) {
  8049. if (!this._geometry) {
  8050. if (this._delayInfo) {
  8051. return this._delayInfo.indexOf(kind) !== -1;
  8052. }
  8053. return false;
  8054. }
  8055. return this._geometry.isVerticesDataPresent(kind);
  8056. };
  8057. Mesh.prototype.getVerticesDataKinds = function () {
  8058. if (!this._geometry) {
  8059. var result = [];
  8060. if (this._delayInfo) {
  8061. for (var kind in this._delayInfo) {
  8062. result.push(kind);
  8063. }
  8064. }
  8065. return result;
  8066. }
  8067. return this._geometry.getVerticesDataKinds();
  8068. };
  8069. Mesh.prototype.getTotalIndices = function () {
  8070. if (!this._geometry) {
  8071. return 0;
  8072. }
  8073. return this._geometry.getTotalIndices();
  8074. };
  8075. Mesh.prototype.getIndices = function () {
  8076. if (!this._geometry) {
  8077. return [];
  8078. }
  8079. return this._geometry.getIndices();
  8080. };
  8081. Mesh.prototype.isReady = function () {
  8082. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8083. return false;
  8084. }
  8085. return _super.prototype.isReady.call(this);
  8086. };
  8087. Mesh.prototype.isDisposed = function () {
  8088. return this._isDisposed;
  8089. };
  8090. Mesh.prototype._preActivate = function () {
  8091. var sceneRenderId = this.getScene().getRenderId();
  8092. if (this._preActivateId == sceneRenderId) {
  8093. return;
  8094. }
  8095. this._preActivateId = sceneRenderId;
  8096. this._visibleInstances = null;
  8097. };
  8098. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  8099. if (!this._visibleInstances) {
  8100. this._visibleInstances = {};
  8101. this._visibleInstances.defaultRenderId = renderId;
  8102. this._visibleInstances.selfDefaultRenderId = this._renderId;
  8103. }
  8104. if (!this._visibleInstances[renderId]) {
  8105. this._visibleInstances[renderId] = new Array();
  8106. }
  8107. this._visibleInstances[renderId].push(instance);
  8108. };
  8109. Mesh.prototype.refreshBoundingInfo = function () {
  8110. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8111. if (data) {
  8112. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  8113. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8114. }
  8115. if (this.subMeshes) {
  8116. for (var index = 0; index < this.subMeshes.length; index++) {
  8117. this.subMeshes[index].refreshBoundingInfo();
  8118. }
  8119. }
  8120. this._updateBoundingInfo();
  8121. };
  8122. Mesh.prototype._createGlobalSubMesh = function () {
  8123. var totalVertices = this.getTotalVertices();
  8124. if (!totalVertices || !this.getIndices()) {
  8125. return null;
  8126. }
  8127. this.releaseSubMeshes();
  8128. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  8129. };
  8130. Mesh.prototype.subdivide = function (count) {
  8131. if (count < 1) {
  8132. return;
  8133. }
  8134. var totalIndices = this.getTotalIndices();
  8135. var subdivisionSize = (totalIndices / count) | 0;
  8136. var offset = 0;
  8137. while (subdivisionSize % 3 != 0) {
  8138. subdivisionSize++;
  8139. }
  8140. this.releaseSubMeshes();
  8141. for (var index = 0; index < count; index++) {
  8142. if (offset >= totalIndices) {
  8143. break;
  8144. }
  8145. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  8146. offset += subdivisionSize;
  8147. }
  8148. this.synchronizeInstances();
  8149. };
  8150. Mesh.prototype.setVerticesData = function (kind, data, updatable) {
  8151. if (kind instanceof Array) {
  8152. var temp = data;
  8153. data = kind;
  8154. kind = temp;
  8155. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  8156. }
  8157. if (!this._geometry) {
  8158. var vertexData = new BABYLON.VertexData();
  8159. vertexData.set(data, kind);
  8160. var scene = this.getScene();
  8161. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  8162. } else {
  8163. this._geometry.setVerticesData(kind, data, updatable);
  8164. }
  8165. };
  8166. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  8167. if (!this._geometry) {
  8168. return;
  8169. }
  8170. if (!makeItUnique) {
  8171. this._geometry.updateVerticesData(kind, data, updateExtends);
  8172. } else {
  8173. this.makeGeometryUnique();
  8174. this.updateVerticesData(kind, data, updateExtends, false);
  8175. }
  8176. };
  8177. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, makeItUnique) {
  8178. if (!this._geometry) {
  8179. return;
  8180. }
  8181. if (!makeItUnique) {
  8182. this._geometry.updateVerticesDataDirectly(kind, data);
  8183. } else {
  8184. this.makeGeometryUnique();
  8185. this.updateVerticesDataDirectly(kind, data, false);
  8186. }
  8187. };
  8188. Mesh.prototype.makeGeometryUnique = function () {
  8189. if (!this._geometry) {
  8190. return;
  8191. }
  8192. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  8193. geometry.applyToMesh(this);
  8194. };
  8195. Mesh.prototype.setIndices = function (indices) {
  8196. if (!this._geometry) {
  8197. var vertexData = new BABYLON.VertexData();
  8198. vertexData.indices = indices;
  8199. var scene = this.getScene();
  8200. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  8201. } else {
  8202. this._geometry.setIndices(indices);
  8203. }
  8204. };
  8205. Mesh.prototype._bind = function (subMesh, effect, wireframe) {
  8206. var engine = this.getScene().getEngine();
  8207. var indexToBind = this._geometry.getIndexBuffer();
  8208. if (wireframe) {
  8209. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  8210. }
  8211. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  8212. };
  8213. Mesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  8214. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8215. return;
  8216. }
  8217. var engine = this.getScene().getEngine();
  8218. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  8219. };
  8220. Mesh.prototype._fullDraw = function (subMesh, useTriangles, instancesCount) {
  8221. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8222. return;
  8223. }
  8224. var engine = this.getScene().getEngine();
  8225. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount, instancesCount);
  8226. };
  8227. Mesh.prototype.registerBeforeRender = function (func) {
  8228. this._onBeforeRenderCallbacks.push(func);
  8229. };
  8230. Mesh.prototype.unregisterBeforeRender = function (func) {
  8231. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8232. if (index > -1) {
  8233. this._onBeforeRenderCallbacks.splice(index, 1);
  8234. }
  8235. };
  8236. Mesh.prototype.registerAfterRender = function (func) {
  8237. this._onAfterRenderCallbacks.push(func);
  8238. };
  8239. Mesh.prototype.unregisterAfterRender = function (func) {
  8240. var index = this._onAfterRenderCallbacks.indexOf(func);
  8241. if (index > -1) {
  8242. this._onAfterRenderCallbacks.splice(index, 1);
  8243. }
  8244. };
  8245. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  8246. var scene = this.getScene();
  8247. this._batchCache.mustReturn = false;
  8248. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  8249. this._batchCache.visibleInstances[subMeshId] = null;
  8250. if (this._visibleInstances) {
  8251. var currentRenderId = scene.getRenderId();
  8252. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  8253. var selfRenderId = this._renderId;
  8254. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  8255. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  8256. currentRenderId = this._visibleInstances.defaultRenderId;
  8257. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  8258. }
  8259. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  8260. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  8261. this._batchCache.mustReturn = true;
  8262. return this._batchCache;
  8263. }
  8264. if (currentRenderId !== selfRenderId) {
  8265. this._batchCache.renderSelf[subMeshId] = false;
  8266. }
  8267. }
  8268. this._renderIdForInstances[subMeshId] = currentRenderId;
  8269. }
  8270. return this._batchCache;
  8271. };
  8272. Mesh.prototype._renderWithInstances = function (subMesh, wireFrame, batch, effect, engine) {
  8273. var matricesCount = this.instances.length + 1;
  8274. var bufferSize = matricesCount * 16 * 4;
  8275. while (this._instancesBufferSize < bufferSize) {
  8276. this._instancesBufferSize *= 2;
  8277. }
  8278. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  8279. if (this._worldMatricesInstancesBuffer) {
  8280. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8281. }
  8282. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  8283. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  8284. }
  8285. var offset = 0;
  8286. var instancesCount = 0;
  8287. var world = this.getWorldMatrix();
  8288. if (batch.renderSelf[subMesh._id]) {
  8289. world.copyToArray(this._worldMatricesInstancesArray, offset);
  8290. offset += 16;
  8291. instancesCount++;
  8292. }
  8293. var visibleInstances = batch.visibleInstances[subMesh._id];
  8294. if (visibleInstances) {
  8295. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  8296. var instance = visibleInstances[instanceIndex];
  8297. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  8298. offset += 16;
  8299. instancesCount++;
  8300. }
  8301. }
  8302. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  8303. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  8304. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  8305. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  8306. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  8307. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  8308. this._draw(subMesh, !wireFrame, instancesCount);
  8309. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  8310. };
  8311. Mesh.prototype.render = function (subMesh) {
  8312. var scene = this.getScene();
  8313. var batch = this._getInstancesRenderList(subMesh._id);
  8314. if (batch.mustReturn) {
  8315. return;
  8316. }
  8317. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8318. return;
  8319. }
  8320. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8321. this._onBeforeRenderCallbacks[callbackIndex]();
  8322. }
  8323. var engine = scene.getEngine();
  8324. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8325. var effectiveMaterial = subMesh.getMaterial();
  8326. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  8327. return;
  8328. }
  8329. var savedDepthWrite = engine.getDepthWrite();
  8330. if (this.renderOutline) {
  8331. engine.setDepthWrite(false);
  8332. scene.getOutlineRenderer().render(subMesh, batch);
  8333. }
  8334. effectiveMaterial._preBind();
  8335. var effect = effectiveMaterial.getEffect();
  8336. var wireFrame = engine.forceWireframe || effectiveMaterial.wireframe;
  8337. this._bind(subMesh, effect, wireFrame);
  8338. var world = this.getWorldMatrix();
  8339. effectiveMaterial.bind(world, this);
  8340. if (hardwareInstancedRendering) {
  8341. this._renderWithInstances(subMesh, wireFrame, batch, effect, engine);
  8342. } else {
  8343. if (batch.renderSelf[subMesh._id]) {
  8344. this._draw(subMesh, !wireFrame);
  8345. }
  8346. if (batch.visibleInstances[subMesh._id]) {
  8347. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  8348. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  8349. world = instance.getWorldMatrix();
  8350. effectiveMaterial.bindOnlyWorldMatrix(world);
  8351. this._draw(subMesh, !wireFrame);
  8352. }
  8353. }
  8354. }
  8355. effectiveMaterial.unbind();
  8356. if (this.renderOutline && savedDepthWrite) {
  8357. engine.setDepthWrite(true);
  8358. engine.setColorWrite(false);
  8359. scene.getOutlineRenderer().render(subMesh, batch);
  8360. engine.setColorWrite(true);
  8361. }
  8362. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8363. this._onAfterRenderCallbacks[callbackIndex]();
  8364. }
  8365. };
  8366. Mesh.prototype.getEmittedParticleSystems = function () {
  8367. var results = new Array();
  8368. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8369. var particleSystem = this.getScene().particleSystems[index];
  8370. if (particleSystem.emitter === this) {
  8371. results.push(particleSystem);
  8372. }
  8373. }
  8374. return results;
  8375. };
  8376. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  8377. var results = new Array();
  8378. var descendants = this.getDescendants();
  8379. descendants.push(this);
  8380. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8381. var particleSystem = this.getScene().particleSystems[index];
  8382. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  8383. results.push(particleSystem);
  8384. }
  8385. }
  8386. return results;
  8387. };
  8388. Mesh.prototype.getChildren = function () {
  8389. var results = [];
  8390. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8391. var mesh = this.getScene().meshes[index];
  8392. if (mesh.parent == this) {
  8393. results.push(mesh);
  8394. }
  8395. }
  8396. return results;
  8397. };
  8398. Mesh.prototype._checkDelayState = function () {
  8399. var _this = this;
  8400. var that = this;
  8401. var scene = this.getScene();
  8402. if (this._geometry) {
  8403. this._geometry.load(scene);
  8404. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8405. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  8406. scene._addPendingData(that);
  8407. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  8408. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  8409. if (data instanceof ArrayBuffer) {
  8410. _this._delayLoadingFunction(data, _this);
  8411. } else {
  8412. _this._delayLoadingFunction(JSON.parse(data), _this);
  8413. }
  8414. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  8415. scene._removePendingData(_this);
  8416. }, function () {
  8417. }, scene.database, getBinaryData);
  8418. }
  8419. };
  8420. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  8421. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8422. return false;
  8423. }
  8424. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  8425. return false;
  8426. }
  8427. this._checkDelayState();
  8428. return true;
  8429. };
  8430. Mesh.prototype.setMaterialByID = function (id) {
  8431. var materials = this.getScene().materials;
  8432. for (var index = 0; index < materials.length; index++) {
  8433. if (materials[index].id == id) {
  8434. this.material = materials[index];
  8435. return;
  8436. }
  8437. }
  8438. var multiMaterials = this.getScene().multiMaterials;
  8439. for (index = 0; index < multiMaterials.length; index++) {
  8440. if (multiMaterials[index].id == id) {
  8441. this.material = multiMaterials[index];
  8442. return;
  8443. }
  8444. }
  8445. };
  8446. Mesh.prototype.getAnimatables = function () {
  8447. var results = [];
  8448. if (this.material) {
  8449. results.push(this.material);
  8450. }
  8451. if (this.skeleton) {
  8452. results.push(this.skeleton);
  8453. }
  8454. return results;
  8455. };
  8456. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  8457. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  8458. return;
  8459. }
  8460. this._resetPointsArrayCache();
  8461. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8462. var temp = [];
  8463. for (var index = 0; index < data.length; index += 3) {
  8464. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8465. }
  8466. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  8467. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8468. return;
  8469. }
  8470. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8471. for (index = 0; index < data.length; index += 3) {
  8472. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8473. }
  8474. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  8475. };
  8476. Mesh.prototype._resetPointsArrayCache = function () {
  8477. this._positions = null;
  8478. };
  8479. Mesh.prototype._generatePointsArray = function () {
  8480. if (this._positions)
  8481. return true;
  8482. this._positions = [];
  8483. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8484. if (!data) {
  8485. return false;
  8486. }
  8487. for (var index = 0; index < data.length; index += 3) {
  8488. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  8489. }
  8490. return true;
  8491. };
  8492. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8493. var result = new BABYLON.Mesh(name, this.getScene());
  8494. this._geometry.applyToMesh(result);
  8495. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  8496. result.material = this.material;
  8497. if (newParent) {
  8498. result.parent = newParent;
  8499. }
  8500. if (!doNotCloneChildren) {
  8501. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8502. var mesh = this.getScene().meshes[index];
  8503. if (mesh.parent == this) {
  8504. mesh.clone(mesh.name, result);
  8505. }
  8506. }
  8507. }
  8508. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8509. var system = this.getScene().particleSystems[index];
  8510. if (system.emitter == this) {
  8511. system.clone(system.name, result);
  8512. }
  8513. }
  8514. result.computeWorldMatrix(true);
  8515. return result;
  8516. };
  8517. Mesh.prototype.dispose = function (doNotRecurse) {
  8518. if (this._geometry) {
  8519. this._geometry.releaseForMesh(this, true);
  8520. }
  8521. if (this._worldMatricesInstancesBuffer) {
  8522. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8523. this._worldMatricesInstancesBuffer = null;
  8524. }
  8525. while (this.instances.length) {
  8526. this.instances[0].dispose();
  8527. }
  8528. _super.prototype.dispose.call(this, doNotRecurse);
  8529. };
  8530. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  8531. var _this = this;
  8532. var scene = this.getScene();
  8533. var onload = function (img) {
  8534. var canvas = document.createElement("canvas");
  8535. var context = canvas.getContext("2d");
  8536. var heightMapWidth = img.width;
  8537. var heightMapHeight = img.height;
  8538. canvas.width = heightMapWidth;
  8539. canvas.height = heightMapHeight;
  8540. context.drawImage(img, 0, 0);
  8541. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8542. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  8543. };
  8544. BABYLON.Tools.LoadImage(url, onload, function () {
  8545. }, scene.database);
  8546. };
  8547. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  8548. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8549. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  8550. return;
  8551. }
  8552. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8553. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8554. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8555. var position = BABYLON.Vector3.Zero();
  8556. var normal = BABYLON.Vector3.Zero();
  8557. var uv = BABYLON.Vector2.Zero();
  8558. for (var index = 0; index < positions.length; index += 3) {
  8559. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  8560. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  8561. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  8562. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  8563. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  8564. var pos = (u + v * heightMapWidth) * 4;
  8565. var r = buffer[pos] / 255.0;
  8566. var g = buffer[pos + 1] / 255.0;
  8567. var b = buffer[pos + 2] / 255.0;
  8568. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  8569. normal.normalize();
  8570. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  8571. position = position.add(normal);
  8572. position.toArray(positions, index);
  8573. }
  8574. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  8575. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  8576. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  8577. };
  8578. Mesh.prototype.convertToFlatShadedMesh = function () {
  8579. var kinds = this.getVerticesDataKinds();
  8580. var vbs = [];
  8581. var data = [];
  8582. var newdata = [];
  8583. var updatableNormals = false;
  8584. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8585. var kind = kinds[kindIndex];
  8586. var vertexBuffer = this.getVertexBuffer(kind);
  8587. if (kind === BABYLON.VertexBuffer.NormalKind) {
  8588. updatableNormals = vertexBuffer.isUpdatable();
  8589. kinds.splice(kindIndex, 1);
  8590. kindIndex--;
  8591. continue;
  8592. }
  8593. vbs[kind] = vertexBuffer;
  8594. data[kind] = vbs[kind].getData();
  8595. newdata[kind] = [];
  8596. }
  8597. var previousSubmeshes = this.subMeshes.slice(0);
  8598. var indices = this.getIndices();
  8599. var totalIndices = this.getTotalIndices();
  8600. for (index = 0; index < totalIndices; index++) {
  8601. var vertexIndex = indices[index];
  8602. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8603. kind = kinds[kindIndex];
  8604. var stride = vbs[kind].getStrideSize();
  8605. for (var offset = 0; offset < stride; offset++) {
  8606. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  8607. }
  8608. }
  8609. }
  8610. var normals = [];
  8611. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  8612. for (var index = 0; index < totalIndices; index += 3) {
  8613. indices[index] = index;
  8614. indices[index + 1] = index + 1;
  8615. indices[index + 2] = index + 2;
  8616. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  8617. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  8618. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  8619. var p1p2 = p1.subtract(p2);
  8620. var p3p2 = p3.subtract(p2);
  8621. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  8622. for (var localIndex = 0; localIndex < 3; localIndex++) {
  8623. normals.push(normal.x);
  8624. normals.push(normal.y);
  8625. normals.push(normal.z);
  8626. }
  8627. }
  8628. this.setIndices(indices);
  8629. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  8630. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8631. kind = kinds[kindIndex];
  8632. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  8633. }
  8634. this.releaseSubMeshes();
  8635. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  8636. var previousOne = previousSubmeshes[submeshIndex];
  8637. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  8638. }
  8639. this.synchronizeInstances();
  8640. };
  8641. Mesh.prototype.createInstance = function (name) {
  8642. return new BABYLON.InstancedMesh(name, this);
  8643. };
  8644. Mesh.prototype.synchronizeInstances = function () {
  8645. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  8646. var instance = this.instances[instanceIndex];
  8647. instance._syncSubMeshes();
  8648. }
  8649. };
  8650. Mesh.CreateBox = function (name, size, scene, updatable) {
  8651. var box = new BABYLON.Mesh(name, scene);
  8652. var vertexData = BABYLON.VertexData.CreateBox(size);
  8653. vertexData.applyToMesh(box, updatable);
  8654. return box;
  8655. };
  8656. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  8657. var sphere = new BABYLON.Mesh(name, scene);
  8658. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  8659. vertexData.applyToMesh(sphere, updatable);
  8660. return sphere;
  8661. };
  8662. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  8663. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  8664. if (scene !== undefined) {
  8665. updatable = scene;
  8666. }
  8667. scene = subdivisions;
  8668. subdivisions = 1;
  8669. }
  8670. var cylinder = new BABYLON.Mesh(name, scene);
  8671. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  8672. vertexData.applyToMesh(cylinder, updatable);
  8673. return cylinder;
  8674. };
  8675. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  8676. var torus = new BABYLON.Mesh(name, scene);
  8677. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  8678. vertexData.applyToMesh(torus, updatable);
  8679. return torus;
  8680. };
  8681. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  8682. var torusKnot = new BABYLON.Mesh(name, scene);
  8683. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  8684. vertexData.applyToMesh(torusKnot, updatable);
  8685. return torusKnot;
  8686. };
  8687. Mesh.CreateLines = function (name, points, scene, updatable) {
  8688. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  8689. var vertexData = BABYLON.VertexData.CreateLines(points);
  8690. vertexData.applyToMesh(lines, updatable);
  8691. return lines;
  8692. };
  8693. Mesh.CreatePlane = function (name, size, scene, updatable) {
  8694. var plane = new BABYLON.Mesh(name, scene);
  8695. var vertexData = BABYLON.VertexData.CreatePlane(size);
  8696. vertexData.applyToMesh(plane, updatable);
  8697. return plane;
  8698. };
  8699. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  8700. var ground = new BABYLON.GroundMesh(name, scene);
  8701. ground._setReady(false);
  8702. ground._subdivisions = subdivisions;
  8703. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  8704. vertexData.applyToMesh(ground, updatable);
  8705. ground._setReady(true);
  8706. return ground;
  8707. };
  8708. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  8709. var tiledGround = new BABYLON.Mesh(name, scene);
  8710. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  8711. vertexData.applyToMesh(tiledGround, updatable);
  8712. return tiledGround;
  8713. };
  8714. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  8715. var ground = new BABYLON.GroundMesh(name, scene);
  8716. ground._subdivisions = subdivisions;
  8717. ground._setReady(false);
  8718. var onload = function (img) {
  8719. var canvas = document.createElement("canvas");
  8720. var context = canvas.getContext("2d");
  8721. var heightMapWidth = img.width;
  8722. var heightMapHeight = img.height;
  8723. canvas.width = heightMapWidth;
  8724. canvas.height = heightMapHeight;
  8725. context.drawImage(img, 0, 0);
  8726. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8727. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  8728. vertexData.applyToMesh(ground, updatable);
  8729. ground._setReady(true);
  8730. };
  8731. BABYLON.Tools.LoadImage(url, onload, function () {
  8732. }, scene.database);
  8733. return ground;
  8734. };
  8735. Mesh.MinMax = function (meshes) {
  8736. var minVector = null;
  8737. var maxVector = null;
  8738. for (var i in meshes) {
  8739. var mesh = meshes[i];
  8740. var boundingBox = mesh.getBoundingInfo().boundingBox;
  8741. if (!minVector) {
  8742. minVector = boundingBox.minimumWorld;
  8743. maxVector = boundingBox.maximumWorld;
  8744. continue;
  8745. }
  8746. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  8747. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  8748. }
  8749. return {
  8750. min: minVector,
  8751. max: maxVector
  8752. };
  8753. };
  8754. Mesh.Center = function (meshesOrMinMaxVector) {
  8755. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8756. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  8757. };
  8758. return Mesh;
  8759. })(BABYLON.AbstractMesh);
  8760. BABYLON.Mesh = Mesh;
  8761. })(BABYLON || (BABYLON = {}));
  8762. var __extends = this.__extends || function (d, b) {
  8763. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8764. function __() { this.constructor = d; }
  8765. __.prototype = b.prototype;
  8766. d.prototype = new __();
  8767. };
  8768. var BABYLON;
  8769. (function (BABYLON) {
  8770. var GroundMesh = (function (_super) {
  8771. __extends(GroundMesh, _super);
  8772. function GroundMesh(name, scene) {
  8773. _super.call(this, name, scene);
  8774. this.generateOctree = false;
  8775. this._worldInverse = new BABYLON.Matrix();
  8776. }
  8777. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  8778. get: function () {
  8779. return this._subdivisions;
  8780. },
  8781. enumerable: true,
  8782. configurable: true
  8783. });
  8784. GroundMesh.prototype.optimize = function (chunksCount) {
  8785. this.subdivide(this._subdivisions);
  8786. this.createOrUpdateSubmeshesOctree(32);
  8787. };
  8788. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  8789. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  8790. this.getWorldMatrix().invertToRef(this._worldInverse);
  8791. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  8792. var pickInfo = this.intersects(ray);
  8793. if (pickInfo.hit) {
  8794. return pickInfo.pickedPoint.y;
  8795. }
  8796. return 0;
  8797. };
  8798. return GroundMesh;
  8799. })(BABYLON.Mesh);
  8800. BABYLON.GroundMesh = GroundMesh;
  8801. })(BABYLON || (BABYLON = {}));
  8802. var __extends = this.__extends || function (d, b) {
  8803. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8804. function __() { this.constructor = d; }
  8805. __.prototype = b.prototype;
  8806. d.prototype = new __();
  8807. };
  8808. var BABYLON;
  8809. (function (BABYLON) {
  8810. var InstancedMesh = (function (_super) {
  8811. __extends(InstancedMesh, _super);
  8812. function InstancedMesh(name, source) {
  8813. _super.call(this, name, source.getScene());
  8814. source.instances.push(this);
  8815. this._sourceMesh = source;
  8816. this.position.copyFrom(source.position);
  8817. this.rotation.copyFrom(source.rotation);
  8818. this.scaling.copyFrom(source.scaling);
  8819. if (source.rotationQuaternion) {
  8820. this.rotationQuaternion = source.rotationQuaternion.clone();
  8821. }
  8822. this.infiniteDistance = source.infiniteDistance;
  8823. this.setPivotMatrix(source.getPivotMatrix());
  8824. this.refreshBoundingInfo();
  8825. this._syncSubMeshes();
  8826. }
  8827. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  8828. get: function () {
  8829. return this._sourceMesh.receiveShadows;
  8830. },
  8831. enumerable: true,
  8832. configurable: true
  8833. });
  8834. Object.defineProperty(InstancedMesh.prototype, "material", {
  8835. get: function () {
  8836. return this._sourceMesh.material;
  8837. },
  8838. enumerable: true,
  8839. configurable: true
  8840. });
  8841. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  8842. get: function () {
  8843. return this._sourceMesh.visibility;
  8844. },
  8845. enumerable: true,
  8846. configurable: true
  8847. });
  8848. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  8849. get: function () {
  8850. return this._sourceMesh.skeleton;
  8851. },
  8852. enumerable: true,
  8853. configurable: true
  8854. });
  8855. InstancedMesh.prototype.getTotalVertices = function () {
  8856. return this._sourceMesh.getTotalVertices();
  8857. };
  8858. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  8859. get: function () {
  8860. return this._sourceMesh;
  8861. },
  8862. enumerable: true,
  8863. configurable: true
  8864. });
  8865. InstancedMesh.prototype.getVerticesData = function (kind) {
  8866. return this._sourceMesh.getVerticesData(kind);
  8867. };
  8868. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  8869. return this._sourceMesh.isVerticesDataPresent(kind);
  8870. };
  8871. InstancedMesh.prototype.getIndices = function () {
  8872. return this._sourceMesh.getIndices();
  8873. };
  8874. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  8875. get: function () {
  8876. return this._sourceMesh._positions;
  8877. },
  8878. enumerable: true,
  8879. configurable: true
  8880. });
  8881. InstancedMesh.prototype.refreshBoundingInfo = function () {
  8882. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8883. if (data) {
  8884. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  8885. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8886. }
  8887. this._updateBoundingInfo();
  8888. };
  8889. InstancedMesh.prototype._preActivate = function () {
  8890. this.sourceMesh._preActivate();
  8891. };
  8892. InstancedMesh.prototype._activate = function (renderId) {
  8893. this.sourceMesh._registerInstanceForRenderId(this, renderId);
  8894. };
  8895. InstancedMesh.prototype._syncSubMeshes = function () {
  8896. this.releaseSubMeshes();
  8897. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  8898. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  8899. }
  8900. };
  8901. InstancedMesh.prototype._generatePointsArray = function () {
  8902. return this._sourceMesh._generatePointsArray();
  8903. };
  8904. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8905. var result = this._sourceMesh.createInstance(name);
  8906. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  8907. this.refreshBoundingInfo();
  8908. if (newParent) {
  8909. result.parent = newParent;
  8910. }
  8911. if (!doNotCloneChildren) {
  8912. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8913. var mesh = this.getScene().meshes[index];
  8914. if (mesh.parent == this) {
  8915. mesh.clone(mesh.name, result);
  8916. }
  8917. }
  8918. }
  8919. result.computeWorldMatrix(true);
  8920. return result;
  8921. };
  8922. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  8923. var index = this._sourceMesh.instances.indexOf(this);
  8924. this._sourceMesh.instances.splice(index, 1);
  8925. _super.prototype.dispose.call(this, doNotRecurse);
  8926. };
  8927. return InstancedMesh;
  8928. })(BABYLON.AbstractMesh);
  8929. BABYLON.InstancedMesh = InstancedMesh;
  8930. })(BABYLON || (BABYLON = {}));
  8931. var BABYLON;
  8932. (function (BABYLON) {
  8933. var SubMesh = (function () {
  8934. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  8935. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  8936. this.materialIndex = materialIndex;
  8937. this.verticesStart = verticesStart;
  8938. this.verticesCount = verticesCount;
  8939. this.indexStart = indexStart;
  8940. this.indexCount = indexCount;
  8941. this._renderId = 0;
  8942. this._mesh = mesh;
  8943. this._renderingMesh = renderingMesh || mesh;
  8944. mesh.subMeshes.push(this);
  8945. this._id = mesh.subMeshes.length - 1;
  8946. if (createBoundingBox) {
  8947. this.refreshBoundingInfo();
  8948. }
  8949. }
  8950. SubMesh.prototype.getBoundingInfo = function () {
  8951. return this._boundingInfo;
  8952. };
  8953. SubMesh.prototype.getMesh = function () {
  8954. return this._mesh;
  8955. };
  8956. SubMesh.prototype.getRenderingMesh = function () {
  8957. return this._renderingMesh;
  8958. };
  8959. SubMesh.prototype.getMaterial = function () {
  8960. var rootMaterial = this._renderingMesh.material;
  8961. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  8962. var multiMaterial = rootMaterial;
  8963. return multiMaterial.getSubMaterial(this.materialIndex);
  8964. }
  8965. if (!rootMaterial) {
  8966. return this._mesh.getScene().defaultMaterial;
  8967. }
  8968. return rootMaterial;
  8969. };
  8970. SubMesh.prototype.refreshBoundingInfo = function () {
  8971. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8972. if (!data) {
  8973. this._boundingInfo = this._mesh._boundingInfo;
  8974. return;
  8975. }
  8976. var indices = this._renderingMesh.getIndices();
  8977. var extend;
  8978. if (this.indexStart === 0 && this.indexCount === indices.length) {
  8979. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  8980. } else {
  8981. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  8982. }
  8983. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8984. };
  8985. SubMesh.prototype._checkCollision = function (collider) {
  8986. return this._boundingInfo._checkCollision(collider);
  8987. };
  8988. SubMesh.prototype.updateBoundingInfo = function (world) {
  8989. if (!this._boundingInfo) {
  8990. this.refreshBoundingInfo();
  8991. }
  8992. this._boundingInfo._update(world);
  8993. };
  8994. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  8995. return this._boundingInfo.isInFrustum(frustumPlanes);
  8996. };
  8997. SubMesh.prototype.render = function () {
  8998. this._renderingMesh.render(this);
  8999. };
  9000. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  9001. if (!this._linesIndexBuffer) {
  9002. var linesIndices = [];
  9003. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  9004. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  9005. }
  9006. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  9007. this.linesIndexCount = linesIndices.length;
  9008. }
  9009. return this._linesIndexBuffer;
  9010. };
  9011. SubMesh.prototype.canIntersects = function (ray) {
  9012. return ray.intersectsBox(this._boundingInfo.boundingBox);
  9013. };
  9014. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  9015. var intersectInfo = null;
  9016. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  9017. var p0 = positions[indices[index]];
  9018. var p1 = positions[indices[index + 1]];
  9019. var p2 = positions[indices[index + 2]];
  9020. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  9021. if (currentIntersectInfo) {
  9022. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9023. intersectInfo = currentIntersectInfo;
  9024. intersectInfo.faceId = index / 3;
  9025. if (fastCheck) {
  9026. break;
  9027. }
  9028. }
  9029. }
  9030. }
  9031. return intersectInfo;
  9032. };
  9033. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  9034. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  9035. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  9036. return result;
  9037. };
  9038. SubMesh.prototype.dispose = function () {
  9039. if (this._linesIndexBuffer) {
  9040. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  9041. this._linesIndexBuffer = null;
  9042. }
  9043. var index = this._mesh.subMeshes.indexOf(this);
  9044. this._mesh.subMeshes.splice(index, 1);
  9045. };
  9046. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  9047. var minVertexIndex = Number.MAX_VALUE;
  9048. var maxVertexIndex = -Number.MAX_VALUE;
  9049. renderingMesh = renderingMesh || mesh;
  9050. var indices = renderingMesh.getIndices();
  9051. for (var index = startIndex; index < startIndex + indexCount; index++) {
  9052. var vertexIndex = indices[index];
  9053. if (vertexIndex < minVertexIndex)
  9054. minVertexIndex = vertexIndex;
  9055. if (vertexIndex > maxVertexIndex)
  9056. maxVertexIndex = vertexIndex;
  9057. }
  9058. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  9059. };
  9060. return SubMesh;
  9061. })();
  9062. BABYLON.SubMesh = SubMesh;
  9063. })(BABYLON || (BABYLON = {}));
  9064. var BABYLON;
  9065. (function (BABYLON) {
  9066. var BaseTexture = (function () {
  9067. function BaseTexture(scene) {
  9068. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9069. this.hasAlpha = false;
  9070. this.getAlphaFromRGB = false;
  9071. this.level = 1;
  9072. this.isCube = false;
  9073. this.isRenderTarget = false;
  9074. this.animations = new Array();
  9075. this.coordinatesIndex = 0;
  9076. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  9077. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  9078. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  9079. this.anisotropicFilteringLevel = 4;
  9080. this._scene = scene;
  9081. this._scene.textures.push(this);
  9082. }
  9083. BaseTexture.prototype.getScene = function () {
  9084. return this._scene;
  9085. };
  9086. BaseTexture.prototype.getTextureMatrix = function () {
  9087. return null;
  9088. };
  9089. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  9090. return null;
  9091. };
  9092. BaseTexture.prototype.getInternalTexture = function () {
  9093. return this._texture;
  9094. };
  9095. BaseTexture.prototype.isReady = function () {
  9096. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9097. return true;
  9098. }
  9099. if (this._texture) {
  9100. return this._texture.isReady;
  9101. }
  9102. return false;
  9103. };
  9104. BaseTexture.prototype.getSize = function () {
  9105. if (this._texture._width) {
  9106. return { width: this._texture._width, height: this._texture._height };
  9107. }
  9108. if (this._texture._size) {
  9109. return { width: this._texture._size, height: this._texture._size };
  9110. }
  9111. return { width: 0, height: 0 };
  9112. };
  9113. BaseTexture.prototype.getBaseSize = function () {
  9114. if (!this.isReady())
  9115. return { width: 0, height: 0 };
  9116. if (this._texture._size) {
  9117. return { width: this._texture._size, height: this._texture._size };
  9118. }
  9119. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  9120. };
  9121. BaseTexture.prototype.scale = function (ratio) {
  9122. };
  9123. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  9124. get: function () {
  9125. return false;
  9126. },
  9127. enumerable: true,
  9128. configurable: true
  9129. });
  9130. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  9131. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9132. for (var index = 0; index < texturesCache.length; index++) {
  9133. var texturesCacheEntry = texturesCache[index];
  9134. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  9135. texturesCache.splice(index, 1);
  9136. return;
  9137. }
  9138. }
  9139. };
  9140. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  9141. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9142. for (var index = 0; index < texturesCache.length; index++) {
  9143. var texturesCacheEntry = texturesCache[index];
  9144. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  9145. texturesCacheEntry.references++;
  9146. return texturesCacheEntry;
  9147. }
  9148. }
  9149. return null;
  9150. };
  9151. BaseTexture.prototype.delayLoad = function () {
  9152. };
  9153. BaseTexture.prototype.releaseInternalTexture = function () {
  9154. if (!this._texture) {
  9155. return;
  9156. }
  9157. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9158. this._texture.references--;
  9159. if (this._texture.references == 0) {
  9160. var index = texturesCache.indexOf(this._texture);
  9161. texturesCache.splice(index, 1);
  9162. this._scene.getEngine()._releaseTexture(this._texture);
  9163. delete this._texture;
  9164. }
  9165. };
  9166. BaseTexture.prototype.clone = function () {
  9167. return null;
  9168. };
  9169. BaseTexture.prototype.dispose = function () {
  9170. var index = this._scene.textures.indexOf(this);
  9171. if (index >= 0) {
  9172. this._scene.textures.splice(index, 1);
  9173. }
  9174. if (this._texture === undefined) {
  9175. return;
  9176. }
  9177. this.releaseInternalTexture();
  9178. if (this.onDispose) {
  9179. this.onDispose();
  9180. }
  9181. };
  9182. return BaseTexture;
  9183. })();
  9184. BABYLON.BaseTexture = BaseTexture;
  9185. })(BABYLON || (BABYLON = {}));
  9186. var BABYLON;
  9187. (function (BABYLON) {
  9188. var RenderingGroup = (function () {
  9189. function RenderingGroup(index, scene) {
  9190. this.index = index;
  9191. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  9192. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  9193. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  9194. this._scene = scene;
  9195. }
  9196. RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
  9197. if (customRenderFunction) {
  9198. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
  9199. return true;
  9200. }
  9201. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  9202. return false;
  9203. }
  9204. var engine = this._scene.getEngine();
  9205. var subIndex;
  9206. var submesh;
  9207. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  9208. submesh = this._opaqueSubMeshes.data[subIndex];
  9209. this._activeVertices += submesh.verticesCount;
  9210. submesh.render();
  9211. }
  9212. engine.setAlphaTesting(true);
  9213. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  9214. submesh = this._alphaTestSubMeshes.data[subIndex];
  9215. this._activeVertices += submesh.verticesCount;
  9216. submesh.render();
  9217. }
  9218. engine.setAlphaTesting(false);
  9219. if (beforeTransparents) {
  9220. beforeTransparents();
  9221. }
  9222. if (this._transparentSubMeshes.length) {
  9223. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  9224. submesh = this._transparentSubMeshes.data[subIndex];
  9225. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  9226. }
  9227. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  9228. sortedArray.sort(function (a, b) {
  9229. if (a._distanceToCamera < b._distanceToCamera) {
  9230. return 1;
  9231. }
  9232. if (a._distanceToCamera > b._distanceToCamera) {
  9233. return -1;
  9234. }
  9235. return 0;
  9236. });
  9237. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9238. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  9239. submesh = sortedArray[subIndex];
  9240. this._activeVertices += submesh.verticesCount;
  9241. submesh.render();
  9242. }
  9243. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  9244. }
  9245. return true;
  9246. };
  9247. RenderingGroup.prototype.prepare = function () {
  9248. this._opaqueSubMeshes.reset();
  9249. this._transparentSubMeshes.reset();
  9250. this._alphaTestSubMeshes.reset();
  9251. };
  9252. RenderingGroup.prototype.dispatch = function (subMesh) {
  9253. var material = subMesh.getMaterial();
  9254. var mesh = subMesh.getMesh();
  9255. if (material.needAlphaBlending() || mesh.visibility < 1.0) {
  9256. if (material.alpha > 0 || mesh.visibility < 1.0) {
  9257. this._transparentSubMeshes.push(subMesh);
  9258. }
  9259. } else if (material.needAlphaTesting()) {
  9260. this._alphaTestSubMeshes.push(subMesh);
  9261. } else {
  9262. this._opaqueSubMeshes.push(subMesh);
  9263. }
  9264. };
  9265. return RenderingGroup;
  9266. })();
  9267. BABYLON.RenderingGroup = RenderingGroup;
  9268. })(BABYLON || (BABYLON = {}));
  9269. var BABYLON;
  9270. (function (BABYLON) {
  9271. var RenderingManager = (function () {
  9272. function RenderingManager(scene) {
  9273. this._renderingGroups = new Array();
  9274. this._scene = scene;
  9275. }
  9276. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  9277. if (this._scene._activeParticleSystems.length === 0) {
  9278. return;
  9279. }
  9280. var beforeParticlesDate = BABYLON.Tools.Now;
  9281. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  9282. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  9283. if (particleSystem.renderingGroupId !== index) {
  9284. continue;
  9285. }
  9286. this._clearDepthBuffer();
  9287. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  9288. this._scene._activeParticles += particleSystem.render();
  9289. }
  9290. }
  9291. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  9292. };
  9293. RenderingManager.prototype._renderSprites = function (index) {
  9294. if (this._scene.spriteManagers.length === 0) {
  9295. return;
  9296. }
  9297. var beforeSpritessDate = BABYLON.Tools.Now;
  9298. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  9299. var spriteManager = this._scene.spriteManagers[id];
  9300. if (spriteManager.renderingGroupId === index) {
  9301. this._clearDepthBuffer();
  9302. spriteManager.render();
  9303. }
  9304. }
  9305. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  9306. };
  9307. RenderingManager.prototype._clearDepthBuffer = function () {
  9308. if (this._depthBufferAlreadyCleaned) {
  9309. return;
  9310. }
  9311. this._scene.getEngine().clear(0, false, true);
  9312. this._depthBufferAlreadyCleaned = true;
  9313. };
  9314. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  9315. var _this = this;
  9316. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  9317. this._depthBufferAlreadyCleaned = false;
  9318. var renderingGroup = this._renderingGroups[index];
  9319. if (renderingGroup) {
  9320. this._clearDepthBuffer();
  9321. if (!renderingGroup.render(customRenderFunction, function () {
  9322. if (renderSprites) {
  9323. _this._renderSprites(index);
  9324. }
  9325. })) {
  9326. this._renderingGroups.splice(index, 1);
  9327. }
  9328. } else if (renderSprites) {
  9329. this._renderSprites(index);
  9330. }
  9331. if (renderParticles) {
  9332. this._renderParticles(index, activeMeshes);
  9333. }
  9334. }
  9335. };
  9336. RenderingManager.prototype.reset = function () {
  9337. for (var index in this._renderingGroups) {
  9338. var renderingGroup = this._renderingGroups[index];
  9339. renderingGroup.prepare();
  9340. }
  9341. };
  9342. RenderingManager.prototype.dispatch = function (subMesh) {
  9343. var mesh = subMesh.getMesh();
  9344. var renderingGroupId = mesh.renderingGroupId || 0;
  9345. if (!this._renderingGroups[renderingGroupId]) {
  9346. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  9347. }
  9348. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  9349. };
  9350. RenderingManager.MAX_RENDERINGGROUPS = 4;
  9351. return RenderingManager;
  9352. })();
  9353. BABYLON.RenderingManager = RenderingManager;
  9354. })(BABYLON || (BABYLON = {}));
  9355. var __extends = this.__extends || function (d, b) {
  9356. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9357. function __() { this.constructor = d; }
  9358. __.prototype = b.prototype;
  9359. d.prototype = new __();
  9360. };
  9361. var BABYLON;
  9362. (function (BABYLON) {
  9363. var Texture = (function (_super) {
  9364. __extends(Texture, _super);
  9365. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  9366. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  9367. if (typeof onLoad === "undefined") { onLoad = null; }
  9368. if (typeof onError === "undefined") { onError = null; }
  9369. if (typeof buffer === "undefined") { buffer = null; }
  9370. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  9371. _super.call(this, scene);
  9372. this.uOffset = 0;
  9373. this.vOffset = 0;
  9374. this.uScale = 1.0;
  9375. this.vScale = 1.0;
  9376. this.uAng = 0;
  9377. this.vAng = 0;
  9378. this.wAng = 0;
  9379. this.name = url;
  9380. this.url = url;
  9381. this._noMipmap = noMipmap;
  9382. this._invertY = invertY;
  9383. this._samplingMode = samplingMode;
  9384. this._buffer = buffer;
  9385. this._deleteBuffer = deleteBuffer;
  9386. if (!url) {
  9387. return;
  9388. }
  9389. this._texture = this._getFromCache(url, noMipmap);
  9390. if (!this._texture) {
  9391. if (!scene.useDelayedTextureLoading) {
  9392. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  9393. if (deleteBuffer) {
  9394. delete this._buffer;
  9395. }
  9396. } else {
  9397. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9398. }
  9399. }
  9400. }
  9401. Texture.prototype.delayLoad = function () {
  9402. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9403. return;
  9404. }
  9405. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9406. this._texture = this._getFromCache(this.url, this._noMipmap);
  9407. if (!this._texture) {
  9408. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  9409. if (this._deleteBuffer) {
  9410. delete this._buffer;
  9411. }
  9412. }
  9413. };
  9414. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  9415. x -= this.uOffset + 0.5;
  9416. y -= this.vOffset + 0.5;
  9417. z -= 0.5;
  9418. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  9419. t.x *= this.uScale;
  9420. t.y *= this.vScale;
  9421. t.x += 0.5;
  9422. t.y += 0.5;
  9423. t.z += 0.5;
  9424. };
  9425. Texture.prototype.getTextureMatrix = function () {
  9426. 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) {
  9427. return this._cachedTextureMatrix;
  9428. }
  9429. this._cachedUOffset = this.uOffset;
  9430. this._cachedVOffset = this.vOffset;
  9431. this._cachedUScale = this.uScale;
  9432. this._cachedVScale = this.vScale;
  9433. this._cachedUAng = this.uAng;
  9434. this._cachedVAng = this.vAng;
  9435. this._cachedWAng = this.wAng;
  9436. if (!this._cachedTextureMatrix) {
  9437. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9438. this._rowGenerationMatrix = new BABYLON.Matrix();
  9439. this._t0 = BABYLON.Vector3.Zero();
  9440. this._t1 = BABYLON.Vector3.Zero();
  9441. this._t2 = BABYLON.Vector3.Zero();
  9442. }
  9443. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  9444. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  9445. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  9446. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  9447. this._t1.subtractInPlace(this._t0);
  9448. this._t2.subtractInPlace(this._t0);
  9449. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9450. this._cachedTextureMatrix.m[0] = this._t1.x;
  9451. this._cachedTextureMatrix.m[1] = this._t1.y;
  9452. this._cachedTextureMatrix.m[2] = this._t1.z;
  9453. this._cachedTextureMatrix.m[4] = this._t2.x;
  9454. this._cachedTextureMatrix.m[5] = this._t2.y;
  9455. this._cachedTextureMatrix.m[6] = this._t2.z;
  9456. this._cachedTextureMatrix.m[8] = this._t0.x;
  9457. this._cachedTextureMatrix.m[9] = this._t0.y;
  9458. this._cachedTextureMatrix.m[10] = this._t0.z;
  9459. return this._cachedTextureMatrix;
  9460. };
  9461. Texture.prototype.getReflectionTextureMatrix = function () {
  9462. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  9463. return this._cachedTextureMatrix;
  9464. }
  9465. if (!this._cachedTextureMatrix) {
  9466. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9467. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  9468. }
  9469. switch (this.coordinatesMode) {
  9470. case BABYLON.Texture.SPHERICAL_MODE:
  9471. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9472. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  9473. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  9474. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  9475. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  9476. break;
  9477. case BABYLON.Texture.PLANAR_MODE:
  9478. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9479. this._cachedTextureMatrix[0] = this.uScale;
  9480. this._cachedTextureMatrix[5] = this.vScale;
  9481. this._cachedTextureMatrix[12] = this.uOffset;
  9482. this._cachedTextureMatrix[13] = this.vOffset;
  9483. break;
  9484. case BABYLON.Texture.PROJECTION_MODE:
  9485. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  9486. this._projectionModeMatrix.m[0] = 0.5;
  9487. this._projectionModeMatrix.m[5] = -0.5;
  9488. this._projectionModeMatrix.m[10] = 0.0;
  9489. this._projectionModeMatrix.m[12] = 0.5;
  9490. this._projectionModeMatrix.m[13] = 0.5;
  9491. this._projectionModeMatrix.m[14] = 1.0;
  9492. this._projectionModeMatrix.m[15] = 1.0;
  9493. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  9494. break;
  9495. default:
  9496. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9497. break;
  9498. }
  9499. return this._cachedTextureMatrix;
  9500. };
  9501. Texture.prototype.clone = function () {
  9502. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  9503. newTexture.hasAlpha = this.hasAlpha;
  9504. newTexture.level = this.level;
  9505. newTexture.wrapU = this.wrapU;
  9506. newTexture.wrapV = this.wrapV;
  9507. newTexture.coordinatesIndex = this.coordinatesIndex;
  9508. newTexture.coordinatesMode = this.coordinatesMode;
  9509. newTexture.uOffset = this.uOffset;
  9510. newTexture.vOffset = this.vOffset;
  9511. newTexture.uScale = this.uScale;
  9512. newTexture.vScale = this.vScale;
  9513. newTexture.uAng = this.uAng;
  9514. newTexture.vAng = this.vAng;
  9515. newTexture.wAng = this.wAng;
  9516. return newTexture;
  9517. };
  9518. Texture.NEAREST_SAMPLINGMODE = 1;
  9519. Texture.BILINEAR_SAMPLINGMODE = 2;
  9520. Texture.TRILINEAR_SAMPLINGMODE = 3;
  9521. Texture.EXPLICIT_MODE = 0;
  9522. Texture.SPHERICAL_MODE = 1;
  9523. Texture.PLANAR_MODE = 2;
  9524. Texture.CUBIC_MODE = 3;
  9525. Texture.PROJECTION_MODE = 4;
  9526. Texture.SKYBOX_MODE = 5;
  9527. Texture.CLAMP_ADDRESSMODE = 0;
  9528. Texture.WRAP_ADDRESSMODE = 1;
  9529. Texture.MIRROR_ADDRESSMODE = 2;
  9530. return Texture;
  9531. })(BABYLON.BaseTexture);
  9532. BABYLON.Texture = Texture;
  9533. })(BABYLON || (BABYLON = {}));
  9534. var __extends = this.__extends || function (d, b) {
  9535. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9536. function __() { this.constructor = d; }
  9537. __.prototype = b.prototype;
  9538. d.prototype = new __();
  9539. };
  9540. var BABYLON;
  9541. (function (BABYLON) {
  9542. var CubeTexture = (function (_super) {
  9543. __extends(CubeTexture, _super);
  9544. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  9545. _super.call(this, scene);
  9546. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  9547. this.name = rootUrl;
  9548. this.url = rootUrl;
  9549. this._noMipmap = noMipmap;
  9550. this.hasAlpha = false;
  9551. this._texture = this._getFromCache(rootUrl, noMipmap);
  9552. if (!extensions) {
  9553. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  9554. }
  9555. this._extensions = extensions;
  9556. if (!this._texture) {
  9557. if (!scene.useDelayedTextureLoading) {
  9558. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  9559. } else {
  9560. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9561. }
  9562. }
  9563. this.isCube = true;
  9564. this._textureMatrix = BABYLON.Matrix.Identity();
  9565. }
  9566. CubeTexture.prototype.clone = function () {
  9567. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  9568. newTexture.level = this.level;
  9569. newTexture.wrapU = this.wrapU;
  9570. newTexture.wrapV = this.wrapV;
  9571. newTexture.coordinatesIndex = this.coordinatesIndex;
  9572. newTexture.coordinatesMode = this.coordinatesMode;
  9573. return newTexture;
  9574. };
  9575. CubeTexture.prototype.delayLoad = function () {
  9576. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9577. return;
  9578. }
  9579. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9580. this._texture = this._getFromCache(this.url, this._noMipmap);
  9581. if (!this._texture) {
  9582. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  9583. }
  9584. };
  9585. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  9586. return this._textureMatrix;
  9587. };
  9588. return CubeTexture;
  9589. })(BABYLON.BaseTexture);
  9590. BABYLON.CubeTexture = CubeTexture;
  9591. })(BABYLON || (BABYLON = {}));
  9592. var __extends = this.__extends || function (d, b) {
  9593. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9594. function __() { this.constructor = d; }
  9595. __.prototype = b.prototype;
  9596. d.prototype = new __();
  9597. };
  9598. var BABYLON;
  9599. (function (BABYLON) {
  9600. var RenderTargetTexture = (function (_super) {
  9601. __extends(RenderTargetTexture, _super);
  9602. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  9603. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  9604. _super.call(this, null, scene, !generateMipMaps);
  9605. this.renderList = new Array();
  9606. this.renderParticles = true;
  9607. this.renderSprites = false;
  9608. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  9609. this._currentRefreshId = -1;
  9610. this._refreshRate = 1;
  9611. this.name = name;
  9612. this.isRenderTarget = true;
  9613. this._size = size;
  9614. this._generateMipMaps = generateMipMaps;
  9615. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  9616. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  9617. this._renderingManager = new BABYLON.RenderingManager(scene);
  9618. }
  9619. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  9620. this._currentRefreshId = -1;
  9621. };
  9622. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  9623. get: function () {
  9624. return this._refreshRate;
  9625. },
  9626. set: function (value) {
  9627. this._refreshRate = value;
  9628. this.resetRefreshCounter();
  9629. },
  9630. enumerable: true,
  9631. configurable: true
  9632. });
  9633. RenderTargetTexture.prototype._shouldRender = function () {
  9634. if (this._currentRefreshId === -1) {
  9635. this._currentRefreshId = 1;
  9636. return true;
  9637. }
  9638. if (this.refreshRate == this._currentRefreshId) {
  9639. this._currentRefreshId = 1;
  9640. return true;
  9641. }
  9642. this._currentRefreshId++;
  9643. return false;
  9644. };
  9645. RenderTargetTexture.prototype.isReady = function () {
  9646. if (!this.getScene().renderTargetsEnabled) {
  9647. return false;
  9648. }
  9649. return _super.prototype.isReady.call(this);
  9650. };
  9651. RenderTargetTexture.prototype.getRenderSize = function () {
  9652. return this._size;
  9653. };
  9654. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  9655. get: function () {
  9656. return true;
  9657. },
  9658. enumerable: true,
  9659. configurable: true
  9660. });
  9661. RenderTargetTexture.prototype.scale = function (ratio) {
  9662. var newSize = this._size * ratio;
  9663. this.resize(newSize, this._generateMipMaps);
  9664. };
  9665. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  9666. this.releaseInternalTexture();
  9667. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  9668. };
  9669. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  9670. var scene = this.getScene();
  9671. var engine = scene.getEngine();
  9672. if (this._waitingRenderList) {
  9673. this.renderList = [];
  9674. for (var index = 0; index < this._waitingRenderList.length; index++) {
  9675. var id = this._waitingRenderList[index];
  9676. this.renderList.push(scene.getMeshByID(id));
  9677. }
  9678. delete this._waitingRenderList;
  9679. }
  9680. if (!this.renderList) {
  9681. return;
  9682. }
  9683. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  9684. engine.bindFramebuffer(this._texture);
  9685. }
  9686. engine.clear(scene.clearColor, true, true);
  9687. this._renderingManager.reset();
  9688. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  9689. var mesh = this.renderList[meshIndex];
  9690. if (mesh) {
  9691. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  9692. this.resetRefreshCounter();
  9693. continue;
  9694. }
  9695. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  9696. mesh._activate(scene.getRenderId());
  9697. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  9698. var subMesh = mesh.subMeshes[subIndex];
  9699. scene._activeVertices += subMesh.verticesCount;
  9700. this._renderingManager.dispatch(subMesh);
  9701. }
  9702. }
  9703. }
  9704. }
  9705. if (!this._doNotChangeAspectRatio) {
  9706. scene.updateTransformMatrix(true);
  9707. }
  9708. if (this.onBeforeRender) {
  9709. this.onBeforeRender();
  9710. }
  9711. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  9712. if (useCameraPostProcess) {
  9713. scene.postProcessManager._finalizeFrame(false, this._texture);
  9714. }
  9715. if (this.onAfterRender) {
  9716. this.onAfterRender();
  9717. }
  9718. engine.unBindFramebuffer(this._texture);
  9719. if (!this._doNotChangeAspectRatio) {
  9720. scene.updateTransformMatrix(true);
  9721. }
  9722. };
  9723. RenderTargetTexture.prototype.clone = function () {
  9724. var textureSize = this.getSize();
  9725. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  9726. newTexture.hasAlpha = this.hasAlpha;
  9727. newTexture.level = this.level;
  9728. newTexture.coordinatesMode = this.coordinatesMode;
  9729. newTexture.renderList = this.renderList.slice(0);
  9730. return newTexture;
  9731. };
  9732. return RenderTargetTexture;
  9733. })(BABYLON.Texture);
  9734. BABYLON.RenderTargetTexture = RenderTargetTexture;
  9735. })(BABYLON || (BABYLON = {}));
  9736. var __extends = this.__extends || function (d, b) {
  9737. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9738. function __() { this.constructor = d; }
  9739. __.prototype = b.prototype;
  9740. d.prototype = new __();
  9741. };
  9742. var BABYLON;
  9743. (function (BABYLON) {
  9744. var ProceduralTexture = (function (_super) {
  9745. __extends(ProceduralTexture, _super);
  9746. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  9747. _super.call(this, null, scene, !generateMipMaps);
  9748. this._currentRefreshId = -1;
  9749. this._refreshRate = 1;
  9750. this._vertexDeclaration = [2];
  9751. this._vertexStrideSize = 2 * 4;
  9752. this._uniforms = new Array();
  9753. this._samplers = new Array();
  9754. this._textures = new Array();
  9755. this._floats = new Array();
  9756. this._floatsArrays = {};
  9757. this._colors3 = new Array();
  9758. this._colors4 = new Array();
  9759. this._vectors2 = new Array();
  9760. this._vectors3 = new Array();
  9761. this._matrices = new Array();
  9762. scene._proceduralTextures.push(this);
  9763. this.name = name;
  9764. this.isRenderTarget = true;
  9765. this._size = size;
  9766. this._generateMipMaps = generateMipMaps;
  9767. this._fragment = fragment;
  9768. this._fallbackTexture = fallbackTexture;
  9769. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  9770. var vertices = [];
  9771. vertices.push(1, 1);
  9772. vertices.push(-1, 1);
  9773. vertices.push(-1, -1);
  9774. vertices.push(1, -1);
  9775. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  9776. var indices = [];
  9777. indices.push(0);
  9778. indices.push(1);
  9779. indices.push(2);
  9780. indices.push(0);
  9781. indices.push(2);
  9782. indices.push(3);
  9783. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  9784. }
  9785. ProceduralTexture.prototype.isReady = function () {
  9786. var _this = this;
  9787. var engine = this.getScene().getEngine();
  9788. this._effect = engine.createEffect({ vertex: "procedural", fragment: this._fragment }, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  9789. _this.releaseInternalTexture();
  9790. _this._texture = _this._fallbackTexture._texture;
  9791. _this._texture.references++;
  9792. });
  9793. return this._effect.isReady();
  9794. };
  9795. ProceduralTexture.prototype.resetRefreshCounter = function () {
  9796. this._currentRefreshId = -1;
  9797. };
  9798. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  9799. get: function () {
  9800. return this._refreshRate;
  9801. },
  9802. set: function (value) {
  9803. this._refreshRate = value;
  9804. this.resetRefreshCounter();
  9805. },
  9806. enumerable: true,
  9807. configurable: true
  9808. });
  9809. ProceduralTexture.prototype._shouldRender = function () {
  9810. if (!this.isReady() || !this._texture) {
  9811. return false;
  9812. }
  9813. if (this._currentRefreshId === -1) {
  9814. this._currentRefreshId = 1;
  9815. return true;
  9816. }
  9817. if (this.refreshRate == this._currentRefreshId) {
  9818. this._currentRefreshId = 1;
  9819. return true;
  9820. }
  9821. this._currentRefreshId++;
  9822. return false;
  9823. };
  9824. ProceduralTexture.prototype.getRenderSize = function () {
  9825. return this._size;
  9826. };
  9827. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  9828. this.releaseInternalTexture();
  9829. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  9830. };
  9831. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  9832. if (this._uniforms.indexOf(uniformName) === -1) {
  9833. this._uniforms.push(uniformName);
  9834. }
  9835. };
  9836. ProceduralTexture.prototype.setTexture = function (name, texture) {
  9837. if (this._samplers.indexOf(name) === -1) {
  9838. this._samplers.push(name);
  9839. }
  9840. this._textures[name] = texture;
  9841. return this;
  9842. };
  9843. ProceduralTexture.prototype.setFloat = function (name, value) {
  9844. this._checkUniform(name);
  9845. this._floats[name] = value;
  9846. return this;
  9847. };
  9848. ProceduralTexture.prototype.setFloats = function (name, value) {
  9849. this._checkUniform(name);
  9850. this._floatsArrays[name] = value;
  9851. return this;
  9852. };
  9853. ProceduralTexture.prototype.setColor3 = function (name, value) {
  9854. this._checkUniform(name);
  9855. this._colors3[name] = value;
  9856. return this;
  9857. };
  9858. ProceduralTexture.prototype.setColor4 = function (name, value) {
  9859. this._checkUniform(name);
  9860. this._colors4[name] = value;
  9861. return this;
  9862. };
  9863. ProceduralTexture.prototype.setVector2 = function (name, value) {
  9864. this._checkUniform(name);
  9865. this._vectors2[name] = value;
  9866. return this;
  9867. };
  9868. ProceduralTexture.prototype.setVector3 = function (name, value) {
  9869. this._checkUniform(name);
  9870. this._vectors3[name] = value;
  9871. return this;
  9872. };
  9873. ProceduralTexture.prototype.setMatrix = function (name, value) {
  9874. this._checkUniform(name);
  9875. this._matrices[name] = value;
  9876. return this;
  9877. };
  9878. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  9879. var scene = this.getScene();
  9880. var engine = scene.getEngine();
  9881. engine.bindFramebuffer(this._texture);
  9882. engine.clear(scene.clearColor, true, true);
  9883. engine.enableEffect(this._effect);
  9884. engine.setState(false);
  9885. for (var name in this._textures) {
  9886. this._effect.setTexture(name, this._textures[name]);
  9887. }
  9888. for (name in this._floats) {
  9889. this._effect.setFloat(name, this._floats[name]);
  9890. }
  9891. for (name in this._floatsArrays) {
  9892. this._effect.setArray(name, this._floatsArrays[name]);
  9893. }
  9894. for (name in this._colors3) {
  9895. this._effect.setColor3(name, this._colors3[name]);
  9896. }
  9897. for (name in this._colors4) {
  9898. var color = this._colors4[name];
  9899. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  9900. }
  9901. for (name in this._vectors2) {
  9902. this._effect.setVector2(name, this._vectors2[name]);
  9903. }
  9904. for (name in this._vectors3) {
  9905. this._effect.setVector3(name, this._vectors3[name]);
  9906. }
  9907. for (name in this._matrices) {
  9908. this._effect.setMatrix(name, this._matrices[name]);
  9909. }
  9910. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  9911. engine.draw(true, 0, 6);
  9912. engine.unBindFramebuffer(this._texture);
  9913. };
  9914. ProceduralTexture.prototype.clone = function () {
  9915. var textureSize = this.getSize();
  9916. var newTexture = new BABYLON.ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  9917. newTexture.hasAlpha = this.hasAlpha;
  9918. newTexture.level = this.level;
  9919. newTexture.coordinatesMode = this.coordinatesMode;
  9920. return newTexture;
  9921. };
  9922. ProceduralTexture.prototype.dispose = function () {
  9923. var index = this.getScene()._proceduralTextures.indexOf(this);
  9924. if (index >= 0) {
  9925. this.getScene()._proceduralTextures.splice(index, 1);
  9926. }
  9927. _super.prototype.dispose.call(this);
  9928. };
  9929. return ProceduralTexture;
  9930. })(BABYLON.Texture);
  9931. BABYLON.ProceduralTexture = ProceduralTexture;
  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 WoodProceduralTexture = (function (_super) {
  9942. __extends(WoodProceduralTexture, _super);
  9943. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  9944. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  9945. this._ampScale = 0.03;
  9946. this._ringScale = 5;
  9947. this._woodColor1 = new BABYLON.Color3(0.80, 0.55, 0.01);
  9948. this._woodColor2 = new BABYLON.Color3(0.60, 0.41, 0.0);
  9949. this.updateShaderUniforms();
  9950. this.refreshRate = 0;
  9951. }
  9952. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  9953. this.setFloat("ampScale", this._ampScale);
  9954. this.setFloat("ringScale", this._ringScale);
  9955. this.setColor3("woodColor1", this._woodColor1);
  9956. this.setColor3("woodColor2", this._woodColor2);
  9957. };
  9958. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  9959. get: function () {
  9960. return this._ampScale;
  9961. },
  9962. set: function (value) {
  9963. this._ampScale = value;
  9964. this.updateShaderUniforms();
  9965. },
  9966. enumerable: true,
  9967. configurable: true
  9968. });
  9969. Object.defineProperty(WoodProceduralTexture.prototype, "ringScale", {
  9970. get: function () {
  9971. return this._ringScale;
  9972. },
  9973. set: function (value) {
  9974. this._ringScale = value;
  9975. this.updateShaderUniforms();
  9976. },
  9977. enumerable: true,
  9978. configurable: true
  9979. });
  9980. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor1", {
  9981. get: function () {
  9982. return this._woodColor1;
  9983. },
  9984. set: function (value) {
  9985. this._woodColor1 = value;
  9986. this.updateShaderUniforms();
  9987. },
  9988. enumerable: true,
  9989. configurable: true
  9990. });
  9991. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor2", {
  9992. get: function () {
  9993. return this._woodColor2;
  9994. },
  9995. set: function (value) {
  9996. this._woodColor2 = value;
  9997. this.updateShaderUniforms();
  9998. },
  9999. enumerable: true,
  10000. configurable: true
  10001. });
  10002. return WoodProceduralTexture;
  10003. })(BABYLON.ProceduralTexture);
  10004. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  10005. var FireProceduralTexture = (function (_super) {
  10006. __extends(FireProceduralTexture, _super);
  10007. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10008. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  10009. this._time = 0.0;
  10010. this._speed = new BABYLON.Vector2(0.5, 0.3);
  10011. this._shift = 1.6;
  10012. this._alpha = 1.0;
  10013. this._autoGenerateTime = true;
  10014. this._fireColors = FireProceduralTexture.RedFireColors;
  10015. this.updateShaderUniforms();
  10016. this.refreshRate = 1;
  10017. }
  10018. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  10019. this.setFloat("iGlobalTime", this._time);
  10020. this.setVector2("speed", this._speed);
  10021. this.setFloat("shift", this._shift);
  10022. this.setFloat("alpha", this._alpha);
  10023. this.setColor3("c1", new BABYLON.Color3(this._fireColors[0][0], this._fireColors[0][1], this._fireColors[0][2]));
  10024. this.setColor3("c2", new BABYLON.Color3(this._fireColors[1][0], this._fireColors[1][1], this._fireColors[1][2]));
  10025. this.setColor3("c3", new BABYLON.Color3(this._fireColors[2][0], this._fireColors[2][1], this._fireColors[2][2]));
  10026. this.setColor3("c4", new BABYLON.Color3(this._fireColors[3][0], this._fireColors[3][1], this._fireColors[3][2]));
  10027. this.setColor3("c5", new BABYLON.Color3(this._fireColors[4][0], this._fireColors[4][1], this._fireColors[4][2]));
  10028. this.setColor3("c6", new BABYLON.Color3(this._fireColors[5][0], this._fireColors[5][1], this._fireColors[5][2]));
  10029. };
  10030. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  10031. if (this._autoGenerateTime) {
  10032. this._time += this.getScene().getAnimationRatio() * 0.03;
  10033. this.updateShaderUniforms();
  10034. }
  10035. _super.prototype.render.call(this, useCameraPostProcess);
  10036. };
  10037. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  10038. get: function () {
  10039. return [
  10040. [0.5, 0.0, 1.0],
  10041. [0.9, 0.0, 1.0],
  10042. [0.2, 0.0, 1.0],
  10043. [1.0, 0.9, 1.0],
  10044. [0.1, 0.1, 1.0],
  10045. [0.9, 0.9, 1.0]
  10046. ];
  10047. },
  10048. enumerable: true,
  10049. configurable: true
  10050. });
  10051. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  10052. get: function () {
  10053. return [
  10054. [0.5, 1.0, 0.0],
  10055. [0.5, 1.0, 0.0],
  10056. [0.3, 0.4, 0.0],
  10057. [0.5, 1.0, 0.0],
  10058. [0.2, 0.0, 0.0],
  10059. [0.5, 1.0, 0.0]
  10060. ];
  10061. },
  10062. enumerable: true,
  10063. configurable: true
  10064. });
  10065. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  10066. get: function () {
  10067. return [
  10068. [0.5, 0.0, 0.1],
  10069. [0.9, 0.0, 0.0],
  10070. [0.2, 0.0, 0.0],
  10071. [1.0, 0.9, 0.0],
  10072. [0.1, 0.1, 0.1],
  10073. [0.9, 0.9, 0.9]
  10074. ];
  10075. },
  10076. enumerable: true,
  10077. configurable: true
  10078. });
  10079. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  10080. get: function () {
  10081. return [
  10082. [0.1, 0.0, 0.5],
  10083. [0.0, 0.0, 0.5],
  10084. [0.1, 0.0, 0.2],
  10085. [0.0, 0.0, 1.0],
  10086. [0.1, 0.2, 0.3],
  10087. [0.0, 0.2, 0.9]
  10088. ];
  10089. },
  10090. enumerable: true,
  10091. configurable: true
  10092. });
  10093. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  10094. get: function () {
  10095. return this._fireColors;
  10096. },
  10097. set: function (value) {
  10098. this._fireColors = value;
  10099. this.updateShaderUniforms();
  10100. },
  10101. enumerable: true,
  10102. configurable: true
  10103. });
  10104. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  10105. get: function () {
  10106. return this._time;
  10107. },
  10108. set: function (value) {
  10109. this._time = value;
  10110. this.updateShaderUniforms();
  10111. },
  10112. enumerable: true,
  10113. configurable: true
  10114. });
  10115. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  10116. get: function () {
  10117. return this._speed;
  10118. },
  10119. set: function (value) {
  10120. this._speed = value;
  10121. this.updateShaderUniforms();
  10122. },
  10123. enumerable: true,
  10124. configurable: true
  10125. });
  10126. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  10127. get: function () {
  10128. return this._shift;
  10129. },
  10130. set: function (value) {
  10131. this._shift = value;
  10132. this.updateShaderUniforms();
  10133. },
  10134. enumerable: true,
  10135. configurable: true
  10136. });
  10137. Object.defineProperty(FireProceduralTexture.prototype, "alpha", {
  10138. get: function () {
  10139. return this._alpha;
  10140. },
  10141. set: function (value) {
  10142. this._alpha = value;
  10143. this.updateShaderUniforms();
  10144. },
  10145. enumerable: true,
  10146. configurable: true
  10147. });
  10148. return FireProceduralTexture;
  10149. })(BABYLON.ProceduralTexture);
  10150. BABYLON.FireProceduralTexture = FireProceduralTexture;
  10151. })(BABYLON || (BABYLON = {}));
  10152. var __extends = this.__extends || function (d, b) {
  10153. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10154. function __() { this.constructor = d; }
  10155. __.prototype = b.prototype;
  10156. d.prototype = new __();
  10157. };
  10158. var BABYLON;
  10159. (function (BABYLON) {
  10160. var MirrorTexture = (function (_super) {
  10161. __extends(MirrorTexture, _super);
  10162. function MirrorTexture(name, size, scene, generateMipMaps) {
  10163. var _this = this;
  10164. _super.call(this, name, size, scene, generateMipMaps, true);
  10165. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  10166. this._transformMatrix = BABYLON.Matrix.Zero();
  10167. this._mirrorMatrix = BABYLON.Matrix.Zero();
  10168. this.onBeforeRender = function () {
  10169. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  10170. _this._savedViewMatrix = scene.getViewMatrix();
  10171. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  10172. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  10173. scene.clipPlane = _this.mirrorPlane;
  10174. scene.getEngine().cullBackFaces = false;
  10175. };
  10176. this.onAfterRender = function () {
  10177. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  10178. scene.getEngine().cullBackFaces = true;
  10179. delete scene.clipPlane;
  10180. };
  10181. }
  10182. MirrorTexture.prototype.clone = function () {
  10183. var textureSize = this.getSize();
  10184. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10185. newTexture.hasAlpha = this.hasAlpha;
  10186. newTexture.level = this.level;
  10187. newTexture.mirrorPlane = this.mirrorPlane.clone();
  10188. newTexture.renderList = this.renderList.slice(0);
  10189. return newTexture;
  10190. };
  10191. return MirrorTexture;
  10192. })(BABYLON.RenderTargetTexture);
  10193. BABYLON.MirrorTexture = MirrorTexture;
  10194. })(BABYLON || (BABYLON = {}));
  10195. var __extends = this.__extends || function (d, b) {
  10196. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10197. function __() { this.constructor = d; }
  10198. __.prototype = b.prototype;
  10199. d.prototype = new __();
  10200. };
  10201. var BABYLON;
  10202. (function (BABYLON) {
  10203. var DynamicTexture = (function (_super) {
  10204. __extends(DynamicTexture, _super);
  10205. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  10206. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10207. _super.call(this, null, scene, !generateMipMaps);
  10208. this.name = name;
  10209. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10210. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10211. this._generateMipMaps = generateMipMaps;
  10212. if (options.getContext) {
  10213. this._canvas = options;
  10214. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  10215. } else {
  10216. this._canvas = document.createElement("canvas");
  10217. if (options.width) {
  10218. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  10219. } else {
  10220. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  10221. }
  10222. }
  10223. var textureSize = this.getSize();
  10224. this._canvas.width = textureSize.width;
  10225. this._canvas.height = textureSize.height;
  10226. this._context = this._canvas.getContext("2d");
  10227. }
  10228. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  10229. get: function () {
  10230. return true;
  10231. },
  10232. enumerable: true,
  10233. configurable: true
  10234. });
  10235. DynamicTexture.prototype.scale = function (ratio) {
  10236. var textureSize = this.getSize();
  10237. textureSize.width *= ratio;
  10238. textureSize.height *= ratio;
  10239. this._canvas.width = textureSize.width;
  10240. this._canvas.height = textureSize.height;
  10241. this.releaseInternalTexture();
  10242. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  10243. };
  10244. DynamicTexture.prototype.getContext = function () {
  10245. return this._context;
  10246. };
  10247. DynamicTexture.prototype.update = function (invertY) {
  10248. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  10249. };
  10250. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  10251. var size = this.getSize();
  10252. if (clearColor) {
  10253. this._context.fillStyle = clearColor;
  10254. this._context.fillRect(0, 0, size.width, size.height);
  10255. }
  10256. this._context.font = font;
  10257. if (x === null) {
  10258. var textSize = this._context.measureText(text);
  10259. x = (size.width - textSize.width) / 2;
  10260. }
  10261. this._context.fillStyle = color;
  10262. this._context.fillText(text, x, y);
  10263. this.update(invertY);
  10264. };
  10265. DynamicTexture.prototype.clone = function () {
  10266. var textureSize = this.getSize();
  10267. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10268. newTexture.hasAlpha = this.hasAlpha;
  10269. newTexture.level = this.level;
  10270. newTexture.wrapU = this.wrapU;
  10271. newTexture.wrapV = this.wrapV;
  10272. return newTexture;
  10273. };
  10274. return DynamicTexture;
  10275. })(BABYLON.Texture);
  10276. BABYLON.DynamicTexture = DynamicTexture;
  10277. })(BABYLON || (BABYLON = {}));
  10278. var __extends = this.__extends || function (d, b) {
  10279. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10280. function __() { this.constructor = d; }
  10281. __.prototype = b.prototype;
  10282. d.prototype = new __();
  10283. };
  10284. var BABYLON;
  10285. (function (BABYLON) {
  10286. var VideoTexture = (function (_super) {
  10287. __extends(VideoTexture, _super);
  10288. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  10289. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10290. var _this = this;
  10291. _super.call(this, null, scene, !generateMipMaps, invertY);
  10292. this._autoLaunch = true;
  10293. this.name = name;
  10294. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  10295. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  10296. var requiredWidth = size.width || size;
  10297. var requiredHeight = size.height || size;
  10298. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  10299. var textureSize = this.getSize();
  10300. this.video = document.createElement("video");
  10301. this.video.width = textureSize.width;
  10302. this.video.height = textureSize.height;
  10303. this.video.autoplay = false;
  10304. this.video.loop = true;
  10305. this.video.addEventListener("canplaythrough", function () {
  10306. if (_this._texture) {
  10307. _this._texture.isReady = true;
  10308. }
  10309. });
  10310. urls.forEach(function (url) {
  10311. var source = document.createElement("source");
  10312. source.src = url;
  10313. _this.video.appendChild(source);
  10314. });
  10315. this._lastUpdate = BABYLON.Tools.Now;
  10316. }
  10317. VideoTexture.prototype.update = function () {
  10318. if (this._autoLaunch) {
  10319. this._autoLaunch = false;
  10320. this.video.play();
  10321. }
  10322. var now = BABYLON.Tools.Now;
  10323. if (now - this._lastUpdate < 15) {
  10324. return false;
  10325. }
  10326. this._lastUpdate = now;
  10327. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  10328. return true;
  10329. };
  10330. return VideoTexture;
  10331. })(BABYLON.Texture);
  10332. BABYLON.VideoTexture = VideoTexture;
  10333. })(BABYLON || (BABYLON = {}));
  10334. var BABYLON;
  10335. (function (BABYLON) {
  10336. var EffectFallbacks = (function () {
  10337. function EffectFallbacks() {
  10338. this._defines = {};
  10339. this._currentRank = 32;
  10340. this._maxRank = -1;
  10341. }
  10342. EffectFallbacks.prototype.addFallback = function (rank, define) {
  10343. if (!this._defines[rank]) {
  10344. if (rank < this._currentRank) {
  10345. this._currentRank = rank;
  10346. }
  10347. if (rank > this._maxRank) {
  10348. this._maxRank = rank;
  10349. }
  10350. this._defines[rank] = new Array();
  10351. }
  10352. this._defines[rank].push(define);
  10353. };
  10354. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  10355. get: function () {
  10356. return this._currentRank <= this._maxRank;
  10357. },
  10358. enumerable: true,
  10359. configurable: true
  10360. });
  10361. EffectFallbacks.prototype.reduce = function (currentDefines) {
  10362. var currentFallbacks = this._defines[this._currentRank];
  10363. for (var index = 0; index < currentFallbacks.length; index++) {
  10364. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  10365. }
  10366. this._currentRank++;
  10367. return currentDefines;
  10368. };
  10369. return EffectFallbacks;
  10370. })();
  10371. BABYLON.EffectFallbacks = EffectFallbacks;
  10372. var Effect = (function () {
  10373. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  10374. var _this = this;
  10375. this._isReady = false;
  10376. this._compilationError = "";
  10377. this._valueCache = [];
  10378. this._engine = engine;
  10379. this.name = baseName;
  10380. this.defines = defines;
  10381. this._uniformsNames = uniformsNames.concat(samplers);
  10382. this._samplers = samplers;
  10383. this._attributesNames = attributesNames;
  10384. this.onError = onError;
  10385. this.onCompiled = onCompiled;
  10386. var vertexSource;
  10387. var fragmentSource;
  10388. if (baseName.vertexElement) {
  10389. vertexSource = document.getElementById(baseName.vertexElement);
  10390. if (!vertexSource) {
  10391. vertexSource = baseName.vertexElement;
  10392. }
  10393. } else {
  10394. vertexSource = baseName.vertex || baseName;
  10395. }
  10396. if (baseName.fragmentElement) {
  10397. fragmentSource = document.getElementById(baseName.fragmentElement);
  10398. if (!fragmentSource) {
  10399. fragmentSource = baseName.fragmentElement;
  10400. }
  10401. } else {
  10402. fragmentSource = baseName.fragment || baseName;
  10403. }
  10404. this._loadVertexShader(vertexSource, function (vertexCode) {
  10405. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  10406. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  10407. });
  10408. });
  10409. }
  10410. Effect.prototype.isReady = function () {
  10411. return this._isReady;
  10412. };
  10413. Effect.prototype.getProgram = function () {
  10414. return this._program;
  10415. };
  10416. Effect.prototype.getAttributesNames = function () {
  10417. return this._attributesNames;
  10418. };
  10419. Effect.prototype.getAttributeLocation = function (index) {
  10420. return this._attributes[index];
  10421. };
  10422. Effect.prototype.getAttributeLocationByName = function (name) {
  10423. var index = this._attributesNames.indexOf(name);
  10424. return this._attributes[index];
  10425. };
  10426. Effect.prototype.getAttributesCount = function () {
  10427. return this._attributes.length;
  10428. };
  10429. Effect.prototype.getUniformIndex = function (uniformName) {
  10430. return this._uniformsNames.indexOf(uniformName);
  10431. };
  10432. Effect.prototype.getUniform = function (uniformName) {
  10433. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  10434. };
  10435. Effect.prototype.getSamplers = function () {
  10436. return this._samplers;
  10437. };
  10438. Effect.prototype.getCompilationError = function () {
  10439. return this._compilationError;
  10440. };
  10441. Effect.prototype._loadVertexShader = function (vertex, callback) {
  10442. if (vertex instanceof HTMLElement) {
  10443. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  10444. callback(vertexCode);
  10445. return;
  10446. }
  10447. if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
  10448. callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
  10449. return;
  10450. }
  10451. var vertexShaderUrl;
  10452. if (vertex[0] === ".") {
  10453. vertexShaderUrl = vertex;
  10454. } else {
  10455. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  10456. }
  10457. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  10458. };
  10459. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  10460. if (fragment instanceof HTMLElement) {
  10461. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  10462. callback(fragmentCode);
  10463. return;
  10464. }
  10465. if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
  10466. callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
  10467. return;
  10468. }
  10469. if (BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]) {
  10470. callback(BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]);
  10471. return;
  10472. }
  10473. var fragmentShaderUrl;
  10474. if (fragment[0] === ".") {
  10475. fragmentShaderUrl = fragment;
  10476. } else {
  10477. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  10478. }
  10479. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  10480. };
  10481. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  10482. try {
  10483. var engine = this._engine;
  10484. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  10485. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  10486. this._attributes = engine.getAttributes(this._program, attributesNames);
  10487. for (var index = 0; index < this._samplers.length; index++) {
  10488. var sampler = this.getUniform(this._samplers[index]);
  10489. if (sampler == null) {
  10490. this._samplers.splice(index, 1);
  10491. index--;
  10492. }
  10493. }
  10494. engine.bindSamplers(this);
  10495. this._isReady = true;
  10496. if (this.onCompiled) {
  10497. this.onCompiled(this);
  10498. }
  10499. } catch (e) {
  10500. if (fallbacks && fallbacks.isMoreFallbacks) {
  10501. defines = fallbacks.reduce(defines);
  10502. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  10503. } else {
  10504. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  10505. BABYLON.Tools.Error("Defines: " + defines);
  10506. BABYLON.Tools.Error("Error: " + e.message);
  10507. this._compilationError = e.message;
  10508. if (this.onError) {
  10509. this.onError(this, this._compilationError);
  10510. }
  10511. }
  10512. }
  10513. };
  10514. Effect.prototype._bindTexture = function (channel, texture) {
  10515. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  10516. };
  10517. Effect.prototype.setTexture = function (channel, texture) {
  10518. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  10519. };
  10520. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10521. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  10522. };
  10523. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  10524. if (!this._valueCache[uniformName]) {
  10525. this._valueCache[uniformName] = [x, y];
  10526. return;
  10527. }
  10528. this._valueCache[uniformName][0] = x;
  10529. this._valueCache[uniformName][1] = y;
  10530. };
  10531. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  10532. if (!this._valueCache[uniformName]) {
  10533. this._valueCache[uniformName] = [x, y, z];
  10534. return;
  10535. }
  10536. this._valueCache[uniformName][0] = x;
  10537. this._valueCache[uniformName][1] = y;
  10538. this._valueCache[uniformName][2] = z;
  10539. };
  10540. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  10541. if (!this._valueCache[uniformName]) {
  10542. this._valueCache[uniformName] = [x, y, z, w];
  10543. return;
  10544. }
  10545. this._valueCache[uniformName][0] = x;
  10546. this._valueCache[uniformName][1] = y;
  10547. this._valueCache[uniformName][2] = z;
  10548. this._valueCache[uniformName][3] = w;
  10549. };
  10550. Effect.prototype.setArray = function (uniformName, array) {
  10551. this._engine.setArray(this.getUniform(uniformName), array);
  10552. return this;
  10553. };
  10554. Effect.prototype.setMatrices = function (uniformName, matrices) {
  10555. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  10556. return this;
  10557. };
  10558. Effect.prototype.setMatrix = function (uniformName, matrix) {
  10559. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  10560. return this;
  10561. };
  10562. Effect.prototype.setFloat = function (uniformName, value) {
  10563. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  10564. return this;
  10565. this._valueCache[uniformName] = value;
  10566. this._engine.setFloat(this.getUniform(uniformName), value);
  10567. return this;
  10568. };
  10569. Effect.prototype.setBool = function (uniformName, bool) {
  10570. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  10571. return this;
  10572. this._valueCache[uniformName] = bool;
  10573. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  10574. return this;
  10575. };
  10576. Effect.prototype.setVector2 = function (uniformName, vector2) {
  10577. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector2.x && this._valueCache[uniformName][1] == vector2.y)
  10578. return this;
  10579. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  10580. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  10581. return this;
  10582. };
  10583. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  10584. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y)
  10585. return this;
  10586. this._cacheFloat2(uniformName, x, y);
  10587. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  10588. return this;
  10589. };
  10590. Effect.prototype.setVector3 = function (uniformName, vector3) {
  10591. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector3.x && this._valueCache[uniformName][1] == vector3.y && this._valueCache[uniformName][2] == vector3.z)
  10592. return this;
  10593. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  10594. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  10595. return this;
  10596. };
  10597. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  10598. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z)
  10599. return this;
  10600. this._cacheFloat3(uniformName, x, y, z);
  10601. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  10602. return this;
  10603. };
  10604. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  10605. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z && this._valueCache[uniformName][3] == w)
  10606. return this;
  10607. this._cacheFloat4(uniformName, x, y, z, w);
  10608. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  10609. return this;
  10610. };
  10611. Effect.prototype.setColor3 = function (uniformName, color3) {
  10612. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b)
  10613. return this;
  10614. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  10615. this._engine.setColor3(this.getUniform(uniformName), color3);
  10616. return this;
  10617. };
  10618. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  10619. 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)
  10620. return this;
  10621. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  10622. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  10623. return this;
  10624. };
  10625. 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}",
  10626. 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}",
  10627. 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}",
  10628. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  10629. 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}",
  10630. 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}",
  10631. 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}",
  10632. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec3 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef REFLECTION\n vPositionUVW = position;\n#endif \n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n finalWorld = world;\n#endif\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}",
  10633. 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}",
  10634. 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}",
  10635. 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}",
  10636. 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}",
  10637. 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}",
  10638. 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}",
  10639. 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}",
  10640. 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}",
  10641. 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}",
  10642. 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}",
  10643. 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}",
  10644. 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}",
  10645. 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}",
  10646. 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}",
  10647. 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}",
  10648. 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}",
  10649. 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}",
  10650. 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}",
  10651. 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}",
  10652. 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}",
  10653. 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}",
  10654. 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}",
  10655. 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}",
  10656. 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}",
  10657. };
  10658. return Effect;
  10659. })();
  10660. BABYLON.Effect = Effect;
  10661. })(BABYLON || (BABYLON = {}));
  10662. var BABYLON;
  10663. (function (BABYLON) {
  10664. var Material = (function () {
  10665. function Material(name, scene, doNotAdd) {
  10666. this.name = name;
  10667. this.checkReadyOnEveryCall = true;
  10668. this.checkReadyOnlyOnce = false;
  10669. this.state = "";
  10670. this.alpha = 1.0;
  10671. this.wireframe = false;
  10672. this.backFaceCulling = true;
  10673. this._wasPreviouslyReady = false;
  10674. this.id = name;
  10675. this._scene = scene;
  10676. if (!doNotAdd) {
  10677. scene.materials.push(this);
  10678. }
  10679. }
  10680. Material.prototype.isReady = function (mesh, useInstances) {
  10681. return true;
  10682. };
  10683. Material.prototype.getEffect = function () {
  10684. return this._effect;
  10685. };
  10686. Material.prototype.getScene = function () {
  10687. return this._scene;
  10688. };
  10689. Material.prototype.needAlphaBlending = function () {
  10690. return (this.alpha < 1.0);
  10691. };
  10692. Material.prototype.needAlphaTesting = function () {
  10693. return false;
  10694. };
  10695. Material.prototype.getAlphaTestTexture = function () {
  10696. return null;
  10697. };
  10698. Material.prototype.trackCreation = function (onCompiled, onError) {
  10699. };
  10700. Material.prototype._preBind = function () {
  10701. var engine = this._scene.getEngine();
  10702. engine.enableEffect(this._effect);
  10703. engine.setState(this.backFaceCulling);
  10704. };
  10705. Material.prototype.bind = function (world, mesh) {
  10706. };
  10707. Material.prototype.bindOnlyWorldMatrix = function (world) {
  10708. };
  10709. Material.prototype.unbind = function () {
  10710. };
  10711. Material.prototype.dispose = function (forceDisposeEffect) {
  10712. var index = this._scene.materials.indexOf(this);
  10713. this._scene.materials.splice(index, 1);
  10714. if (forceDisposeEffect && this._effect) {
  10715. this._scene.getEngine()._releaseEffect(this._effect);
  10716. this._effect = null;
  10717. }
  10718. if (this.onDispose) {
  10719. this.onDispose();
  10720. }
  10721. };
  10722. return Material;
  10723. })();
  10724. BABYLON.Material = Material;
  10725. })(BABYLON || (BABYLON = {}));
  10726. var __extends = this.__extends || function (d, b) {
  10727. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10728. function __() { this.constructor = d; }
  10729. __.prototype = b.prototype;
  10730. d.prototype = new __();
  10731. };
  10732. var BABYLON;
  10733. (function (BABYLON) {
  10734. var maxSimultaneousLights = 4;
  10735. var FresnelParameters = (function () {
  10736. function FresnelParameters() {
  10737. this.isEnabled = true;
  10738. this.leftColor = BABYLON.Color3.White();
  10739. this.rightColor = BABYLON.Color3.Black();
  10740. this.bias = 0;
  10741. this.power = 1;
  10742. }
  10743. return FresnelParameters;
  10744. })();
  10745. BABYLON.FresnelParameters = FresnelParameters;
  10746. var StandardMaterial = (function (_super) {
  10747. __extends(StandardMaterial, _super);
  10748. function StandardMaterial(name, scene) {
  10749. var _this = this;
  10750. _super.call(this, name, scene);
  10751. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  10752. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  10753. this.specularColor = new BABYLON.Color3(1, 1, 1);
  10754. this.specularPower = 64;
  10755. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  10756. this.useAlphaFromDiffuseTexture = false;
  10757. this.useSpecularOverAlpha = true;
  10758. this.fogEnabled = true;
  10759. this._cachedDefines = null;
  10760. this._renderTargets = new BABYLON.SmartArray(16);
  10761. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  10762. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  10763. this._scaledDiffuse = new BABYLON.Color3();
  10764. this._scaledSpecular = new BABYLON.Color3();
  10765. this.getRenderTargetTextures = function () {
  10766. _this._renderTargets.reset();
  10767. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  10768. _this._renderTargets.push(_this.reflectionTexture);
  10769. }
  10770. return _this._renderTargets;
  10771. };
  10772. }
  10773. StandardMaterial.prototype.needAlphaBlending = function () {
  10774. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  10775. };
  10776. StandardMaterial.prototype.needAlphaTesting = function () {
  10777. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  10778. };
  10779. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  10780. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  10781. };
  10782. StandardMaterial.prototype.getAlphaTestTexture = function () {
  10783. return this.diffuseTexture;
  10784. };
  10785. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  10786. if (this.checkReadyOnlyOnce) {
  10787. if (this._wasPreviouslyReady) {
  10788. return true;
  10789. }
  10790. }
  10791. var scene = this.getScene();
  10792. if (!this.checkReadyOnEveryCall) {
  10793. if (this._renderId === scene.getRenderId()) {
  10794. return true;
  10795. }
  10796. }
  10797. var engine = scene.getEngine();
  10798. var defines = [];
  10799. var fallbacks = new BABYLON.EffectFallbacks();
  10800. if (scene.texturesEnabled) {
  10801. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  10802. if (!this.diffuseTexture.isReady()) {
  10803. return false;
  10804. } else {
  10805. defines.push("#define DIFFUSE");
  10806. }
  10807. }
  10808. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  10809. if (!this.ambientTexture.isReady()) {
  10810. return false;
  10811. } else {
  10812. defines.push("#define AMBIENT");
  10813. }
  10814. }
  10815. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  10816. if (!this.opacityTexture.isReady()) {
  10817. return false;
  10818. } else {
  10819. defines.push("#define OPACITY");
  10820. if (this.opacityTexture.getAlphaFromRGB) {
  10821. defines.push("#define OPACITYRGB");
  10822. }
  10823. }
  10824. }
  10825. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  10826. if (!this.reflectionTexture.isReady()) {
  10827. return false;
  10828. } else {
  10829. defines.push("#define REFLECTION");
  10830. fallbacks.addFallback(0, "REFLECTION");
  10831. }
  10832. }
  10833. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  10834. if (!this.emissiveTexture.isReady()) {
  10835. return false;
  10836. } else {
  10837. defines.push("#define EMISSIVE");
  10838. }
  10839. }
  10840. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  10841. if (!this.specularTexture.isReady()) {
  10842. return false;
  10843. } else {
  10844. defines.push("#define SPECULAR");
  10845. fallbacks.addFallback(0, "SPECULAR");
  10846. }
  10847. }
  10848. }
  10849. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  10850. if (!this.bumpTexture.isReady()) {
  10851. return false;
  10852. } else {
  10853. defines.push("#define BUMP");
  10854. fallbacks.addFallback(0, "BUMP");
  10855. }
  10856. }
  10857. if (this.useSpecularOverAlpha) {
  10858. defines.push("#define SPECULAROVERALPHA");
  10859. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  10860. }
  10861. if (scene.clipPlane) {
  10862. defines.push("#define CLIPPLANE");
  10863. }
  10864. if (engine.getAlphaTesting()) {
  10865. defines.push("#define ALPHATEST");
  10866. }
  10867. if (this._shouldUseAlphaFromDiffuseTexture()) {
  10868. defines.push("#define ALPHAFROMDIFFUSE");
  10869. }
  10870. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  10871. defines.push("#define FOG");
  10872. fallbacks.addFallback(1, "FOG");
  10873. }
  10874. var shadowsActivated = false;
  10875. var lightIndex = 0;
  10876. if (scene.lightsEnabled) {
  10877. for (var index = 0; index < scene.lights.length; index++) {
  10878. var light = scene.lights[index];
  10879. if (!light.isEnabled()) {
  10880. continue;
  10881. }
  10882. if (light._excludedMeshesIds.length > 0) {
  10883. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  10884. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  10885. if (excludedMesh) {
  10886. light.excludedMeshes.push(excludedMesh);
  10887. }
  10888. }
  10889. light._excludedMeshesIds = [];
  10890. }
  10891. if (light._includedOnlyMeshesIds.length > 0) {
  10892. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  10893. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  10894. if (includedOnlyMesh) {
  10895. light.includedOnlyMeshes.push(includedOnlyMesh);
  10896. }
  10897. }
  10898. light._includedOnlyMeshesIds = [];
  10899. }
  10900. if (!light.canAffectMesh(mesh)) {
  10901. continue;
  10902. }
  10903. defines.push("#define LIGHT" + lightIndex);
  10904. if (lightIndex > 0) {
  10905. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  10906. }
  10907. var type;
  10908. if (light instanceof BABYLON.SpotLight) {
  10909. type = "#define SPOTLIGHT" + lightIndex;
  10910. } else if (light instanceof BABYLON.HemisphericLight) {
  10911. type = "#define HEMILIGHT" + lightIndex;
  10912. } else {
  10913. type = "#define POINTDIRLIGHT" + lightIndex;
  10914. }
  10915. defines.push(type);
  10916. if (lightIndex > 0) {
  10917. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  10918. }
  10919. if (scene.shadowsEnabled) {
  10920. var shadowGenerator = light.getShadowGenerator();
  10921. if (mesh && mesh.receiveShadows && shadowGenerator) {
  10922. defines.push("#define SHADOW" + lightIndex);
  10923. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  10924. if (!shadowsActivated) {
  10925. defines.push("#define SHADOWS");
  10926. shadowsActivated = true;
  10927. }
  10928. if (shadowGenerator.useVarianceShadowMap) {
  10929. defines.push("#define SHADOWVSM" + lightIndex);
  10930. if (lightIndex > 0) {
  10931. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  10932. }
  10933. }
  10934. if (shadowGenerator.usePoissonSampling) {
  10935. defines.push("#define SHADOWPCF" + lightIndex);
  10936. if (lightIndex > 0) {
  10937. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  10938. }
  10939. }
  10940. }
  10941. }
  10942. lightIndex++;
  10943. if (lightIndex == maxSimultaneousLights)
  10944. break;
  10945. }
  10946. }
  10947. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10948. var fresnelRank = 1;
  10949. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  10950. defines.push("#define DIFFUSEFRESNEL");
  10951. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  10952. fresnelRank++;
  10953. }
  10954. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  10955. defines.push("#define OPACITYFRESNEL");
  10956. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  10957. fresnelRank++;
  10958. }
  10959. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  10960. defines.push("#define REFLECTIONFRESNEL");
  10961. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  10962. fresnelRank++;
  10963. }
  10964. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  10965. defines.push("#define EMISSIVEFRESNEL");
  10966. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  10967. fresnelRank++;
  10968. }
  10969. defines.push("#define FRESNEL");
  10970. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  10971. }
  10972. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  10973. if (mesh) {
  10974. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10975. attribs.push(BABYLON.VertexBuffer.UVKind);
  10976. defines.push("#define UV1");
  10977. }
  10978. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10979. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10980. defines.push("#define UV2");
  10981. }
  10982. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  10983. attribs.push(BABYLON.VertexBuffer.ColorKind);
  10984. defines.push("#define VERTEXCOLOR");
  10985. }
  10986. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  10987. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10988. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10989. defines.push("#define BONES");
  10990. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10991. defines.push("#define BONES4");
  10992. fallbacks.addFallback(0, "BONES4");
  10993. }
  10994. if (useInstances) {
  10995. defines.push("#define INSTANCES");
  10996. attribs.push("world0");
  10997. attribs.push("world1");
  10998. attribs.push("world2");
  10999. attribs.push("world3");
  11000. }
  11001. }
  11002. var join = defines.join("\n");
  11003. if (this._cachedDefines != join) {
  11004. this._cachedDefines = join;
  11005. var shaderName = "default";
  11006. if (!scene.getEngine().getCaps().standardDerivatives) {
  11007. shaderName = "legacydefault";
  11008. }
  11009. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  11010. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  11011. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  11012. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  11013. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  11014. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  11015. "vFogInfos", "vFogColor",
  11016. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  11017. "mBones",
  11018. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  11019. "darkness0", "darkness1", "darkness2", "darkness3",
  11020. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  11021. ], [
  11022. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  11023. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  11024. ], join, fallbacks, this.onCompiled, this.onError);
  11025. }
  11026. if (!this._effect.isReady()) {
  11027. return false;
  11028. }
  11029. this._renderId = scene.getRenderId();
  11030. this._wasPreviouslyReady = true;
  11031. return true;
  11032. };
  11033. StandardMaterial.prototype.unbind = function () {
  11034. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  11035. this._effect.setTexture("reflection2DSampler", null);
  11036. }
  11037. };
  11038. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  11039. this._effect.setMatrix("world", world);
  11040. };
  11041. StandardMaterial.prototype.bind = function (world, mesh) {
  11042. var scene = this.getScene();
  11043. this.bindOnlyWorldMatrix(world);
  11044. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  11045. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  11046. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  11047. }
  11048. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  11049. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  11050. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  11051. }
  11052. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  11053. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  11054. }
  11055. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  11056. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  11057. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  11058. }
  11059. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  11060. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  11061. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  11062. }
  11063. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  11064. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  11065. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  11066. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  11067. }
  11068. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  11069. this._effect.setTexture("ambientSampler", this.ambientTexture);
  11070. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  11071. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  11072. }
  11073. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  11074. this._effect.setTexture("opacitySampler", this.opacityTexture);
  11075. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  11076. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  11077. }
  11078. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  11079. if (this.reflectionTexture.isCube) {
  11080. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  11081. } else {
  11082. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  11083. }
  11084. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  11085. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  11086. }
  11087. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  11088. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  11089. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  11090. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  11091. }
  11092. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  11093. this._effect.setTexture("specularSampler", this.specularTexture);
  11094. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  11095. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  11096. }
  11097. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
  11098. this._effect.setTexture("bumpSampler", this.bumpTexture);
  11099. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
  11100. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  11101. }
  11102. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  11103. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  11104. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  11105. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  11106. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  11107. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  11108. if (scene.lightsEnabled) {
  11109. var lightIndex = 0;
  11110. for (var index = 0; index < scene.lights.length; index++) {
  11111. var light = scene.lights[index];
  11112. if (!light.isEnabled()) {
  11113. continue;
  11114. }
  11115. if (!light.canAffectMesh(mesh)) {
  11116. continue;
  11117. }
  11118. if (light instanceof BABYLON.PointLight) {
  11119. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  11120. } else if (light instanceof BABYLON.DirectionalLight) {
  11121. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  11122. } else if (light instanceof BABYLON.SpotLight) {
  11123. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  11124. } else if (light instanceof BABYLON.HemisphericLight) {
  11125. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  11126. }
  11127. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  11128. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  11129. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  11130. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  11131. if (scene.shadowsEnabled) {
  11132. var shadowGenerator = light.getShadowGenerator();
  11133. if (mesh.receiveShadows && shadowGenerator) {
  11134. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  11135. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  11136. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  11137. }
  11138. }
  11139. lightIndex++;
  11140. if (lightIndex == maxSimultaneousLights)
  11141. break;
  11142. }
  11143. }
  11144. if (scene.clipPlane) {
  11145. var clipPlane = scene.clipPlane;
  11146. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  11147. }
  11148. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  11149. this._effect.setMatrix("view", scene.getViewMatrix());
  11150. }
  11151. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11152. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  11153. this._effect.setColor3("vFogColor", scene.fogColor);
  11154. }
  11155. };
  11156. StandardMaterial.prototype.getAnimatables = function () {
  11157. var results = [];
  11158. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  11159. results.push(this.diffuseTexture);
  11160. }
  11161. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  11162. results.push(this.ambientTexture);
  11163. }
  11164. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  11165. results.push(this.opacityTexture);
  11166. }
  11167. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  11168. results.push(this.reflectionTexture);
  11169. }
  11170. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  11171. results.push(this.emissiveTexture);
  11172. }
  11173. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  11174. results.push(this.specularTexture);
  11175. }
  11176. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  11177. results.push(this.bumpTexture);
  11178. }
  11179. return results;
  11180. };
  11181. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  11182. if (this.diffuseTexture) {
  11183. this.diffuseTexture.dispose();
  11184. }
  11185. if (this.ambientTexture) {
  11186. this.ambientTexture.dispose();
  11187. }
  11188. if (this.opacityTexture) {
  11189. this.opacityTexture.dispose();
  11190. }
  11191. if (this.reflectionTexture) {
  11192. this.reflectionTexture.dispose();
  11193. }
  11194. if (this.emissiveTexture) {
  11195. this.emissiveTexture.dispose();
  11196. }
  11197. if (this.specularTexture) {
  11198. this.specularTexture.dispose();
  11199. }
  11200. if (this.bumpTexture) {
  11201. this.bumpTexture.dispose();
  11202. }
  11203. _super.prototype.dispose.call(this, forceDisposeEffect);
  11204. };
  11205. StandardMaterial.prototype.clone = function (name) {
  11206. var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
  11207. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  11208. newStandardMaterial.alpha = this.alpha;
  11209. newStandardMaterial.wireframe = this.wireframe;
  11210. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  11211. if (this.diffuseTexture && this.diffuseTexture.clone) {
  11212. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  11213. }
  11214. if (this.ambientTexture && this.ambientTexture.clone) {
  11215. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  11216. }
  11217. if (this.opacityTexture && this.opacityTexture.clone) {
  11218. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  11219. }
  11220. if (this.reflectionTexture && this.reflectionTexture.clone) {
  11221. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  11222. }
  11223. if (this.emissiveTexture && this.emissiveTexture.clone) {
  11224. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  11225. }
  11226. if (this.specularTexture && this.specularTexture.clone) {
  11227. newStandardMaterial.specularTexture = this.specularTexture.clone();
  11228. }
  11229. if (this.bumpTexture && this.bumpTexture.clone) {
  11230. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  11231. }
  11232. newStandardMaterial.ambientColor = this.ambientColor.clone();
  11233. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  11234. newStandardMaterial.specularColor = this.specularColor.clone();
  11235. newStandardMaterial.specularPower = this.specularPower;
  11236. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  11237. return newStandardMaterial;
  11238. };
  11239. StandardMaterial.DiffuseTextureEnabled = true;
  11240. StandardMaterial.AmbientTextureEnabled = true;
  11241. StandardMaterial.OpacityTextureEnabled = true;
  11242. StandardMaterial.ReflectionTextureEnabled = true;
  11243. StandardMaterial.EmissiveTextureEnabled = true;
  11244. StandardMaterial.SpecularTextureEnabled = true;
  11245. StandardMaterial.BumpTextureEnabled = true;
  11246. return StandardMaterial;
  11247. })(BABYLON.Material);
  11248. BABYLON.StandardMaterial = StandardMaterial;
  11249. })(BABYLON || (BABYLON = {}));
  11250. var __extends = this.__extends || function (d, b) {
  11251. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11252. function __() { this.constructor = d; }
  11253. __.prototype = b.prototype;
  11254. d.prototype = new __();
  11255. };
  11256. var BABYLON;
  11257. (function (BABYLON) {
  11258. var MultiMaterial = (function (_super) {
  11259. __extends(MultiMaterial, _super);
  11260. function MultiMaterial(name, scene) {
  11261. _super.call(this, name, scene, true);
  11262. this.subMaterials = new Array();
  11263. scene.multiMaterials.push(this);
  11264. }
  11265. MultiMaterial.prototype.getSubMaterial = function (index) {
  11266. if (index < 0 || index >= this.subMaterials.length) {
  11267. return this.getScene().defaultMaterial;
  11268. }
  11269. return this.subMaterials[index];
  11270. };
  11271. MultiMaterial.prototype.isReady = function (mesh) {
  11272. for (var index = 0; index < this.subMaterials.length; index++) {
  11273. var subMaterial = this.subMaterials[index];
  11274. if (subMaterial) {
  11275. if (!this.subMaterials[index].isReady(mesh)) {
  11276. return false;
  11277. }
  11278. }
  11279. }
  11280. return true;
  11281. };
  11282. return MultiMaterial;
  11283. })(BABYLON.Material);
  11284. BABYLON.MultiMaterial = MultiMaterial;
  11285. })(BABYLON || (BABYLON = {}));
  11286. var BABYLON;
  11287. (function (BABYLON) {
  11288. var Database = (function () {
  11289. function Database(urlToScene, callbackManifestChecked) {
  11290. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  11291. this.callbackManifestChecked = callbackManifestChecked;
  11292. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  11293. this.db = null;
  11294. this.enableSceneOffline = false;
  11295. this.enableTexturesOffline = false;
  11296. this.manifestVersionFound = 0;
  11297. this.mustUpdateRessources = false;
  11298. this.hasReachedQuota = false;
  11299. this.checkManifestFile();
  11300. }
  11301. Database.prototype.checkManifestFile = function () {
  11302. var _this = this;
  11303. function noManifestFile() {
  11304. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  11305. that.enableSceneOffline = false;
  11306. that.enableTexturesOffline = false;
  11307. that.callbackManifestChecked(false);
  11308. }
  11309. var that = this;
  11310. var manifestURL = this.currentSceneUrl + ".manifest";
  11311. var xhr = new XMLHttpRequest();
  11312. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  11313. xhr.open("GET", manifestURLTimeStamped, true);
  11314. xhr.addEventListener("load", function () {
  11315. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  11316. try {
  11317. var manifestFile = JSON.parse(xhr.response);
  11318. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  11319. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  11320. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  11321. _this.manifestVersionFound = manifestFile.version;
  11322. }
  11323. if (_this.callbackManifestChecked) {
  11324. _this.callbackManifestChecked(true);
  11325. }
  11326. } catch (ex) {
  11327. noManifestFile();
  11328. }
  11329. } else {
  11330. noManifestFile();
  11331. }
  11332. }, false);
  11333. xhr.addEventListener("error", function (event) {
  11334. noManifestFile();
  11335. }, false);
  11336. try {
  11337. xhr.send();
  11338. } catch (ex) {
  11339. BABYLON.Tools.Error("Error on XHR send request.");
  11340. that.callbackManifestChecked(false);
  11341. }
  11342. };
  11343. Database.prototype.openAsync = function (successCallback, errorCallback) {
  11344. var _this = this;
  11345. function handleError() {
  11346. that.isSupported = false;
  11347. if (errorCallback)
  11348. errorCallback();
  11349. }
  11350. var that = this;
  11351. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  11352. this.isSupported = false;
  11353. if (errorCallback)
  11354. errorCallback();
  11355. } else {
  11356. if (!this.db) {
  11357. this.hasReachedQuota = false;
  11358. this.isSupported = true;
  11359. var request = this.idbFactory.open("babylonjs", 1);
  11360. request.onerror = function (event) {
  11361. handleError();
  11362. };
  11363. request.onblocked = function (event) {
  11364. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  11365. handleError();
  11366. };
  11367. request.onsuccess = function (event) {
  11368. _this.db = request.result;
  11369. successCallback();
  11370. };
  11371. request.onupgradeneeded = function (event) {
  11372. _this.db = (event.target).result;
  11373. try {
  11374. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  11375. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  11376. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  11377. } catch (ex) {
  11378. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  11379. handleError();
  11380. }
  11381. };
  11382. } else {
  11383. if (successCallback)
  11384. successCallback();
  11385. }
  11386. }
  11387. };
  11388. Database.prototype.loadImageFromDB = function (url, image) {
  11389. var _this = this;
  11390. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  11391. var saveAndLoadImage = function () {
  11392. if (!_this.hasReachedQuota && _this.db !== null) {
  11393. _this._saveImageIntoDBAsync(completeURL, image);
  11394. } else {
  11395. image.src = url;
  11396. }
  11397. };
  11398. if (!this.mustUpdateRessources) {
  11399. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  11400. } else {
  11401. saveAndLoadImage();
  11402. }
  11403. };
  11404. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  11405. if (this.isSupported && this.db !== null) {
  11406. var texture;
  11407. var transaction = this.db.transaction(["textures"]);
  11408. transaction.onabort = function (event) {
  11409. image.src = url;
  11410. };
  11411. transaction.oncomplete = function (event) {
  11412. var blobTextureURL;
  11413. if (texture) {
  11414. var URL = window.URL || window.webkitURL;
  11415. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  11416. image.onerror = function () {
  11417. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  11418. image.src = url;
  11419. };
  11420. image.src = blobTextureURL;
  11421. } else {
  11422. notInDBCallback();
  11423. }
  11424. };
  11425. var getRequest = transaction.objectStore("textures").get(url);
  11426. getRequest.onsuccess = function (event) {
  11427. texture = (event.target).result;
  11428. };
  11429. getRequest.onerror = function (event) {
  11430. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  11431. image.src = url;
  11432. };
  11433. } else {
  11434. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11435. image.src = url;
  11436. }
  11437. };
  11438. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  11439. var _this = this;
  11440. if (this.isSupported) {
  11441. var generateBlobUrl = function () {
  11442. var blobTextureURL;
  11443. if (blob) {
  11444. var URL = window.URL || window.webkitURL;
  11445. try {
  11446. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  11447. } catch (ex) {
  11448. blobTextureURL = URL.createObjectURL(blob);
  11449. }
  11450. }
  11451. image.src = blobTextureURL;
  11452. };
  11453. if (BABYLON.Database.isUASupportingBlobStorage) {
  11454. var xhr = new XMLHttpRequest(), blob;
  11455. xhr.open("GET", url, true);
  11456. xhr.responseType = "blob";
  11457. xhr.addEventListener("load", function () {
  11458. if (xhr.status === 200) {
  11459. blob = xhr.response;
  11460. var transaction = _this.db.transaction(["textures"], "readwrite");
  11461. transaction.onabort = function (event) {
  11462. try {
  11463. if (event.srcElement.error.name === "QuotaExceededError") {
  11464. this.hasReachedQuota = true;
  11465. }
  11466. } catch (ex) {
  11467. }
  11468. generateBlobUrl();
  11469. };
  11470. transaction.oncomplete = function (event) {
  11471. generateBlobUrl();
  11472. };
  11473. var newTexture = { textureUrl: url, data: blob };
  11474. try {
  11475. var addRequest = transaction.objectStore("textures").put(newTexture);
  11476. addRequest.onsuccess = function (event) {
  11477. };
  11478. addRequest.onerror = function (event) {
  11479. generateBlobUrl();
  11480. };
  11481. } catch (ex) {
  11482. if (ex.code === 25) {
  11483. BABYLON.Database.isUASupportingBlobStorage = false;
  11484. }
  11485. image.src = url;
  11486. }
  11487. } else {
  11488. image.src = url;
  11489. }
  11490. }, false);
  11491. xhr.addEventListener("error", function (event) {
  11492. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  11493. image.src = url;
  11494. }, false);
  11495. xhr.send();
  11496. } else {
  11497. image.src = url;
  11498. }
  11499. } else {
  11500. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11501. image.src = url;
  11502. }
  11503. };
  11504. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  11505. var _this = this;
  11506. var updateVersion = function (event) {
  11507. _this._saveVersionIntoDBAsync(url, versionLoaded);
  11508. };
  11509. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  11510. };
  11511. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  11512. var _this = this;
  11513. if (this.isSupported) {
  11514. var version;
  11515. try {
  11516. var transaction = this.db.transaction(["versions"]);
  11517. transaction.oncomplete = function (event) {
  11518. if (version) {
  11519. if (_this.manifestVersionFound > version.data) {
  11520. _this.mustUpdateRessources = true;
  11521. updateInDBCallback();
  11522. } else {
  11523. callback(version.data);
  11524. }
  11525. } else {
  11526. _this.mustUpdateRessources = true;
  11527. updateInDBCallback();
  11528. }
  11529. };
  11530. transaction.onabort = function (event) {
  11531. callback(-1);
  11532. };
  11533. var getRequest = transaction.objectStore("versions").get(url);
  11534. getRequest.onsuccess = function (event) {
  11535. version = (event.target).result;
  11536. };
  11537. getRequest.onerror = function (event) {
  11538. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  11539. callback(-1);
  11540. };
  11541. } catch (ex) {
  11542. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  11543. callback(-1);
  11544. }
  11545. } else {
  11546. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11547. callback(-1);
  11548. }
  11549. };
  11550. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  11551. var _this = this;
  11552. if (this.isSupported && !this.hasReachedQuota) {
  11553. try {
  11554. var transaction = this.db.transaction(["versions"], "readwrite");
  11555. transaction.onabort = function (event) {
  11556. try {
  11557. if (event.srcElement.error.name === "QuotaExceededError") {
  11558. _this.hasReachedQuota = true;
  11559. }
  11560. } catch (ex) {
  11561. }
  11562. callback(-1);
  11563. };
  11564. transaction.oncomplete = function (event) {
  11565. callback(_this.manifestVersionFound);
  11566. };
  11567. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  11568. var addRequest = transaction.objectStore("versions").put(newVersion);
  11569. addRequest.onsuccess = function (event) {
  11570. };
  11571. addRequest.onerror = function (event) {
  11572. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  11573. };
  11574. } catch (ex) {
  11575. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  11576. callback(-1);
  11577. }
  11578. } else {
  11579. callback(-1);
  11580. }
  11581. };
  11582. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  11583. var _this = this;
  11584. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  11585. var saveAndLoadFile = function (event) {
  11586. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  11587. };
  11588. this._checkVersionFromDB(completeUrl, function (version) {
  11589. if (version !== -1) {
  11590. if (!_this.mustUpdateRessources) {
  11591. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  11592. } else {
  11593. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  11594. }
  11595. } else {
  11596. errorCallback();
  11597. }
  11598. });
  11599. };
  11600. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  11601. if (this.isSupported) {
  11602. var targetStore;
  11603. if (url.indexOf(".babylon") !== -1) {
  11604. targetStore = "scenes";
  11605. } else {
  11606. targetStore = "textures";
  11607. }
  11608. var file;
  11609. var transaction = this.db.transaction([targetStore]);
  11610. transaction.oncomplete = function (event) {
  11611. if (file) {
  11612. callback(file.data);
  11613. } else {
  11614. notInDBCallback();
  11615. }
  11616. };
  11617. transaction.onabort = function (event) {
  11618. notInDBCallback();
  11619. };
  11620. var getRequest = transaction.objectStore(targetStore).get(url);
  11621. getRequest.onsuccess = function (event) {
  11622. file = (event.target).result;
  11623. };
  11624. getRequest.onerror = function (event) {
  11625. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  11626. notInDBCallback();
  11627. };
  11628. } else {
  11629. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11630. callback();
  11631. }
  11632. };
  11633. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  11634. var _this = this;
  11635. if (this.isSupported) {
  11636. var targetStore;
  11637. if (url.indexOf(".babylon") !== -1) {
  11638. targetStore = "scenes";
  11639. } else {
  11640. targetStore = "textures";
  11641. }
  11642. var xhr = new XMLHttpRequest(), fileData;
  11643. xhr.open("GET", url, true);
  11644. if (useArrayBuffer) {
  11645. xhr.responseType = "arraybuffer";
  11646. }
  11647. xhr.onprogress = progressCallback;
  11648. xhr.addEventListener("load", function () {
  11649. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  11650. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  11651. if (!_this.hasReachedQuota) {
  11652. var transaction = _this.db.transaction([targetStore], "readwrite");
  11653. transaction.onabort = function (event) {
  11654. try {
  11655. if (event.srcElement.error.name === "QuotaExceededError") {
  11656. this.hasReachedQuota = true;
  11657. }
  11658. } catch (ex) {
  11659. }
  11660. callback(fileData);
  11661. };
  11662. transaction.oncomplete = function (event) {
  11663. callback(fileData);
  11664. };
  11665. var newFile;
  11666. if (targetStore === "scenes") {
  11667. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  11668. } else {
  11669. newFile = { textureUrl: url, data: fileData };
  11670. }
  11671. try {
  11672. var addRequest = transaction.objectStore(targetStore).put(newFile);
  11673. addRequest.onsuccess = function (event) {
  11674. };
  11675. addRequest.onerror = function (event) {
  11676. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  11677. };
  11678. } catch (ex) {
  11679. callback(fileData);
  11680. }
  11681. } else {
  11682. callback(fileData);
  11683. }
  11684. } else {
  11685. callback();
  11686. }
  11687. }, false);
  11688. xhr.addEventListener("error", function (event) {
  11689. BABYLON.Tools.Error("error on XHR request.");
  11690. callback();
  11691. }, false);
  11692. xhr.send();
  11693. } else {
  11694. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11695. callback();
  11696. }
  11697. };
  11698. Database.isUASupportingBlobStorage = true;
  11699. Database.parseURL = function (url) {
  11700. var a = document.createElement('a');
  11701. a.href = url;
  11702. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  11703. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  11704. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  11705. return absLocation;
  11706. };
  11707. Database.ReturnFullUrlLocation = function (url) {
  11708. if (url.indexOf("http:/") === -1) {
  11709. return (BABYLON.Database.parseURL(window.location.href) + url);
  11710. } else {
  11711. return url;
  11712. }
  11713. };
  11714. return Database;
  11715. })();
  11716. BABYLON.Database = Database;
  11717. })(BABYLON || (BABYLON = {}));
  11718. var BABYLON;
  11719. (function (BABYLON) {
  11720. var SpriteManager = (function () {
  11721. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  11722. this.name = name;
  11723. this.cellSize = cellSize;
  11724. this.sprites = new Array();
  11725. this.renderingGroupId = 0;
  11726. this.fogEnabled = true;
  11727. this._vertexDeclaration = [3, 4, 4, 4];
  11728. this._vertexStrideSize = 15 * 4;
  11729. this._capacity = capacity;
  11730. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  11731. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11732. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11733. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  11734. this._scene = scene;
  11735. this._scene.spriteManagers.push(this);
  11736. this._vertexDeclaration = [3, 4, 4, 4];
  11737. this._vertexStrideSize = 15 * 4;
  11738. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  11739. var indices = [];
  11740. var index = 0;
  11741. for (var count = 0; count < capacity; count++) {
  11742. indices.push(index);
  11743. indices.push(index + 1);
  11744. indices.push(index + 2);
  11745. indices.push(index);
  11746. indices.push(index + 2);
  11747. indices.push(index + 3);
  11748. index += 4;
  11749. }
  11750. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11751. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  11752. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  11753. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  11754. }
  11755. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  11756. var arrayOffset = index * 15;
  11757. if (offsetX == 0)
  11758. offsetX = this._epsilon;
  11759. else if (offsetX == 1)
  11760. offsetX = 1 - this._epsilon;
  11761. if (offsetY == 0)
  11762. offsetY = this._epsilon;
  11763. else if (offsetY == 1)
  11764. offsetY = 1 - this._epsilon;
  11765. this._vertices[arrayOffset] = sprite.position.x;
  11766. this._vertices[arrayOffset + 1] = sprite.position.y;
  11767. this._vertices[arrayOffset + 2] = sprite.position.z;
  11768. this._vertices[arrayOffset + 3] = sprite.angle;
  11769. this._vertices[arrayOffset + 4] = sprite.size;
  11770. this._vertices[arrayOffset + 5] = offsetX;
  11771. this._vertices[arrayOffset + 6] = offsetY;
  11772. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  11773. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  11774. var offset = (sprite.cellIndex / rowSize) >> 0;
  11775. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  11776. this._vertices[arrayOffset + 10] = offset;
  11777. this._vertices[arrayOffset + 11] = sprite.color.r;
  11778. this._vertices[arrayOffset + 12] = sprite.color.g;
  11779. this._vertices[arrayOffset + 13] = sprite.color.b;
  11780. this._vertices[arrayOffset + 14] = sprite.color.a;
  11781. };
  11782. SpriteManager.prototype.render = function () {
  11783. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  11784. return;
  11785. var engine = this._scene.getEngine();
  11786. var baseSize = this._spriteTexture.getBaseSize();
  11787. var deltaTime = BABYLON.Tools.GetDeltaTime();
  11788. var max = Math.min(this._capacity, this.sprites.length);
  11789. var rowSize = baseSize.width / this.cellSize;
  11790. var offset = 0;
  11791. for (var index = 0; index < max; index++) {
  11792. var sprite = this.sprites[index];
  11793. if (!sprite) {
  11794. continue;
  11795. }
  11796. sprite._animate(deltaTime);
  11797. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  11798. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  11799. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  11800. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  11801. }
  11802. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
  11803. var effect = this._effectBase;
  11804. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  11805. effect = this._effectFog;
  11806. }
  11807. engine.enableEffect(effect);
  11808. var viewMatrix = this._scene.getViewMatrix();
  11809. effect.setTexture("diffuseSampler", this._spriteTexture);
  11810. effect.setMatrix("view", viewMatrix);
  11811. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  11812. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  11813. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  11814. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  11815. effect.setColor3("vFogColor", this._scene.fogColor);
  11816. }
  11817. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  11818. effect.setBool("alphaTest", true);
  11819. engine.setColorWrite(false);
  11820. engine.draw(true, 0, max * 6);
  11821. engine.setColorWrite(true);
  11822. effect.setBool("alphaTest", false);
  11823. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11824. engine.draw(true, 0, max * 6);
  11825. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11826. };
  11827. SpriteManager.prototype.dispose = function () {
  11828. if (this._vertexBuffer) {
  11829. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11830. this._vertexBuffer = null;
  11831. }
  11832. if (this._indexBuffer) {
  11833. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11834. this._indexBuffer = null;
  11835. }
  11836. if (this._spriteTexture) {
  11837. this._spriteTexture.dispose();
  11838. this._spriteTexture = null;
  11839. }
  11840. var index = this._scene.spriteManagers.indexOf(this);
  11841. this._scene.spriteManagers.splice(index, 1);
  11842. if (this.onDispose) {
  11843. this.onDispose();
  11844. }
  11845. };
  11846. return SpriteManager;
  11847. })();
  11848. BABYLON.SpriteManager = SpriteManager;
  11849. })(BABYLON || (BABYLON = {}));
  11850. var BABYLON;
  11851. (function (BABYLON) {
  11852. var Sprite = (function () {
  11853. function Sprite(name, manager) {
  11854. this.name = name;
  11855. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  11856. this.size = 1.0;
  11857. this.angle = 0;
  11858. this.cellIndex = 0;
  11859. this.invertU = 0;
  11860. this.invertV = 0;
  11861. this.animations = new Array();
  11862. this._animationStarted = false;
  11863. this._loopAnimation = false;
  11864. this._fromIndex = 0;
  11865. this._toIndex = 0;
  11866. this._delay = 0;
  11867. this._direction = 1;
  11868. this._frameCount = 0;
  11869. this._time = 0;
  11870. this._manager = manager;
  11871. this._manager.sprites.push(this);
  11872. this.position = BABYLON.Vector3.Zero();
  11873. }
  11874. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  11875. this._fromIndex = from;
  11876. this._toIndex = to;
  11877. this._loopAnimation = loop;
  11878. this._delay = delay;
  11879. this._animationStarted = true;
  11880. this._direction = from < to ? 1 : -1;
  11881. this.cellIndex = from;
  11882. this._time = 0;
  11883. };
  11884. Sprite.prototype.stopAnimation = function () {
  11885. this._animationStarted = false;
  11886. };
  11887. Sprite.prototype._animate = function (deltaTime) {
  11888. if (!this._animationStarted)
  11889. return;
  11890. this._time += deltaTime;
  11891. if (this._time > this._delay) {
  11892. this._time = this._time % this._delay;
  11893. this.cellIndex += this._direction;
  11894. if (this.cellIndex == this._toIndex) {
  11895. if (this._loopAnimation) {
  11896. this.cellIndex = this._fromIndex;
  11897. } else {
  11898. this._animationStarted = false;
  11899. if (this.disposeWhenFinishedAnimating) {
  11900. this.dispose();
  11901. }
  11902. }
  11903. }
  11904. }
  11905. };
  11906. Sprite.prototype.dispose = function () {
  11907. for (var i = 0; i < this._manager.sprites.length; i++) {
  11908. if (this._manager.sprites[i] == this) {
  11909. this._manager.sprites.splice(i, 1);
  11910. }
  11911. }
  11912. };
  11913. return Sprite;
  11914. })();
  11915. BABYLON.Sprite = Sprite;
  11916. })(BABYLON || (BABYLON = {}));
  11917. var BABYLON;
  11918. (function (BABYLON) {
  11919. var Layer = (function () {
  11920. function Layer(name, imgUrl, scene, isBackground, color) {
  11921. this.name = name;
  11922. this._vertexDeclaration = [2];
  11923. this._vertexStrideSize = 2 * 4;
  11924. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  11925. this.isBackground = isBackground === undefined ? true : isBackground;
  11926. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  11927. this._scene = scene;
  11928. this._scene.layers.push(this);
  11929. var vertices = [];
  11930. vertices.push(1, 1);
  11931. vertices.push(-1, 1);
  11932. vertices.push(-1, -1);
  11933. vertices.push(1, -1);
  11934. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11935. var indices = [];
  11936. indices.push(0);
  11937. indices.push(1);
  11938. indices.push(2);
  11939. indices.push(0);
  11940. indices.push(2);
  11941. indices.push(3);
  11942. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11943. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  11944. }
  11945. Layer.prototype.render = function () {
  11946. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  11947. return;
  11948. var engine = this._scene.getEngine();
  11949. engine.enableEffect(this._effect);
  11950. engine.setState(false);
  11951. this._effect.setTexture("textureSampler", this.texture);
  11952. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  11953. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  11954. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11955. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11956. engine.draw(true, 0, 6);
  11957. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11958. };
  11959. Layer.prototype.dispose = function () {
  11960. if (this._vertexBuffer) {
  11961. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  11962. this._vertexBuffer = null;
  11963. }
  11964. if (this._indexBuffer) {
  11965. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  11966. this._indexBuffer = null;
  11967. }
  11968. if (this.texture) {
  11969. this.texture.dispose();
  11970. this.texture = null;
  11971. }
  11972. var index = this._scene.layers.indexOf(this);
  11973. this._scene.layers.splice(index, 1);
  11974. if (this.onDispose) {
  11975. this.onDispose();
  11976. }
  11977. };
  11978. return Layer;
  11979. })();
  11980. BABYLON.Layer = Layer;
  11981. })(BABYLON || (BABYLON = {}));
  11982. var BABYLON;
  11983. (function (BABYLON) {
  11984. var Particle = (function () {
  11985. function Particle() {
  11986. this.position = BABYLON.Vector3.Zero();
  11987. this.direction = BABYLON.Vector3.Zero();
  11988. this.color = new BABYLON.Color4(0, 0, 0, 0);
  11989. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  11990. this.lifeTime = 1.0;
  11991. this.age = 0;
  11992. this.size = 0;
  11993. this.angle = 0;
  11994. this.angularSpeed = 0;
  11995. }
  11996. return Particle;
  11997. })();
  11998. BABYLON.Particle = Particle;
  11999. })(BABYLON || (BABYLON = {}));
  12000. var BABYLON;
  12001. (function (BABYLON) {
  12002. var randomNumber = function (min, max) {
  12003. if (min == max) {
  12004. return (min);
  12005. }
  12006. var random = Math.random();
  12007. return ((random * (max - min)) + min);
  12008. };
  12009. var ParticleSystem = (function () {
  12010. function ParticleSystem(name, capacity, scene, customEffect) {
  12011. var _this = this;
  12012. this.name = name;
  12013. this.renderingGroupId = 0;
  12014. this.emitter = null;
  12015. this.emitRate = 10;
  12016. this.manualEmitCount = -1;
  12017. this.updateSpeed = 0.01;
  12018. this.targetStopDuration = 0;
  12019. this.disposeOnStop = false;
  12020. this.minEmitPower = 1;
  12021. this.maxEmitPower = 1;
  12022. this.minLifeTime = 1;
  12023. this.maxLifeTime = 1;
  12024. this.minSize = 1;
  12025. this.maxSize = 1;
  12026. this.minAngularSpeed = 0;
  12027. this.maxAngularSpeed = 0;
  12028. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  12029. this.forceDepthWrite = false;
  12030. this.gravity = BABYLON.Vector3.Zero();
  12031. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  12032. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  12033. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  12034. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  12035. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12036. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12037. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  12038. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12039. this.particles = new Array();
  12040. this._vertexDeclaration = [3, 4, 4];
  12041. this._vertexStrideSize = 11 * 4;
  12042. this._stockParticles = new Array();
  12043. this._newPartsExcess = 0;
  12044. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  12045. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  12046. this._scaledDirection = BABYLON.Vector3.Zero();
  12047. this._scaledGravity = BABYLON.Vector3.Zero();
  12048. this._currentRenderId = -1;
  12049. this._started = false;
  12050. this._stopped = false;
  12051. this._actualFrame = 0;
  12052. this.id = name;
  12053. this._capacity = capacity;
  12054. this._scene = scene;
  12055. this._customEffect = customEffect;
  12056. scene.particleSystems.push(this);
  12057. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  12058. var indices = [];
  12059. var index = 0;
  12060. for (var count = 0; count < capacity; count++) {
  12061. indices.push(index);
  12062. indices.push(index + 1);
  12063. indices.push(index + 2);
  12064. indices.push(index);
  12065. indices.push(index + 2);
  12066. indices.push(index + 3);
  12067. index += 4;
  12068. }
  12069. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12070. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  12071. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  12072. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  12073. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  12074. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  12075. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  12076. };
  12077. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  12078. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  12079. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  12080. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  12081. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  12082. };
  12083. }
  12084. ParticleSystem.prototype.getCapacity = function () {
  12085. return this._capacity;
  12086. };
  12087. ParticleSystem.prototype.isAlive = function () {
  12088. return this._alive;
  12089. };
  12090. ParticleSystem.prototype.isStarted = function () {
  12091. return this._started;
  12092. };
  12093. ParticleSystem.prototype.start = function () {
  12094. this._started = true;
  12095. this._stopped = false;
  12096. this._actualFrame = 0;
  12097. };
  12098. ParticleSystem.prototype.stop = function () {
  12099. this._stopped = true;
  12100. };
  12101. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  12102. var offset = index * 11;
  12103. this._vertices[offset] = particle.position.x;
  12104. this._vertices[offset + 1] = particle.position.y;
  12105. this._vertices[offset + 2] = particle.position.z;
  12106. this._vertices[offset + 3] = particle.color.r;
  12107. this._vertices[offset + 4] = particle.color.g;
  12108. this._vertices[offset + 5] = particle.color.b;
  12109. this._vertices[offset + 6] = particle.color.a;
  12110. this._vertices[offset + 7] = particle.angle;
  12111. this._vertices[offset + 8] = particle.size;
  12112. this._vertices[offset + 9] = offsetX;
  12113. this._vertices[offset + 10] = offsetY;
  12114. };
  12115. ParticleSystem.prototype._update = function (newParticles) {
  12116. this._alive = this.particles.length > 0;
  12117. for (var index = 0; index < this.particles.length; index++) {
  12118. var particle = this.particles[index];
  12119. particle.age += this._scaledUpdateSpeed;
  12120. if (particle.age >= particle.lifeTime) {
  12121. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  12122. index--;
  12123. continue;
  12124. } else {
  12125. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  12126. particle.color.addInPlace(this._scaledColorStep);
  12127. if (particle.color.a < 0)
  12128. particle.color.a = 0;
  12129. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  12130. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  12131. particle.position.addInPlace(this._scaledDirection);
  12132. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  12133. particle.direction.addInPlace(this._scaledGravity);
  12134. }
  12135. }
  12136. var worldMatrix;
  12137. if (this.emitter.position) {
  12138. worldMatrix = this.emitter.getWorldMatrix();
  12139. } else {
  12140. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  12141. }
  12142. for (index = 0; index < newParticles; index++) {
  12143. if (this.particles.length == this._capacity) {
  12144. break;
  12145. }
  12146. if (this._stockParticles.length !== 0) {
  12147. particle = this._stockParticles.pop();
  12148. particle.age = 0;
  12149. } else {
  12150. particle = new BABYLON.Particle();
  12151. }
  12152. this.particles.push(particle);
  12153. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  12154. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  12155. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  12156. particle.size = randomNumber(this.minSize, this.maxSize);
  12157. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  12158. this.startPositionFunction(worldMatrix, particle.position);
  12159. var step = randomNumber(0, 1.0);
  12160. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  12161. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  12162. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  12163. }
  12164. };
  12165. ParticleSystem.prototype._getEffect = function () {
  12166. if (this._customEffect) {
  12167. return this._customEffect;
  12168. }
  12169. ;
  12170. var defines = [];
  12171. if (this._scene.clipPlane) {
  12172. defines.push("#define CLIPPLANE");
  12173. }
  12174. var join = defines.join("\n");
  12175. if (this._cachedDefines != join) {
  12176. this._cachedDefines = join;
  12177. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  12178. }
  12179. return this._effect;
  12180. };
  12181. ParticleSystem.prototype.animate = function () {
  12182. if (!this._started)
  12183. return;
  12184. var effect = this._getEffect();
  12185. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  12186. return;
  12187. if (this._currentRenderId === this._scene.getRenderId()) {
  12188. return;
  12189. }
  12190. this._currentRenderId = this._scene.getRenderId();
  12191. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  12192. var emitCout;
  12193. if (this.manualEmitCount > -1) {
  12194. emitCout = this.manualEmitCount;
  12195. this.manualEmitCount = 0;
  12196. } else {
  12197. emitCout = this.emitRate;
  12198. }
  12199. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  12200. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  12201. if (this._newPartsExcess > 1.0) {
  12202. newParticles += this._newPartsExcess >> 0;
  12203. this._newPartsExcess -= this._newPartsExcess >> 0;
  12204. }
  12205. this._alive = false;
  12206. if (!this._stopped) {
  12207. this._actualFrame += this._scaledUpdateSpeed;
  12208. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  12209. this.stop();
  12210. } else {
  12211. newParticles = 0;
  12212. }
  12213. this._update(newParticles);
  12214. if (this._stopped) {
  12215. if (!this._alive) {
  12216. this._started = false;
  12217. if (this.disposeOnStop) {
  12218. this._scene._toBeDisposed.push(this);
  12219. }
  12220. }
  12221. }
  12222. var offset = 0;
  12223. for (var index = 0; index < this.particles.length; index++) {
  12224. var particle = this.particles[index];
  12225. this._appendParticleVertex(offset++, particle, 0, 0);
  12226. this._appendParticleVertex(offset++, particle, 1, 0);
  12227. this._appendParticleVertex(offset++, particle, 1, 1);
  12228. this._appendParticleVertex(offset++, particle, 0, 1);
  12229. }
  12230. var engine = this._scene.getEngine();
  12231. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  12232. };
  12233. ParticleSystem.prototype.render = function () {
  12234. var effect = this._getEffect();
  12235. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  12236. return 0;
  12237. var engine = this._scene.getEngine();
  12238. engine.enableEffect(effect);
  12239. var viewMatrix = this._scene.getViewMatrix();
  12240. effect.setTexture("diffuseSampler", this.particleTexture);
  12241. effect.setMatrix("view", viewMatrix);
  12242. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  12243. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  12244. if (this._scene.clipPlane) {
  12245. var clipPlane = this._scene.clipPlane;
  12246. var invView = viewMatrix.clone();
  12247. invView.invert();
  12248. effect.setMatrix("invView", invView);
  12249. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  12250. }
  12251. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12252. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  12253. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  12254. } else {
  12255. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12256. }
  12257. if (this.forceDepthWrite) {
  12258. engine.setDepthWrite(true);
  12259. }
  12260. engine.draw(true, 0, this.particles.length * 6);
  12261. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12262. return this.particles.length;
  12263. };
  12264. ParticleSystem.prototype.dispose = function () {
  12265. if (this._vertexBuffer) {
  12266. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12267. this._vertexBuffer = null;
  12268. }
  12269. if (this._indexBuffer) {
  12270. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12271. this._indexBuffer = null;
  12272. }
  12273. if (this.particleTexture) {
  12274. this.particleTexture.dispose();
  12275. this.particleTexture = null;
  12276. }
  12277. var index = this._scene.particleSystems.indexOf(this);
  12278. this._scene.particleSystems.splice(index, 1);
  12279. if (this.onDispose) {
  12280. this.onDispose();
  12281. }
  12282. };
  12283. ParticleSystem.prototype.clone = function (name, newEmitter) {
  12284. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  12285. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  12286. if (newEmitter === undefined) {
  12287. newEmitter = this.emitter;
  12288. }
  12289. result.emitter = newEmitter;
  12290. if (this.particleTexture) {
  12291. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  12292. }
  12293. result.start();
  12294. return result;
  12295. };
  12296. ParticleSystem.BLENDMODE_ONEONE = 0;
  12297. ParticleSystem.BLENDMODE_STANDARD = 1;
  12298. return ParticleSystem;
  12299. })();
  12300. BABYLON.ParticleSystem = ParticleSystem;
  12301. })(BABYLON || (BABYLON = {}));
  12302. var BABYLON;
  12303. (function (BABYLON) {
  12304. var Animation = (function () {
  12305. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  12306. this.name = name;
  12307. this.targetProperty = targetProperty;
  12308. this.framePerSecond = framePerSecond;
  12309. this.dataType = dataType;
  12310. this.loopMode = loopMode;
  12311. this._offsetsCache = {};
  12312. this._highLimitsCache = {};
  12313. this._stopped = false;
  12314. this.targetPropertyPath = targetProperty.split(".");
  12315. this.dataType = dataType;
  12316. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  12317. }
  12318. Animation.prototype.isStopped = function () {
  12319. return this._stopped;
  12320. };
  12321. Animation.prototype.getKeys = function () {
  12322. return this._keys;
  12323. };
  12324. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  12325. return startValue + (endValue - startValue) * gradient;
  12326. };
  12327. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  12328. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  12329. };
  12330. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  12331. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  12332. };
  12333. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  12334. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  12335. };
  12336. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  12337. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  12338. };
  12339. Animation.prototype.clone = function () {
  12340. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  12341. clone.setKeys(this._keys);
  12342. return clone;
  12343. };
  12344. Animation.prototype.setKeys = function (values) {
  12345. this._keys = values.slice(0);
  12346. this._offsetsCache = {};
  12347. this._highLimitsCache = {};
  12348. };
  12349. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  12350. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  12351. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  12352. }
  12353. this.currentFrame = currentFrame;
  12354. for (var key = 0; key < this._keys.length; key++) {
  12355. if (this._keys[key + 1].frame >= currentFrame) {
  12356. var startValue = this._keys[key].value;
  12357. var endValue = this._keys[key + 1].value;
  12358. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  12359. switch (this.dataType) {
  12360. case Animation.ANIMATIONTYPE_FLOAT:
  12361. switch (loopMode) {
  12362. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12363. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12364. return this.floatInterpolateFunction(startValue, endValue, gradient);
  12365. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12366. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  12367. }
  12368. break;
  12369. case Animation.ANIMATIONTYPE_QUATERNION:
  12370. var quaternion = null;
  12371. switch (loopMode) {
  12372. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12373. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12374. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  12375. break;
  12376. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12377. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12378. break;
  12379. }
  12380. return quaternion;
  12381. case Animation.ANIMATIONTYPE_VECTOR3:
  12382. switch (loopMode) {
  12383. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12384. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12385. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  12386. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12387. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12388. }
  12389. case Animation.ANIMATIONTYPE_VECTOR2:
  12390. switch (loopMode) {
  12391. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12392. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12393. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  12394. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12395. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12396. }
  12397. case Animation.ANIMATIONTYPE_COLOR3:
  12398. switch (loopMode) {
  12399. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12400. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12401. return this.color3InterpolateFunction(startValue, endValue, gradient);
  12402. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12403. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12404. }
  12405. case Animation.ANIMATIONTYPE_MATRIX:
  12406. switch (loopMode) {
  12407. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12408. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12409. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12410. return startValue;
  12411. }
  12412. default:
  12413. break;
  12414. }
  12415. break;
  12416. }
  12417. }
  12418. return this._keys[this._keys.length - 1].value;
  12419. };
  12420. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  12421. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  12422. this._stopped = true;
  12423. return false;
  12424. }
  12425. var returnValue = true;
  12426. if (this._keys[0].frame != 0) {
  12427. var newKey = {
  12428. frame: 0,
  12429. value: this._keys[0].value
  12430. };
  12431. this._keys.splice(0, 0, newKey);
  12432. }
  12433. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  12434. from = this._keys[0].frame;
  12435. }
  12436. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  12437. to = this._keys[this._keys.length - 1].frame;
  12438. }
  12439. var range = to - from;
  12440. var offsetValue;
  12441. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  12442. if (ratio > range && !loop) {
  12443. returnValue = false;
  12444. highLimitValue = this._keys[this._keys.length - 1].value;
  12445. } else {
  12446. var highLimitValue = 0;
  12447. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  12448. var keyOffset = to.toString() + from.toString();
  12449. if (!this._offsetsCache[keyOffset]) {
  12450. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  12451. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  12452. switch (this.dataType) {
  12453. case Animation.ANIMATIONTYPE_FLOAT:
  12454. this._offsetsCache[keyOffset] = toValue - fromValue;
  12455. break;
  12456. case Animation.ANIMATIONTYPE_QUATERNION:
  12457. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12458. break;
  12459. case Animation.ANIMATIONTYPE_VECTOR3:
  12460. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12461. case Animation.ANIMATIONTYPE_VECTOR2:
  12462. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12463. case Animation.ANIMATIONTYPE_COLOR3:
  12464. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12465. default:
  12466. break;
  12467. }
  12468. this._highLimitsCache[keyOffset] = toValue;
  12469. }
  12470. highLimitValue = this._highLimitsCache[keyOffset];
  12471. offsetValue = this._offsetsCache[keyOffset];
  12472. }
  12473. }
  12474. if (offsetValue === undefined) {
  12475. switch (this.dataType) {
  12476. case Animation.ANIMATIONTYPE_FLOAT:
  12477. offsetValue = 0;
  12478. break;
  12479. case Animation.ANIMATIONTYPE_QUATERNION:
  12480. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  12481. break;
  12482. case Animation.ANIMATIONTYPE_VECTOR3:
  12483. offsetValue = BABYLON.Vector3.Zero();
  12484. break;
  12485. case Animation.ANIMATIONTYPE_VECTOR2:
  12486. offsetValue = BABYLON.Vector2.Zero();
  12487. break;
  12488. case Animation.ANIMATIONTYPE_COLOR3:
  12489. offsetValue = BABYLON.Color3.Black();
  12490. }
  12491. }
  12492. var repeatCount = (ratio / range) >> 0;
  12493. var currentFrame = returnValue ? from + ratio % range : to;
  12494. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  12495. if (this.targetPropertyPath.length > 1) {
  12496. var property = this._target[this.targetPropertyPath[0]];
  12497. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  12498. property = property[this.targetPropertyPath[index]];
  12499. }
  12500. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  12501. } else {
  12502. this._target[this.targetPropertyPath[0]] = currentValue;
  12503. }
  12504. if (this._target.markAsDirty) {
  12505. this._target.markAsDirty(this.targetProperty);
  12506. }
  12507. if (!returnValue) {
  12508. this._stopped = true;
  12509. }
  12510. return returnValue;
  12511. };
  12512. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  12513. get: function () {
  12514. return Animation._ANIMATIONTYPE_FLOAT;
  12515. },
  12516. enumerable: true,
  12517. configurable: true
  12518. });
  12519. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  12520. get: function () {
  12521. return Animation._ANIMATIONTYPE_VECTOR3;
  12522. },
  12523. enumerable: true,
  12524. configurable: true
  12525. });
  12526. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  12527. get: function () {
  12528. return Animation._ANIMATIONTYPE_VECTOR2;
  12529. },
  12530. enumerable: true,
  12531. configurable: true
  12532. });
  12533. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  12534. get: function () {
  12535. return Animation._ANIMATIONTYPE_QUATERNION;
  12536. },
  12537. enumerable: true,
  12538. configurable: true
  12539. });
  12540. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  12541. get: function () {
  12542. return Animation._ANIMATIONTYPE_MATRIX;
  12543. },
  12544. enumerable: true,
  12545. configurable: true
  12546. });
  12547. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  12548. get: function () {
  12549. return Animation._ANIMATIONTYPE_COLOR3;
  12550. },
  12551. enumerable: true,
  12552. configurable: true
  12553. });
  12554. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  12555. get: function () {
  12556. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  12557. },
  12558. enumerable: true,
  12559. configurable: true
  12560. });
  12561. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  12562. get: function () {
  12563. return Animation._ANIMATIONLOOPMODE_CYCLE;
  12564. },
  12565. enumerable: true,
  12566. configurable: true
  12567. });
  12568. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  12569. get: function () {
  12570. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  12571. },
  12572. enumerable: true,
  12573. configurable: true
  12574. });
  12575. Animation._ANIMATIONTYPE_FLOAT = 0;
  12576. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  12577. Animation._ANIMATIONTYPE_QUATERNION = 2;
  12578. Animation._ANIMATIONTYPE_MATRIX = 3;
  12579. Animation._ANIMATIONTYPE_COLOR3 = 4;
  12580. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  12581. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  12582. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  12583. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  12584. return Animation;
  12585. })();
  12586. BABYLON.Animation = Animation;
  12587. })(BABYLON || (BABYLON = {}));
  12588. var BABYLON;
  12589. (function (BABYLON) {
  12590. var Animatable = (function () {
  12591. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  12592. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  12593. if (typeof toFrame === "undefined") { toFrame = 100; }
  12594. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  12595. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  12596. this.target = target;
  12597. this.fromFrame = fromFrame;
  12598. this.toFrame = toFrame;
  12599. this.loopAnimation = loopAnimation;
  12600. this.speedRatio = speedRatio;
  12601. this.onAnimationEnd = onAnimationEnd;
  12602. this._animations = new Array();
  12603. this._paused = false;
  12604. this.animationStarted = false;
  12605. if (animations) {
  12606. this.appendAnimations(target, animations);
  12607. }
  12608. this._scene = scene;
  12609. scene._activeAnimatables.push(this);
  12610. }
  12611. Animatable.prototype.appendAnimations = function (target, animations) {
  12612. for (var index = 0; index < animations.length; index++) {
  12613. var animation = animations[index];
  12614. animation._target = target;
  12615. this._animations.push(animation);
  12616. }
  12617. };
  12618. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  12619. var animations = this._animations;
  12620. for (var index = 0; index < animations.length; index++) {
  12621. if (animations[index].targetProperty === property) {
  12622. return animations[index];
  12623. }
  12624. }
  12625. return null;
  12626. };
  12627. Animatable.prototype.pause = function () {
  12628. if (this._paused) {
  12629. return;
  12630. }
  12631. this._paused = true;
  12632. };
  12633. Animatable.prototype.restart = function () {
  12634. this._paused = false;
  12635. };
  12636. Animatable.prototype.stop = function () {
  12637. var index = this._scene._activeAnimatables.indexOf(this);
  12638. if (index > -1) {
  12639. this._scene._activeAnimatables.splice(index, 1);
  12640. }
  12641. if (this.onAnimationEnd) {
  12642. this.onAnimationEnd();
  12643. }
  12644. };
  12645. Animatable.prototype._animate = function (delay) {
  12646. if (this._paused) {
  12647. if (!this._pausedDelay) {
  12648. this._pausedDelay = delay;
  12649. }
  12650. return true;
  12651. }
  12652. if (!this._localDelayOffset) {
  12653. this._localDelayOffset = delay;
  12654. } else if (this._pausedDelay) {
  12655. this._localDelayOffset += delay - this._pausedDelay;
  12656. this._pausedDelay = null;
  12657. }
  12658. var running = false;
  12659. var animations = this._animations;
  12660. for (var index = 0; index < animations.length; index++) {
  12661. var animation = animations[index];
  12662. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  12663. running = running || isRunning;
  12664. }
  12665. if (!running && this.onAnimationEnd) {
  12666. this.onAnimationEnd();
  12667. }
  12668. return running;
  12669. };
  12670. return Animatable;
  12671. })();
  12672. BABYLON.Animatable = Animatable;
  12673. })(BABYLON || (BABYLON = {}));
  12674. var BABYLON;
  12675. (function (BABYLON) {
  12676. var Octree = (function () {
  12677. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  12678. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  12679. this.maxDepth = maxDepth;
  12680. this.dynamicContent = new Array();
  12681. this._maxBlockCapacity = maxBlockCapacity || 64;
  12682. this._selectionContent = new BABYLON.SmartArray(1024);
  12683. this._creationFunc = creationFunc;
  12684. }
  12685. Octree.prototype.update = function (worldMin, worldMax, entries) {
  12686. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  12687. };
  12688. Octree.prototype.addMesh = function (entry) {
  12689. for (var index = 0; index < this.blocks.length; index++) {
  12690. var block = this.blocks[index];
  12691. block.addEntry(entry);
  12692. }
  12693. };
  12694. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  12695. this._selectionContent.reset();
  12696. for (var index = 0; index < this.blocks.length; index++) {
  12697. var block = this.blocks[index];
  12698. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  12699. }
  12700. if (allowDuplicate) {
  12701. this._selectionContent.concat(this.dynamicContent);
  12702. } else {
  12703. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  12704. }
  12705. return this._selectionContent;
  12706. };
  12707. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  12708. this._selectionContent.reset();
  12709. for (var index = 0; index < this.blocks.length; index++) {
  12710. var block = this.blocks[index];
  12711. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  12712. }
  12713. if (allowDuplicate) {
  12714. this._selectionContent.concat(this.dynamicContent);
  12715. } else {
  12716. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  12717. }
  12718. return this._selectionContent;
  12719. };
  12720. Octree.prototype.intersectsRay = function (ray) {
  12721. this._selectionContent.reset();
  12722. for (var index = 0; index < this.blocks.length; index++) {
  12723. var block = this.blocks[index];
  12724. block.intersectsRay(ray, this._selectionContent);
  12725. }
  12726. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  12727. return this._selectionContent;
  12728. };
  12729. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  12730. target.blocks = new Array();
  12731. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  12732. for (var x = 0; x < 2; x++) {
  12733. for (var y = 0; y < 2; y++) {
  12734. for (var z = 0; z < 2; z++) {
  12735. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  12736. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  12737. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  12738. block.addEntries(entries);
  12739. target.blocks.push(block);
  12740. }
  12741. }
  12742. }
  12743. };
  12744. Octree.CreationFuncForMeshes = function (entry, block) {
  12745. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  12746. block.entries.push(entry);
  12747. }
  12748. };
  12749. Octree.CreationFuncForSubMeshes = function (entry, block) {
  12750. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  12751. block.entries.push(entry);
  12752. }
  12753. };
  12754. return Octree;
  12755. })();
  12756. BABYLON.Octree = Octree;
  12757. })(BABYLON || (BABYLON = {}));
  12758. var BABYLON;
  12759. (function (BABYLON) {
  12760. var OctreeBlock = (function () {
  12761. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  12762. this.entries = new Array();
  12763. this._boundingVectors = new Array();
  12764. this._capacity = capacity;
  12765. this._depth = depth;
  12766. this._maxDepth = maxDepth;
  12767. this._creationFunc = creationFunc;
  12768. this._minPoint = minPoint;
  12769. this._maxPoint = maxPoint;
  12770. this._boundingVectors.push(minPoint.clone());
  12771. this._boundingVectors.push(maxPoint.clone());
  12772. this._boundingVectors.push(minPoint.clone());
  12773. this._boundingVectors[2].x = maxPoint.x;
  12774. this._boundingVectors.push(minPoint.clone());
  12775. this._boundingVectors[3].y = maxPoint.y;
  12776. this._boundingVectors.push(minPoint.clone());
  12777. this._boundingVectors[4].z = maxPoint.z;
  12778. this._boundingVectors.push(maxPoint.clone());
  12779. this._boundingVectors[5].z = minPoint.z;
  12780. this._boundingVectors.push(maxPoint.clone());
  12781. this._boundingVectors[6].x = minPoint.x;
  12782. this._boundingVectors.push(maxPoint.clone());
  12783. this._boundingVectors[7].y = minPoint.y;
  12784. }
  12785. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  12786. get: function () {
  12787. return this._capacity;
  12788. },
  12789. enumerable: true,
  12790. configurable: true
  12791. });
  12792. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  12793. get: function () {
  12794. return this._minPoint;
  12795. },
  12796. enumerable: true,
  12797. configurable: true
  12798. });
  12799. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  12800. get: function () {
  12801. return this._maxPoint;
  12802. },
  12803. enumerable: true,
  12804. configurable: true
  12805. });
  12806. OctreeBlock.prototype.addEntry = function (entry) {
  12807. if (this.blocks) {
  12808. for (var index = 0; index < this.blocks.length; index++) {
  12809. var block = this.blocks[index];
  12810. block.addEntry(entry);
  12811. }
  12812. return;
  12813. }
  12814. this._creationFunc(entry, this);
  12815. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  12816. this.createInnerBlocks();
  12817. }
  12818. };
  12819. OctreeBlock.prototype.addEntries = function (entries) {
  12820. for (var index = 0; index < entries.length; index++) {
  12821. var mesh = entries[index];
  12822. this.addEntry(mesh);
  12823. }
  12824. };
  12825. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  12826. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  12827. if (this.blocks) {
  12828. for (var index = 0; index < this.blocks.length; index++) {
  12829. var block = this.blocks[index];
  12830. block.select(frustumPlanes, selection, allowDuplicate);
  12831. }
  12832. return;
  12833. }
  12834. if (allowDuplicate) {
  12835. selection.concat(this.entries);
  12836. } else {
  12837. selection.concatWithNoDuplicate(this.entries);
  12838. }
  12839. }
  12840. };
  12841. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  12842. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  12843. if (this.blocks) {
  12844. for (var index = 0; index < this.blocks.length; index++) {
  12845. var block = this.blocks[index];
  12846. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  12847. }
  12848. return;
  12849. }
  12850. if (allowDuplicate) {
  12851. selection.concat(this.entries);
  12852. } else {
  12853. selection.concatWithNoDuplicate(this.entries);
  12854. }
  12855. }
  12856. };
  12857. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  12858. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  12859. if (this.blocks) {
  12860. for (var index = 0; index < this.blocks.length; index++) {
  12861. var block = this.blocks[index];
  12862. block.intersectsRay(ray, selection);
  12863. }
  12864. return;
  12865. }
  12866. selection.concatWithNoDuplicate(this.entries);
  12867. }
  12868. };
  12869. OctreeBlock.prototype.createInnerBlocks = function () {
  12870. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  12871. };
  12872. return OctreeBlock;
  12873. })();
  12874. BABYLON.OctreeBlock = OctreeBlock;
  12875. })(BABYLON || (BABYLON = {}));
  12876. var BABYLON;
  12877. (function (BABYLON) {
  12878. var Bone = (function () {
  12879. function Bone(name, skeleton, parentBone, matrix) {
  12880. this.name = name;
  12881. this.children = new Array();
  12882. this.animations = new Array();
  12883. this._worldTransform = new BABYLON.Matrix();
  12884. this._absoluteTransform = new BABYLON.Matrix();
  12885. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  12886. this._skeleton = skeleton;
  12887. this._matrix = matrix;
  12888. this._baseMatrix = matrix;
  12889. skeleton.bones.push(this);
  12890. if (parentBone) {
  12891. this._parent = parentBone;
  12892. parentBone.children.push(this);
  12893. } else {
  12894. this._parent = null;
  12895. }
  12896. this._updateDifferenceMatrix();
  12897. }
  12898. Bone.prototype.getParent = function () {
  12899. return this._parent;
  12900. };
  12901. Bone.prototype.getLocalMatrix = function () {
  12902. return this._matrix;
  12903. };
  12904. Bone.prototype.getBaseMatrix = function () {
  12905. return this._baseMatrix;
  12906. };
  12907. Bone.prototype.getWorldMatrix = function () {
  12908. return this._worldTransform;
  12909. };
  12910. Bone.prototype.getInvertedAbsoluteTransform = function () {
  12911. return this._invertedAbsoluteTransform;
  12912. };
  12913. Bone.prototype.getAbsoluteMatrix = function () {
  12914. var matrix = this._matrix.clone();
  12915. var parent = this._parent;
  12916. while (parent) {
  12917. matrix = matrix.multiply(parent.getLocalMatrix());
  12918. parent = parent.getParent();
  12919. }
  12920. return matrix;
  12921. };
  12922. Bone.prototype.updateMatrix = function (matrix) {
  12923. this._matrix = matrix;
  12924. this._skeleton._markAsDirty();
  12925. this._updateDifferenceMatrix();
  12926. };
  12927. Bone.prototype._updateDifferenceMatrix = function () {
  12928. if (this._parent) {
  12929. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  12930. } else {
  12931. this._absoluteTransform.copyFrom(this._matrix);
  12932. }
  12933. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  12934. for (var index = 0; index < this.children.length; index++) {
  12935. this.children[index]._updateDifferenceMatrix();
  12936. }
  12937. };
  12938. Bone.prototype.markAsDirty = function () {
  12939. this._skeleton._markAsDirty();
  12940. };
  12941. return Bone;
  12942. })();
  12943. BABYLON.Bone = Bone;
  12944. })(BABYLON || (BABYLON = {}));
  12945. var BABYLON;
  12946. (function (BABYLON) {
  12947. var Skeleton = (function () {
  12948. function Skeleton(name, id, scene) {
  12949. this.name = name;
  12950. this.id = id;
  12951. this.bones = new Array();
  12952. this._isDirty = true;
  12953. this._identity = BABYLON.Matrix.Identity();
  12954. this.bones = [];
  12955. this._scene = scene;
  12956. scene.skeletons.push(this);
  12957. }
  12958. Skeleton.prototype.getTransformMatrices = function () {
  12959. return this._transformMatrices;
  12960. };
  12961. Skeleton.prototype._markAsDirty = function () {
  12962. this._isDirty = true;
  12963. };
  12964. Skeleton.prototype.prepare = function () {
  12965. if (!this._isDirty) {
  12966. return;
  12967. }
  12968. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  12969. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  12970. }
  12971. for (var index = 0; index < this.bones.length; index++) {
  12972. var bone = this.bones[index];
  12973. var parentBone = bone.getParent();
  12974. if (parentBone) {
  12975. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  12976. } else {
  12977. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  12978. }
  12979. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  12980. }
  12981. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  12982. this._isDirty = false;
  12983. };
  12984. Skeleton.prototype.getAnimatables = function () {
  12985. if (!this._animatables || this._animatables.length != this.bones.length) {
  12986. this._animatables = [];
  12987. for (var index = 0; index < this.bones.length; index++) {
  12988. this._animatables.push(this.bones[index]);
  12989. }
  12990. }
  12991. return this._animatables;
  12992. };
  12993. Skeleton.prototype.clone = function (name, id) {
  12994. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  12995. for (var index = 0; index < this.bones.length; index++) {
  12996. var source = this.bones[index];
  12997. var parentBone = null;
  12998. if (source.getParent()) {
  12999. var parentIndex = this.bones.indexOf(source.getParent());
  13000. parentBone = result.bones[parentIndex];
  13001. }
  13002. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  13003. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  13004. }
  13005. return result;
  13006. };
  13007. return Skeleton;
  13008. })();
  13009. BABYLON.Skeleton = Skeleton;
  13010. })(BABYLON || (BABYLON = {}));
  13011. var BABYLON;
  13012. (function (BABYLON) {
  13013. var PostProcess = (function () {
  13014. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  13015. this.name = name;
  13016. this.width = -1;
  13017. this.height = -1;
  13018. this._reusable = false;
  13019. this._textures = new BABYLON.SmartArray(2);
  13020. this._currentRenderTextureInd = 0;
  13021. if (camera != null) {
  13022. this._camera = camera;
  13023. this._scene = camera.getScene();
  13024. camera.attachPostProcess(this);
  13025. this._engine = this._scene.getEngine();
  13026. } else {
  13027. this._engine = engine;
  13028. }
  13029. this._renderRatio = ratio;
  13030. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13031. this._reusable = reusable || false;
  13032. samplers = samplers || [];
  13033. samplers.push("textureSampler");
  13034. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  13035. }
  13036. PostProcess.prototype.isReusable = function () {
  13037. return this._reusable;
  13038. };
  13039. PostProcess.prototype.activate = function (camera, sourceTexture) {
  13040. camera = camera || this._camera;
  13041. var scene = camera.getScene();
  13042. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  13043. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  13044. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  13045. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  13046. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  13047. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  13048. if (this._textures.length > 0) {
  13049. for (var i = 0; i < this._textures.length; i++) {
  13050. this._engine._releaseTexture(this._textures.data[i]);
  13051. }
  13052. this._textures.reset();
  13053. }
  13054. this.width = desiredWidth;
  13055. this.height = desiredHeight;
  13056. 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 }));
  13057. if (this._reusable) {
  13058. 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 }));
  13059. }
  13060. if (this.onSizeChanged) {
  13061. this.onSizeChanged();
  13062. }
  13063. }
  13064. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  13065. if (this.onActivate) {
  13066. this.onActivate(camera);
  13067. }
  13068. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  13069. if (this._reusable) {
  13070. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  13071. }
  13072. };
  13073. PostProcess.prototype.apply = function () {
  13074. if (!this._effect.isReady())
  13075. return null;
  13076. this._engine.enableEffect(this._effect);
  13077. this._engine.setState(false);
  13078. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13079. this._engine.setDepthBuffer(false);
  13080. this._engine.setDepthWrite(false);
  13081. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  13082. if (this.onApply) {
  13083. this.onApply(this._effect);
  13084. }
  13085. return this._effect;
  13086. };
  13087. PostProcess.prototype.dispose = function (camera) {
  13088. camera = camera || this._camera;
  13089. if (this._textures.length > 0) {
  13090. for (var i = 0; i < this._textures.length; i++) {
  13091. this._engine._releaseTexture(this._textures.data[i]);
  13092. }
  13093. this._textures.reset();
  13094. }
  13095. camera.detachPostProcess(this);
  13096. var index = camera._postProcesses.indexOf(this);
  13097. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  13098. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  13099. }
  13100. };
  13101. return PostProcess;
  13102. })();
  13103. BABYLON.PostProcess = PostProcess;
  13104. })(BABYLON || (BABYLON = {}));
  13105. var BABYLON;
  13106. (function (BABYLON) {
  13107. var PostProcessManager = (function () {
  13108. function PostProcessManager(scene) {
  13109. this._vertexDeclaration = [2];
  13110. this._vertexStrideSize = 2 * 4;
  13111. this._scene = scene;
  13112. var vertices = [];
  13113. vertices.push(1, 1);
  13114. vertices.push(-1, 1);
  13115. vertices.push(-1, -1);
  13116. vertices.push(1, -1);
  13117. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13118. var indices = [];
  13119. indices.push(0);
  13120. indices.push(1);
  13121. indices.push(2);
  13122. indices.push(0);
  13123. indices.push(2);
  13124. indices.push(3);
  13125. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13126. }
  13127. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  13128. var postProcesses = this._scene.activeCamera._postProcesses;
  13129. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  13130. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  13131. return false;
  13132. }
  13133. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  13134. return true;
  13135. };
  13136. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  13137. var postProcesses = this._scene.activeCamera._postProcesses;
  13138. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  13139. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  13140. return;
  13141. }
  13142. var engine = this._scene.getEngine();
  13143. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  13144. if (index < postProcessesTakenIndices.length - 1) {
  13145. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  13146. } else {
  13147. if (targetTexture) {
  13148. engine.bindFramebuffer(targetTexture);
  13149. } else {
  13150. engine.restoreDefaultFramebuffer();
  13151. }
  13152. }
  13153. if (doNotPresent) {
  13154. break;
  13155. }
  13156. var pp = postProcesses[postProcessesTakenIndices[index]];
  13157. var effect = pp.apply();
  13158. if (effect) {
  13159. if (pp.onBeforeRender) {
  13160. pp.onBeforeRender(effect);
  13161. }
  13162. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13163. engine.draw(true, 0, 6);
  13164. }
  13165. }
  13166. engine.setDepthBuffer(true);
  13167. engine.setDepthWrite(true);
  13168. };
  13169. PostProcessManager.prototype.dispose = function () {
  13170. if (this._vertexBuffer) {
  13171. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13172. this._vertexBuffer = null;
  13173. }
  13174. if (this._indexBuffer) {
  13175. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13176. this._indexBuffer = null;
  13177. }
  13178. };
  13179. return PostProcessManager;
  13180. })();
  13181. BABYLON.PostProcessManager = PostProcessManager;
  13182. })(BABYLON || (BABYLON = {}));
  13183. var __extends = this.__extends || function (d, b) {
  13184. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13185. function __() { this.constructor = d; }
  13186. __.prototype = b.prototype;
  13187. d.prototype = new __();
  13188. };
  13189. var BABYLON;
  13190. (function (BABYLON) {
  13191. var PassPostProcess = (function (_super) {
  13192. __extends(PassPostProcess, _super);
  13193. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  13194. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  13195. }
  13196. return PassPostProcess;
  13197. })(BABYLON.PostProcess);
  13198. BABYLON.PassPostProcess = PassPostProcess;
  13199. })(BABYLON || (BABYLON = {}));
  13200. var __extends = this.__extends || function (d, b) {
  13201. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13202. function __() { this.constructor = d; }
  13203. __.prototype = b.prototype;
  13204. d.prototype = new __();
  13205. };
  13206. var BABYLON;
  13207. (function (BABYLON) {
  13208. var BlurPostProcess = (function (_super) {
  13209. __extends(BlurPostProcess, _super);
  13210. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  13211. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  13212. var _this = this;
  13213. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  13214. this.direction = direction;
  13215. this.blurWidth = blurWidth;
  13216. this.onApply = function (effect) {
  13217. effect.setFloat2("screenSize", _this.width, _this.height);
  13218. effect.setVector2("direction", _this.direction);
  13219. effect.setFloat("blurWidth", _this.blurWidth);
  13220. };
  13221. }
  13222. return BlurPostProcess;
  13223. })(BABYLON.PostProcess);
  13224. BABYLON.BlurPostProcess = BlurPostProcess;
  13225. })(BABYLON || (BABYLON = {}));
  13226. var __extends = this.__extends || function (d, b) {
  13227. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13228. function __() { this.constructor = d; }
  13229. __.prototype = b.prototype;
  13230. d.prototype = new __();
  13231. };
  13232. var BABYLON;
  13233. (function (BABYLON) {
  13234. var FilterPostProcess = (function (_super) {
  13235. __extends(FilterPostProcess, _super);
  13236. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  13237. var _this = this;
  13238. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  13239. this.kernelMatrix = kernelMatrix;
  13240. this.onApply = function (effect) {
  13241. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  13242. };
  13243. }
  13244. return FilterPostProcess;
  13245. })(BABYLON.PostProcess);
  13246. BABYLON.FilterPostProcess = FilterPostProcess;
  13247. })(BABYLON || (BABYLON = {}));
  13248. var __extends = this.__extends || function (d, b) {
  13249. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13250. function __() { this.constructor = d; }
  13251. __.prototype = b.prototype;
  13252. d.prototype = new __();
  13253. };
  13254. var BABYLON;
  13255. (function (BABYLON) {
  13256. var RefractionPostProcess = (function (_super) {
  13257. __extends(RefractionPostProcess, _super);
  13258. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  13259. var _this = this;
  13260. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  13261. this.color = color;
  13262. this.depth = depth;
  13263. this.colorLevel = colorLevel;
  13264. this.onActivate = function (cam) {
  13265. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  13266. };
  13267. this.onApply = function (effect) {
  13268. effect.setColor3("baseColor", _this.color);
  13269. effect.setFloat("depth", _this.depth);
  13270. effect.setFloat("colorLevel", _this.colorLevel);
  13271. effect.setTexture("refractionSampler", _this._refRexture);
  13272. };
  13273. }
  13274. RefractionPostProcess.prototype.dispose = function (camera) {
  13275. if (this._refRexture) {
  13276. this._refRexture.dispose();
  13277. }
  13278. _super.prototype.dispose.call(this, camera);
  13279. };
  13280. return RefractionPostProcess;
  13281. })(BABYLON.PostProcess);
  13282. BABYLON.RefractionPostProcess = RefractionPostProcess;
  13283. })(BABYLON || (BABYLON = {}));
  13284. var __extends = this.__extends || function (d, b) {
  13285. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13286. function __() { this.constructor = d; }
  13287. __.prototype = b.prototype;
  13288. d.prototype = new __();
  13289. };
  13290. var BABYLON;
  13291. (function (BABYLON) {
  13292. var BlackAndWhitePostProcess = (function (_super) {
  13293. __extends(BlackAndWhitePostProcess, _super);
  13294. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  13295. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  13296. }
  13297. return BlackAndWhitePostProcess;
  13298. })(BABYLON.PostProcess);
  13299. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  13300. })(BABYLON || (BABYLON = {}));
  13301. var __extends = this.__extends || function (d, b) {
  13302. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13303. function __() { this.constructor = d; }
  13304. __.prototype = b.prototype;
  13305. d.prototype = new __();
  13306. };
  13307. var BABYLON;
  13308. (function (BABYLON) {
  13309. var ConvolutionPostProcess = (function (_super) {
  13310. __extends(ConvolutionPostProcess, _super);
  13311. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  13312. var _this = this;
  13313. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  13314. this.kernel = kernel;
  13315. this.onApply = function (effect) {
  13316. effect.setFloat2("screenSize", _this.width, _this.height);
  13317. effect.setArray("kernel", _this.kernel);
  13318. };
  13319. }
  13320. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  13321. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  13322. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  13323. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  13324. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  13325. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  13326. return ConvolutionPostProcess;
  13327. })(BABYLON.PostProcess);
  13328. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  13329. })(BABYLON || (BABYLON = {}));
  13330. var __extends = this.__extends || function (d, b) {
  13331. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13332. function __() { this.constructor = d; }
  13333. __.prototype = b.prototype;
  13334. d.prototype = new __();
  13335. };
  13336. var BABYLON;
  13337. (function (BABYLON) {
  13338. var FxaaPostProcess = (function (_super) {
  13339. __extends(FxaaPostProcess, _super);
  13340. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  13341. var _this = this;
  13342. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  13343. this.onSizeChanged = function () {
  13344. _this.texelWidth = 1.0 / _this.width;
  13345. _this.texelHeight = 1.0 / _this.height;
  13346. };
  13347. this.onApply = function (effect) {
  13348. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  13349. };
  13350. }
  13351. return FxaaPostProcess;
  13352. })(BABYLON.PostProcess);
  13353. BABYLON.FxaaPostProcess = FxaaPostProcess;
  13354. })(BABYLON || (BABYLON = {}));
  13355. var BABYLON;
  13356. (function (BABYLON) {
  13357. var LensFlare = (function () {
  13358. function LensFlare(size, position, color, imgUrl, system) {
  13359. this.size = size;
  13360. this.position = position;
  13361. this.dispose = function () {
  13362. if (this.texture) {
  13363. this.texture.dispose();
  13364. }
  13365. var index = this._system.lensFlares.indexOf(this);
  13366. this._system.lensFlares.splice(index, 1);
  13367. };
  13368. this.color = color || new BABYLON.Color3(1, 1, 1);
  13369. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  13370. this._system = system;
  13371. system.lensFlares.push(this);
  13372. }
  13373. return LensFlare;
  13374. })();
  13375. BABYLON.LensFlare = LensFlare;
  13376. })(BABYLON || (BABYLON = {}));
  13377. var BABYLON;
  13378. (function (BABYLON) {
  13379. var LensFlareSystem = (function () {
  13380. function LensFlareSystem(name, emitter, scene) {
  13381. this.name = name;
  13382. this.lensFlares = new Array();
  13383. this.borderLimit = 300;
  13384. this._vertexDeclaration = [2];
  13385. this._vertexStrideSize = 2 * 4;
  13386. this._isEnabled = true;
  13387. this._scene = scene;
  13388. this._emitter = emitter;
  13389. scene.lensFlareSystems.push(this);
  13390. this.meshesSelectionPredicate = function (m) {
  13391. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  13392. };
  13393. var vertices = [];
  13394. vertices.push(1, 1);
  13395. vertices.push(-1, 1);
  13396. vertices.push(-1, -1);
  13397. vertices.push(1, -1);
  13398. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13399. var indices = [];
  13400. indices.push(0);
  13401. indices.push(1);
  13402. indices.push(2);
  13403. indices.push(0);
  13404. indices.push(2);
  13405. indices.push(3);
  13406. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13407. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  13408. }
  13409. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  13410. get: function () {
  13411. return this._isEnabled;
  13412. },
  13413. set: function (value) {
  13414. this._isEnabled = value;
  13415. },
  13416. enumerable: true,
  13417. configurable: true
  13418. });
  13419. LensFlareSystem.prototype.getScene = function () {
  13420. return this._scene;
  13421. };
  13422. LensFlareSystem.prototype.getEmitter = function () {
  13423. return this._emitter;
  13424. };
  13425. LensFlareSystem.prototype.getEmitterPosition = function () {
  13426. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  13427. };
  13428. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  13429. var position = this.getEmitterPosition();
  13430. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  13431. this._positionX = position.x;
  13432. this._positionY = position.y;
  13433. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  13434. if (position.z > 0) {
  13435. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  13436. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  13437. return true;
  13438. }
  13439. }
  13440. return false;
  13441. };
  13442. LensFlareSystem.prototype._isVisible = function () {
  13443. if (!this._isEnabled) {
  13444. return false;
  13445. }
  13446. var emitterPosition = this.getEmitterPosition();
  13447. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  13448. var distance = direction.length();
  13449. direction.normalize();
  13450. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  13451. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  13452. return !pickInfo.hit || pickInfo.distance > distance;
  13453. };
  13454. LensFlareSystem.prototype.render = function () {
  13455. if (!this._effect.isReady())
  13456. return false;
  13457. var engine = this._scene.getEngine();
  13458. var viewport = this._scene.activeCamera.viewport;
  13459. var globalViewport = viewport.toGlobal(engine);
  13460. if (!this.computeEffectivePosition(globalViewport)) {
  13461. return false;
  13462. }
  13463. if (!this._isVisible()) {
  13464. return false;
  13465. }
  13466. var awayX;
  13467. var awayY;
  13468. if (this._positionX < this.borderLimit + globalViewport.x) {
  13469. awayX = this.borderLimit + globalViewport.x - this._positionX;
  13470. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  13471. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  13472. } else {
  13473. awayX = 0;
  13474. }
  13475. if (this._positionY < this.borderLimit + globalViewport.y) {
  13476. awayY = this.borderLimit + globalViewport.y - this._positionY;
  13477. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  13478. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  13479. } else {
  13480. awayY = 0;
  13481. }
  13482. var away = (awayX > awayY) ? awayX : awayY;
  13483. if (away > this.borderLimit) {
  13484. away = this.borderLimit;
  13485. }
  13486. var intensity = 1.0 - (away / this.borderLimit);
  13487. if (intensity < 0) {
  13488. return false;
  13489. }
  13490. if (intensity > 1.0) {
  13491. intensity = 1.0;
  13492. }
  13493. var centerX = globalViewport.x + globalViewport.width / 2;
  13494. var centerY = globalViewport.y + globalViewport.height / 2;
  13495. var distX = centerX - this._positionX;
  13496. var distY = centerY - this._positionY;
  13497. engine.enableEffect(this._effect);
  13498. engine.setState(false);
  13499. engine.setDepthBuffer(false);
  13500. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  13501. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13502. for (var index = 0; index < this.lensFlares.length; index++) {
  13503. var flare = this.lensFlares[index];
  13504. var x = centerX - (distX * flare.position);
  13505. var y = centerY - (distY * flare.position);
  13506. var cw = flare.size;
  13507. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  13508. var cx = 2 * (x / globalViewport.width) - 1.0;
  13509. var cy = 1.0 - 2 * (y / globalViewport.height);
  13510. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  13511. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  13512. this._effect.setTexture("textureSampler", flare.texture);
  13513. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  13514. engine.draw(true, 0, 6);
  13515. }
  13516. engine.setDepthBuffer(true);
  13517. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13518. return true;
  13519. };
  13520. LensFlareSystem.prototype.dispose = function () {
  13521. if (this._vertexBuffer) {
  13522. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13523. this._vertexBuffer = null;
  13524. }
  13525. if (this._indexBuffer) {
  13526. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13527. this._indexBuffer = null;
  13528. }
  13529. while (this.lensFlares.length) {
  13530. this.lensFlares[0].dispose();
  13531. }
  13532. var index = this._scene.lensFlareSystems.indexOf(this);
  13533. this._scene.lensFlareSystems.splice(index, 1);
  13534. };
  13535. return LensFlareSystem;
  13536. })();
  13537. BABYLON.LensFlareSystem = LensFlareSystem;
  13538. })(BABYLON || (BABYLON = {}));
  13539. var BABYLON;
  13540. (function (BABYLON) {
  13541. var IntersectionInfo = (function () {
  13542. function IntersectionInfo(bu, bv, distance) {
  13543. this.bu = bu;
  13544. this.bv = bv;
  13545. this.distance = distance;
  13546. this.faceId = 0;
  13547. }
  13548. return IntersectionInfo;
  13549. })();
  13550. BABYLON.IntersectionInfo = IntersectionInfo;
  13551. var PickingInfo = (function () {
  13552. function PickingInfo() {
  13553. this.hit = false;
  13554. this.distance = 0;
  13555. this.pickedPoint = null;
  13556. this.pickedMesh = null;
  13557. this.bu = 0;
  13558. this.bv = 0;
  13559. this.faceId = -1;
  13560. }
  13561. PickingInfo.prototype.getNormal = function () {
  13562. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13563. return null;
  13564. }
  13565. var indices = this.pickedMesh.getIndices();
  13566. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13567. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  13568. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  13569. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  13570. normal0 = normal0.scale(this.bu);
  13571. normal1 = normal1.scale(this.bv);
  13572. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  13573. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  13574. };
  13575. PickingInfo.prototype.getTextureCoordinates = function () {
  13576. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13577. return null;
  13578. }
  13579. var indices = this.pickedMesh.getIndices();
  13580. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  13581. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  13582. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  13583. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  13584. uv0 = uv0.scale(this.bu);
  13585. uv1 = uv1.scale(this.bv);
  13586. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  13587. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  13588. };
  13589. return PickingInfo;
  13590. })();
  13591. BABYLON.PickingInfo = PickingInfo;
  13592. })(BABYLON || (BABYLON = {}));
  13593. var BABYLON;
  13594. (function (BABYLON) {
  13595. var FilesInput = (function () {
  13596. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  13597. this.engine = p_engine;
  13598. this.canvas = p_canvas;
  13599. this.currentScene = p_scene;
  13600. this.sceneLoadedCallback = p_sceneLoadedCallback;
  13601. this.progressCallback = p_progressCallback;
  13602. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  13603. this.textureLoadingCallback = p_textureLoadingCallback;
  13604. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  13605. }
  13606. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  13607. var _this = this;
  13608. if (p_elementToMonitor) {
  13609. this.elementToMonitor = p_elementToMonitor;
  13610. this.elementToMonitor.addEventListener("dragenter", function (e) {
  13611. _this.drag(e);
  13612. }, false);
  13613. this.elementToMonitor.addEventListener("dragover", function (e) {
  13614. _this.drag(e);
  13615. }, false);
  13616. this.elementToMonitor.addEventListener("drop", function (e) {
  13617. _this.drop(e);
  13618. }, false);
  13619. }
  13620. };
  13621. FilesInput.prototype.renderFunction = function () {
  13622. if (this.additionnalRenderLoopLogicCallback) {
  13623. this.additionnalRenderLoopLogicCallback();
  13624. }
  13625. if (this.currentScene) {
  13626. if (this.textureLoadingCallback) {
  13627. var remaining = this.currentScene.getWaitingItemsCount();
  13628. if (remaining > 0) {
  13629. this.textureLoadingCallback(remaining);
  13630. }
  13631. }
  13632. this.currentScene.render();
  13633. }
  13634. };
  13635. FilesInput.prototype.drag = function (e) {
  13636. e.stopPropagation();
  13637. e.preventDefault();
  13638. };
  13639. FilesInput.prototype.drop = function (eventDrop) {
  13640. eventDrop.stopPropagation();
  13641. eventDrop.preventDefault();
  13642. this.loadFiles(eventDrop);
  13643. };
  13644. FilesInput.prototype.loadFiles = function (event) {
  13645. var _this = this;
  13646. var that = this;
  13647. if (this.startingProcessingFilesCallback)
  13648. this.startingProcessingFilesCallback();
  13649. var sceneFileToLoad;
  13650. var filesToLoad;
  13651. if (event && event.dataTransfer && event.dataTransfer.files) {
  13652. filesToLoad = event.dataTransfer.files;
  13653. }
  13654. if (event && event.target && event.target.files) {
  13655. filesToLoad = event.target.files;
  13656. }
  13657. if (filesToLoad && filesToLoad.length > 0) {
  13658. for (var i = 0; i < filesToLoad.length; i++) {
  13659. switch (filesToLoad[i].type) {
  13660. case "image/jpeg":
  13661. case "image/png":
  13662. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  13663. break;
  13664. case "image/targa":
  13665. case "image/vnd.ms-dds":
  13666. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  13667. break;
  13668. default:
  13669. 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) {
  13670. sceneFileToLoad = filesToLoad[i];
  13671. }
  13672. break;
  13673. }
  13674. }
  13675. if (sceneFileToLoad) {
  13676. if (this.currentScene) {
  13677. this.engine.stopRenderLoop();
  13678. this.currentScene.dispose();
  13679. }
  13680. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  13681. that.currentScene = newScene;
  13682. that.currentScene.executeWhenReady(function () {
  13683. if (that.currentScene.activeCamera) {
  13684. that.currentScene.activeCamera.attachControl(that.canvas);
  13685. }
  13686. if (that.sceneLoadedCallback) {
  13687. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  13688. }
  13689. that.engine.runRenderLoop(function () {
  13690. that.renderFunction();
  13691. });
  13692. });
  13693. }, function (progress) {
  13694. if (_this.progressCallback) {
  13695. _this.progressCallback(progress);
  13696. }
  13697. });
  13698. } else {
  13699. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  13700. }
  13701. }
  13702. };
  13703. FilesInput.FilesTextures = new Array();
  13704. FilesInput.FilesToLoad = new Array();
  13705. return FilesInput;
  13706. })();
  13707. BABYLON.FilesInput = FilesInput;
  13708. })(BABYLON || (BABYLON = {}));
  13709. var BABYLON;
  13710. (function (BABYLON) {
  13711. var OimoJSPlugin = (function () {
  13712. function OimoJSPlugin() {
  13713. this._registeredMeshes = [];
  13714. /**
  13715. * Update the body position according to the mesh position
  13716. * @param mesh
  13717. */
  13718. this.updateBodyPosition = function (mesh) {
  13719. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13720. var registeredMesh = this._registeredMeshes[index];
  13721. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13722. var body = registeredMesh.body.body;
  13723. mesh.computeWorldMatrix(true);
  13724. var center = mesh.getBoundingInfo().boundingBox.center;
  13725. body.setPosition(center.x, center.y, center.z);
  13726. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  13727. return;
  13728. }
  13729. if (registeredMesh.mesh.parent === mesh) {
  13730. mesh.computeWorldMatrix(true);
  13731. registeredMesh.mesh.computeWorldMatrix(true);
  13732. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  13733. var absoluteRotation = mesh.rotation;
  13734. body = registeredMesh.body.body;
  13735. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  13736. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  13737. return;
  13738. }
  13739. }
  13740. };
  13741. }
  13742. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  13743. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  13744. };
  13745. OimoJSPlugin.prototype.initialize = function (iterations) {
  13746. this._world = new OIMO.World();
  13747. this._world.clear();
  13748. };
  13749. OimoJSPlugin.prototype.setGravity = function (gravity) {
  13750. this._world.gravity = gravity;
  13751. };
  13752. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  13753. var body = null;
  13754. this.unregisterMesh(mesh);
  13755. mesh.computeWorldMatrix(true);
  13756. switch (impostor) {
  13757. case BABYLON.PhysicsEngine.SphereImpostor:
  13758. var bbox = mesh.getBoundingInfo().boundingBox;
  13759. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  13760. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  13761. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  13762. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  13763. var deltaPosition = mesh.position.subtract(bbox.center);
  13764. body = new OIMO.Body({
  13765. type: 'sphere',
  13766. size: [size],
  13767. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  13768. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  13769. move: options.mass != 0,
  13770. config: [options.mass, options.friction, options.restitution],
  13771. world: this._world
  13772. });
  13773. this._registeredMeshes.push({
  13774. mesh: mesh,
  13775. body: body,
  13776. delta: deltaPosition
  13777. });
  13778. break;
  13779. case BABYLON.PhysicsEngine.PlaneImpostor:
  13780. case BABYLON.PhysicsEngine.BoxImpostor:
  13781. bbox = mesh.getBoundingInfo().boundingBox;
  13782. var min = bbox.minimumWorld;
  13783. var max = bbox.maximumWorld;
  13784. var box = max.subtract(min);
  13785. var sizeX = this._checkWithEpsilon(box.x);
  13786. var sizeY = this._checkWithEpsilon(box.y);
  13787. var sizeZ = this._checkWithEpsilon(box.z);
  13788. var deltaPosition = mesh.position.subtract(bbox.center);
  13789. body = new OIMO.Body({
  13790. type: 'box',
  13791. size: [sizeX, sizeY, sizeZ],
  13792. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  13793. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  13794. move: options.mass != 0,
  13795. config: [options.mass, options.friction, options.restitution],
  13796. world: this._world
  13797. });
  13798. this._registeredMeshes.push({
  13799. mesh: mesh,
  13800. body: body,
  13801. delta: deltaPosition
  13802. });
  13803. break;
  13804. }
  13805. return body;
  13806. };
  13807. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  13808. var types = [], sizes = [], positions = [], rotations = [];
  13809. var initialMesh = parts[0].mesh;
  13810. for (var index = 0; index < parts.length; index++) {
  13811. var part = parts[index];
  13812. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  13813. types.push(bodyParameters.type);
  13814. sizes.push.apply(sizes, bodyParameters.size);
  13815. positions.push.apply(positions, bodyParameters.pos);
  13816. rotations.push.apply(rotations, bodyParameters.rot);
  13817. }
  13818. var body = new OIMO.Body({
  13819. type: types,
  13820. size: sizes,
  13821. pos: positions,
  13822. rot: rotations,
  13823. move: options.mass != 0,
  13824. config: [options.mass, options.friction, options.restitution],
  13825. world: this._world
  13826. });
  13827. this._registeredMeshes.push({
  13828. mesh: initialMesh,
  13829. body: body
  13830. });
  13831. return body;
  13832. };
  13833. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  13834. var bodyParameters = null;
  13835. var mesh = part.mesh;
  13836. switch (part.impostor) {
  13837. case BABYLON.PhysicsEngine.SphereImpostor:
  13838. var bbox = mesh.getBoundingInfo().boundingBox;
  13839. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  13840. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  13841. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  13842. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  13843. bodyParameters = {
  13844. type: 'sphere',
  13845. /* bug with oimo : sphere needs 3 sizes in this case */
  13846. size: [size, -1, -1],
  13847. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  13848. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  13849. };
  13850. break;
  13851. case BABYLON.PhysicsEngine.PlaneImpostor:
  13852. case BABYLON.PhysicsEngine.BoxImpostor:
  13853. bbox = mesh.getBoundingInfo().boundingBox;
  13854. var min = bbox.minimumWorld;
  13855. var max = bbox.maximumWorld;
  13856. var box = max.subtract(min);
  13857. var sizeX = this._checkWithEpsilon(box.x);
  13858. var sizeY = this._checkWithEpsilon(box.y);
  13859. var sizeZ = this._checkWithEpsilon(box.z);
  13860. var relativePosition = mesh.position;
  13861. bodyParameters = {
  13862. type: 'box',
  13863. size: [sizeX, sizeY, sizeZ],
  13864. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  13865. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  13866. };
  13867. break;
  13868. }
  13869. return bodyParameters;
  13870. };
  13871. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  13872. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13873. var registeredMesh = this._registeredMeshes[index];
  13874. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13875. if (registeredMesh.body) {
  13876. this._world.removeRigidBody(registeredMesh.body.body);
  13877. this._unbindBody(registeredMesh.body);
  13878. }
  13879. this._registeredMeshes.splice(index, 1);
  13880. return;
  13881. }
  13882. }
  13883. };
  13884. OimoJSPlugin.prototype._unbindBody = function (body) {
  13885. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13886. var registeredMesh = this._registeredMeshes[index];
  13887. if (registeredMesh.body === body) {
  13888. registeredMesh.body = null;
  13889. }
  13890. }
  13891. };
  13892. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  13893. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13894. var registeredMesh = this._registeredMeshes[index];
  13895. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  13896. var mass = registeredMesh.body.body.massInfo.mass;
  13897. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  13898. return;
  13899. }
  13900. }
  13901. };
  13902. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  13903. var body1 = null, body2 = null;
  13904. for (var index = 0; index < this._registeredMeshes.length; index++) {
  13905. var registeredMesh = this._registeredMeshes[index];
  13906. if (registeredMesh.mesh === mesh1) {
  13907. body1 = registeredMesh.body.body;
  13908. } else if (registeredMesh.mesh === mesh2) {
  13909. body2 = registeredMesh.body.body;
  13910. }
  13911. }
  13912. if (!body1 || !body2) {
  13913. return false;
  13914. }
  13915. if (!options) {
  13916. options = {};
  13917. }
  13918. new OIMO.Link({
  13919. type: options.type,
  13920. body1: body1,
  13921. body2: body2,
  13922. min: options.min,
  13923. max: options.max,
  13924. axe1: options.axe1,
  13925. axe2: options.axe2,
  13926. pos1: [pivot1.x, pivot1.y, pivot1.z],
  13927. pos2: [pivot2.x, pivot2.y, pivot2.z],
  13928. collision: options.collision,
  13929. spring: options.spring,
  13930. world: this._world
  13931. });
  13932. return true;
  13933. };
  13934. OimoJSPlugin.prototype.dispose = function () {
  13935. this._world.clear();
  13936. while (this._registeredMeshes.length) {
  13937. this.unregisterMesh(this._registeredMeshes[0].mesh);
  13938. }
  13939. };
  13940. OimoJSPlugin.prototype.isSupported = function () {
  13941. return OIMO !== undefined;
  13942. };
  13943. OimoJSPlugin.prototype._getLastShape = function (body) {
  13944. var lastShape = body.shapes;
  13945. while (lastShape.next) {
  13946. lastShape = lastShape.next;
  13947. }
  13948. return lastShape;
  13949. };
  13950. OimoJSPlugin.prototype.runOneStep = function (time) {
  13951. this._world.step();
  13952. var i = this._registeredMeshes.length;
  13953. var m;
  13954. while (i--) {
  13955. var body = this._registeredMeshes[i].body.body;
  13956. var mesh = this._registeredMeshes[i].mesh;
  13957. var delta = this._registeredMeshes[i].delta;
  13958. if (!body.sleeping) {
  13959. if (body.shapes.next) {
  13960. var parentShape = this._getLastShape(body);
  13961. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  13962. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  13963. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  13964. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  13965. if (!mesh.rotationQuaternion) {
  13966. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13967. }
  13968. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13969. } else {
  13970. m = body.getMatrix();
  13971. mtx = BABYLON.Matrix.FromArray(m);
  13972. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  13973. if (!delta) {
  13974. mesh.position.x = bodyX;
  13975. mesh.position.y = bodyY;
  13976. mesh.position.z = bodyZ;
  13977. } else {
  13978. mesh.position.x = bodyX + delta.x;
  13979. mesh.position.y = bodyY + delta.y;
  13980. mesh.position.z = bodyZ + delta.z;
  13981. }
  13982. if (!mesh.rotationQuaternion) {
  13983. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  13984. }
  13985. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  13986. }
  13987. }
  13988. }
  13989. };
  13990. return OimoJSPlugin;
  13991. })();
  13992. BABYLON.OimoJSPlugin = OimoJSPlugin;
  13993. })(BABYLON || (BABYLON = {}));
  13994. var BABYLON;
  13995. (function (BABYLON) {
  13996. var PhysicsEngine = (function () {
  13997. function PhysicsEngine(plugin) {
  13998. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  13999. }
  14000. PhysicsEngine.prototype._initialize = function (gravity) {
  14001. this._currentPlugin.initialize();
  14002. this._setGravity(gravity);
  14003. };
  14004. PhysicsEngine.prototype._runOneStep = function (delta) {
  14005. if (delta > 0.1) {
  14006. delta = 0.1;
  14007. } else if (delta <= 0) {
  14008. delta = 1.0 / 60.0;
  14009. }
  14010. this._currentPlugin.runOneStep(delta);
  14011. };
  14012. PhysicsEngine.prototype._setGravity = function (gravity) {
  14013. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  14014. this._currentPlugin.setGravity(this.gravity);
  14015. };
  14016. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  14017. return this._currentPlugin.registerMesh(mesh, impostor, options);
  14018. };
  14019. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  14020. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  14021. };
  14022. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  14023. this._currentPlugin.unregisterMesh(mesh);
  14024. };
  14025. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  14026. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  14027. };
  14028. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  14029. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  14030. };
  14031. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  14032. this._currentPlugin.updateBodyPosition(mesh);
  14033. };
  14034. PhysicsEngine.prototype.dispose = function () {
  14035. this._currentPlugin.dispose();
  14036. };
  14037. PhysicsEngine.prototype.isSupported = function () {
  14038. return this._currentPlugin.isSupported();
  14039. };
  14040. PhysicsEngine.NoImpostor = 0;
  14041. PhysicsEngine.SphereImpostor = 1;
  14042. PhysicsEngine.BoxImpostor = 2;
  14043. PhysicsEngine.PlaneImpostor = 3;
  14044. PhysicsEngine.MeshImpostor = 4;
  14045. PhysicsEngine.CapsuleImpostor = 5;
  14046. PhysicsEngine.ConeImpostor = 6;
  14047. PhysicsEngine.CylinderImpostor = 7;
  14048. PhysicsEngine.ConvexHullImpostor = 8;
  14049. PhysicsEngine.Epsilon = 0.001;
  14050. return PhysicsEngine;
  14051. })();
  14052. BABYLON.PhysicsEngine = PhysicsEngine;
  14053. })(BABYLON || (BABYLON = {}));
  14054. var BABYLON;
  14055. (function (BABYLON) {
  14056. var serializeLight = function (light) {
  14057. var serializationObject = {};
  14058. serializationObject.name = light.name;
  14059. serializationObject.id = light.id;
  14060. serializationObject.tags = BABYLON.Tags.GetTags(light);
  14061. if (light instanceof BABYLON.PointLight) {
  14062. serializationObject.type = 0;
  14063. serializationObject.position = light.position.asArray();
  14064. } else if (light instanceof BABYLON.DirectionalLight) {
  14065. serializationObject.type = 1;
  14066. var directionalLight = light;
  14067. serializationObject.position = directionalLight.position.asArray();
  14068. serializationObject.direction = directionalLight.direction.asArray();
  14069. } else if (light instanceof BABYLON.SpotLight) {
  14070. serializationObject.type = 2;
  14071. var spotLight = light;
  14072. serializationObject.position = spotLight.position.asArray();
  14073. serializationObject.direction = spotLight.position.asArray();
  14074. serializationObject.angle = spotLight.angle;
  14075. serializationObject.exponent = spotLight.exponent;
  14076. } else if (light instanceof BABYLON.HemisphericLight) {
  14077. serializationObject.type = 3;
  14078. var hemisphericLight = light;
  14079. serializationObject.direction = hemisphericLight.direction.asArray();
  14080. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  14081. }
  14082. if (light.intensity) {
  14083. serializationObject.intensity = light.intensity;
  14084. }
  14085. serializationObject.range = light.range;
  14086. serializationObject.diffuse = light.diffuse.asArray();
  14087. serializationObject.specular = light.specular.asArray();
  14088. return serializationObject;
  14089. };
  14090. var serializeFresnelParameter = function (fresnelParameter) {
  14091. var serializationObject = {};
  14092. serializationObject.isEnabled = fresnelParameter.isEnabled;
  14093. serializationObject.leftColor = fresnelParameter.leftColor;
  14094. serializationObject.rightColor = fresnelParameter.rightColor;
  14095. serializationObject.bias = fresnelParameter.bias;
  14096. serializationObject.power = fresnelParameter.power;
  14097. return serializationObject;
  14098. };
  14099. var serializeCamera = function (camera) {
  14100. var serializationObject = {};
  14101. serializationObject.name = camera.name;
  14102. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  14103. serializationObject.id = camera.id;
  14104. serializationObject.position = camera.position.asArray();
  14105. if (camera.parent) {
  14106. serializationObject.parentId = camera.parent.id;
  14107. }
  14108. serializationObject.rotation = camera.rotation.asArray();
  14109. if (camera.lockedTarget && camera.lockedTarget.id) {
  14110. serializationObject.lockedTargetId = camera.lockedTarget.id;
  14111. }
  14112. serializationObject.fov = camera.fov;
  14113. serializationObject.minZ = camera.minZ;
  14114. serializationObject.maxZ = camera.maxZ;
  14115. serializationObject.speed = camera.speed;
  14116. serializationObject.inertia = camera.inertia;
  14117. serializationObject.checkCollisions = camera.checkCollisions;
  14118. serializationObject.applyGravity = camera.applyGravity;
  14119. if (camera.ellipsoid) {
  14120. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  14121. }
  14122. appendAnimations(camera, serializationObject);
  14123. serializationObject.layerMask = camera.layerMask;
  14124. return serializationObject;
  14125. };
  14126. var appendAnimations = function (source, destination) {
  14127. if (source.animations) {
  14128. destination.animations = [];
  14129. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  14130. var animation = source.animations[animationIndex];
  14131. destination.animations.push(serializeAnimation(animation));
  14132. }
  14133. }
  14134. };
  14135. var serializeAnimation = function (animation) {
  14136. var serializationObject = {};
  14137. serializationObject.name = animation.name;
  14138. serializationObject.property = animation.targetProperty;
  14139. serializationObject.framePerSecond = animation.framePerSecond;
  14140. serializationObject.dataType = animation.dataType;
  14141. serializationObject.loopBehavior = animation.loopMode;
  14142. var dataType = animation.dataType;
  14143. serializationObject.keys = [];
  14144. var keys = animation.getKeys();
  14145. for (var index = 0; index < keys.length; index++) {
  14146. var animationKey = keys[index];
  14147. var key = {};
  14148. key.frame = animationKey.frame;
  14149. switch (dataType) {
  14150. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  14151. key.values = [animationKey.value];
  14152. break;
  14153. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  14154. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  14155. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  14156. key.values = animationKey.value.asArray();
  14157. break;
  14158. }
  14159. serializationObject.keys.push(key);
  14160. }
  14161. return serializationObject;
  14162. };
  14163. var serializeMultiMaterial = function (material) {
  14164. var serializationObject = {};
  14165. serializationObject.name = material.name;
  14166. serializationObject.id = material.id;
  14167. serializationObject.tags = BABYLON.Tags.GetTags(material);
  14168. serializationObject.materials = [];
  14169. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  14170. var subMat = material.subMaterials[matIndex];
  14171. if (subMat) {
  14172. serializationObject.materials.push(subMat.id);
  14173. } else {
  14174. serializationObject.materials.push(null);
  14175. }
  14176. }
  14177. return serializationObject;
  14178. };
  14179. var serializeMaterial = function (material) {
  14180. var serializationObject = {};
  14181. serializationObject.name = material.name;
  14182. serializationObject.ambient = material.ambientColor.asArray();
  14183. serializationObject.diffuse = material.diffuseColor.asArray();
  14184. serializationObject.specular = material.specularColor.asArray();
  14185. serializationObject.specularPower = material.specularPower;
  14186. serializationObject.emissive = material.emissiveColor.asArray();
  14187. serializationObject.alpha = material.alpha;
  14188. serializationObject.id = material.id;
  14189. serializationObject.tags = BABYLON.Tags.GetTags(material);
  14190. serializationObject.backFaceCulling = material.backFaceCulling;
  14191. if (material.diffuseTexture) {
  14192. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  14193. }
  14194. if (material.diffuseFresnelParameters) {
  14195. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  14196. }
  14197. if (material.ambientTexture) {
  14198. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  14199. }
  14200. if (material.opacityTexture) {
  14201. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  14202. }
  14203. if (material.opacityFresnelParameters) {
  14204. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  14205. }
  14206. if (material.reflectionTexture) {
  14207. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  14208. }
  14209. if (material.reflectionFresnelParameters) {
  14210. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  14211. }
  14212. if (material.emissiveTexture) {
  14213. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  14214. }
  14215. if (material.emissiveFresnelParameters) {
  14216. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  14217. }
  14218. if (material.specularTexture) {
  14219. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  14220. }
  14221. if (material.bumpTexture) {
  14222. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  14223. }
  14224. return serializationObject;
  14225. };
  14226. var serializeTexture = function (texture) {
  14227. var serializationObject = {};
  14228. if (!texture.name) {
  14229. return null;
  14230. }
  14231. if (texture instanceof BABYLON.CubeTexture) {
  14232. serializationObject.name = texture.name;
  14233. serializationObject.hasAlpha = texture.hasAlpha;
  14234. serializationObject.level = texture.level;
  14235. serializationObject.coordinatesMode = texture.coordinatesMode;
  14236. return serializationObject;
  14237. }
  14238. if (texture instanceof BABYLON.MirrorTexture) {
  14239. var mirrorTexture = texture;
  14240. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  14241. serializationObject.renderList = [];
  14242. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  14243. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  14244. }
  14245. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  14246. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  14247. var renderTargetTexture = texture;
  14248. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  14249. serializationObject.renderList = [];
  14250. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  14251. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  14252. }
  14253. }
  14254. var regularTexture = texture;
  14255. serializationObject.name = texture.name;
  14256. serializationObject.hasAlpha = texture.hasAlpha;
  14257. serializationObject.level = texture.level;
  14258. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  14259. serializationObject.coordinatesMode = texture.coordinatesMode;
  14260. serializationObject.uOffset = regularTexture.uOffset;
  14261. serializationObject.vOffset = regularTexture.vOffset;
  14262. serializationObject.uScale = regularTexture.uScale;
  14263. serializationObject.vScale = regularTexture.vScale;
  14264. serializationObject.uAng = regularTexture.uAng;
  14265. serializationObject.vAng = regularTexture.vAng;
  14266. serializationObject.wAng = regularTexture.wAng;
  14267. serializationObject.wrapU = texture.wrapU;
  14268. serializationObject.wrapV = texture.wrapV;
  14269. appendAnimations(texture, serializationObject);
  14270. return serializationObject;
  14271. };
  14272. var serializeSkeleton = function (skeleton) {
  14273. var serializationObject = {};
  14274. serializationObject.name = skeleton.name;
  14275. serializationObject.id = skeleton.id;
  14276. serializationObject.bones = [];
  14277. for (var index = 0; index < skeleton.bones.length; index++) {
  14278. var bone = skeleton.bones[index];
  14279. var serializedBone = {
  14280. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  14281. name: bone.name,
  14282. matrix: bone.getLocalMatrix().toArray()
  14283. };
  14284. serializationObject.bones.push(serializedBone);
  14285. if (bone.animations && bone.animations.length > 0) {
  14286. serializedBone.animation = serializeAnimation(bone.animations[0]);
  14287. }
  14288. }
  14289. return serializationObject;
  14290. };
  14291. var serializeParticleSystem = function (particleSystem) {
  14292. var serializationObject = {};
  14293. serializationObject.emitterId = particleSystem.emitter.id;
  14294. serializationObject.capacity = particleSystem.getCapacity();
  14295. if (particleSystem.particleTexture) {
  14296. serializationObject.textureName = particleSystem.particleTexture.name;
  14297. }
  14298. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  14299. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  14300. serializationObject.minSize = particleSystem.minSize;
  14301. serializationObject.maxSize = particleSystem.maxSize;
  14302. serializationObject.minLifeTime = particleSystem.minLifeTime;
  14303. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  14304. serializationObject.emitRate = particleSystem.emitRate;
  14305. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  14306. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  14307. serializationObject.gravity = particleSystem.gravity.asArray();
  14308. serializationObject.direction1 = particleSystem.direction1.asArray();
  14309. serializationObject.direction2 = particleSystem.direction2.asArray();
  14310. serializationObject.color1 = particleSystem.color1.asArray();
  14311. serializationObject.color2 = particleSystem.color2.asArray();
  14312. serializationObject.colorDead = particleSystem.colorDead.asArray();
  14313. serializationObject.updateSpeed = particleSystem.updateSpeed;
  14314. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  14315. serializationObject.textureMask = particleSystem.textureMask.asArray();
  14316. serializationObject.blendMode = particleSystem.blendMode;
  14317. return serializationObject;
  14318. };
  14319. var serializeLensFlareSystem = function (lensFlareSystem) {
  14320. var serializationObject = {};
  14321. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  14322. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  14323. serializationObject.flares = [];
  14324. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  14325. var flare = lensFlareSystem.lensFlares[index];
  14326. serializationObject.flares.push({
  14327. size: flare.size,
  14328. position: flare.position,
  14329. color: flare.color.asArray(),
  14330. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  14331. });
  14332. }
  14333. return serializationObject;
  14334. };
  14335. var serializeShadowGenerator = function (light) {
  14336. var serializationObject = {};
  14337. var shadowGenerator = light.getShadowGenerator();
  14338. serializationObject.lightId = light.id;
  14339. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  14340. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  14341. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  14342. serializationObject.renderList = [];
  14343. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  14344. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  14345. serializationObject.renderList.push(mesh.id);
  14346. }
  14347. return serializationObject;
  14348. };
  14349. var serializedGeometries = [];
  14350. var serializeGeometry = function (geometry, serializationGeometries) {
  14351. if (serializedGeometries[geometry.id]) {
  14352. return;
  14353. }
  14354. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  14355. serializationGeometries.boxes.push(serializeBox(geometry));
  14356. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  14357. serializationGeometries.spheres.push(serializeSphere(geometry));
  14358. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  14359. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  14360. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  14361. serializationGeometries.toruses.push(serializeTorus(geometry));
  14362. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  14363. serializationGeometries.grounds.push(serializeGround(geometry));
  14364. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  14365. serializationGeometries.planes.push(serializePlane(geometry));
  14366. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  14367. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  14368. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  14369. throw new Error("Unknow primitive type");
  14370. } else {
  14371. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  14372. }
  14373. serializedGeometries[geometry.id] = true;
  14374. };
  14375. var serializeGeometryBase = function (geometry) {
  14376. var serializationObject = {};
  14377. serializationObject.id = geometry.id;
  14378. if (BABYLON.Tags.HasTags(geometry)) {
  14379. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  14380. }
  14381. return serializationObject;
  14382. };
  14383. var serializeVertexData = function (vertexData) {
  14384. var serializationObject = serializeGeometryBase(vertexData);
  14385. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14386. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14387. }
  14388. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14389. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14390. }
  14391. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14392. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14393. }
  14394. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14395. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  14396. }
  14397. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14398. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  14399. }
  14400. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  14401. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  14402. serializationObject.matricesIndices._isExpanded = true;
  14403. }
  14404. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  14405. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  14406. }
  14407. serializationObject.indices = vertexData.getIndices();
  14408. return serializationObject;
  14409. };
  14410. var serializePrimitive = function (primitive) {
  14411. var serializationObject = serializeGeometryBase(primitive);
  14412. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  14413. return serializationObject;
  14414. };
  14415. var serializeBox = function (box) {
  14416. var serializationObject = serializePrimitive(box);
  14417. serializationObject.size = box.size;
  14418. return serializationObject;
  14419. };
  14420. var serializeSphere = function (sphere) {
  14421. var serializationObject = serializePrimitive(sphere);
  14422. serializationObject.segments = sphere.segments;
  14423. serializationObject.diameter = sphere.diameter;
  14424. return serializationObject;
  14425. };
  14426. var serializeCylinder = function (cylinder) {
  14427. var serializationObject = serializePrimitive(cylinder);
  14428. serializationObject.height = cylinder.height;
  14429. serializationObject.diameterTop = cylinder.diameterTop;
  14430. serializationObject.diameterBottom = cylinder.diameterBottom;
  14431. serializationObject.tessellation = cylinder.tessellation;
  14432. return serializationObject;
  14433. };
  14434. var serializeTorus = function (torus) {
  14435. var serializationObject = serializePrimitive(torus);
  14436. serializationObject.diameter = torus.diameter;
  14437. serializationObject.thickness = torus.thickness;
  14438. serializationObject.tessellation = torus.tessellation;
  14439. return serializationObject;
  14440. };
  14441. var serializeGround = function (ground) {
  14442. var serializationObject = serializePrimitive(ground);
  14443. serializationObject.width = ground.width;
  14444. serializationObject.height = ground.height;
  14445. serializationObject.subdivisions = ground.subdivisions;
  14446. return serializationObject;
  14447. };
  14448. var serializePlane = function (plane) {
  14449. var serializationObject = serializePrimitive(plane);
  14450. serializationObject.size = plane.size;
  14451. return serializationObject;
  14452. };
  14453. var serializeTorusKnot = function (torusKnot) {
  14454. var serializationObject = serializePrimitive(torusKnot);
  14455. serializationObject.radius = torusKnot.radius;
  14456. serializationObject.tube = torusKnot.tube;
  14457. serializationObject.radialSegments = torusKnot.radialSegments;
  14458. serializationObject.tubularSegments = torusKnot.tubularSegments;
  14459. serializationObject.p = torusKnot.p;
  14460. serializationObject.q = torusKnot.q;
  14461. return serializationObject;
  14462. };
  14463. var serializeMesh = function (mesh, serializationScene) {
  14464. var serializationObject = {};
  14465. serializationObject.name = mesh.name;
  14466. serializationObject.id = mesh.id;
  14467. if (BABYLON.Tags.HasTags(mesh)) {
  14468. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  14469. }
  14470. serializationObject.position = mesh.position.asArray();
  14471. if (mesh.rotationQuaternion) {
  14472. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  14473. } else if (mesh.rotation) {
  14474. serializationObject.rotation = mesh.rotation.asArray();
  14475. }
  14476. serializationObject.scaling = mesh.scaling.asArray();
  14477. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  14478. serializationObject.isEnabled = mesh.isEnabled();
  14479. serializationObject.isVisible = mesh.isVisible;
  14480. serializationObject.infiniteDistance = mesh.infiniteDistance;
  14481. serializationObject.pickable = mesh.isPickable;
  14482. serializationObject.receiveShadows = mesh.receiveShadows;
  14483. serializationObject.billboardMode = mesh.billboardMode;
  14484. serializationObject.visibility = mesh.visibility;
  14485. serializationObject.checkCollisions = mesh.checkCollisions;
  14486. if (mesh.parent) {
  14487. serializationObject.parentId = mesh.parent.id;
  14488. }
  14489. var geometry = mesh._geometry;
  14490. if (geometry) {
  14491. var geometryId = geometry.id;
  14492. serializationObject.geometryId = geometryId;
  14493. if (!mesh.getScene().getGeometryByID(geometryId)) {
  14494. serializeGeometry(geometry, serializationScene.geometries);
  14495. }
  14496. serializationObject.subMeshes = [];
  14497. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  14498. var subMesh = mesh.subMeshes[subIndex];
  14499. serializationObject.subMeshes.push({
  14500. materialIndex: subMesh.materialIndex,
  14501. verticesStart: subMesh.verticesStart,
  14502. verticesCount: subMesh.verticesCount,
  14503. indexStart: subMesh.indexStart,
  14504. indexCount: subMesh.indexCount
  14505. });
  14506. }
  14507. }
  14508. if (mesh.material) {
  14509. serializationObject.materialId = mesh.material.id;
  14510. } else {
  14511. mesh.material = null;
  14512. }
  14513. if (mesh.skeleton) {
  14514. serializationObject.skeletonId = mesh.skeleton.id;
  14515. }
  14516. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  14517. serializationObject.physicsMass = mesh.getPhysicsMass();
  14518. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  14519. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  14520. switch (mesh.getPhysicsImpostor()) {
  14521. case BABYLON.PhysicsEngine.BoxImpostor:
  14522. serializationObject.physicsImpostor = 1;
  14523. break;
  14524. case BABYLON.PhysicsEngine.SphereImpostor:
  14525. serializationObject.physicsImpostor = 2;
  14526. break;
  14527. }
  14528. }
  14529. serializationObject.instances = [];
  14530. for (var index = 0; index < mesh.instances.length; index++) {
  14531. var instance = mesh.instances[index];
  14532. var serializationInstance = {
  14533. name: instance.name,
  14534. position: instance.position,
  14535. rotation: instance.rotation,
  14536. rotationQuaternion: instance.rotationQuaternion,
  14537. scaling: instance.scaling
  14538. };
  14539. serializationObject.instances.push(serializationInstance);
  14540. appendAnimations(instance, serializationInstance);
  14541. }
  14542. appendAnimations(mesh, serializationObject);
  14543. serializationObject.layerMask = mesh.layerMask;
  14544. return serializationObject;
  14545. };
  14546. var SceneSerializer = (function () {
  14547. function SceneSerializer() {
  14548. }
  14549. SceneSerializer.Serialize = function (scene) {
  14550. var serializationObject = {};
  14551. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  14552. serializationObject.autoClear = scene.autoClear;
  14553. serializationObject.clearColor = scene.clearColor.asArray();
  14554. serializationObject.ambientColor = scene.ambientColor.asArray();
  14555. serializationObject.gravity = scene.gravity.asArray();
  14556. if (scene.fogMode && scene.fogMode !== 0) {
  14557. serializationObject.fogMode = scene.fogMode;
  14558. serializationObject.fogColor = scene.fogColor.asArray();
  14559. serializationObject.fogStart = scene.fogStart;
  14560. serializationObject.fogEnd = scene.fogEnd;
  14561. serializationObject.fogDensity = scene.fogDensity;
  14562. }
  14563. serializationObject.lights = [];
  14564. for (var index = 0; index < scene.lights.length; index++) {
  14565. var light = scene.lights[index];
  14566. serializationObject.lights.push(serializeLight(light));
  14567. }
  14568. serializationObject.cameras = [];
  14569. for (index = 0; index < scene.cameras.length; index++) {
  14570. var camera = scene.cameras[index];
  14571. if (camera instanceof BABYLON.FreeCamera) {
  14572. serializationObject.cameras.push(serializeCamera(camera));
  14573. }
  14574. }
  14575. if (scene.activeCamera) {
  14576. serializationObject.activeCameraID = scene.activeCamera.id;
  14577. }
  14578. serializationObject.materials = [];
  14579. serializationObject.multiMaterials = [];
  14580. for (index = 0; index < scene.materials.length; index++) {
  14581. var material = scene.materials[index];
  14582. if (material instanceof BABYLON.StandardMaterial) {
  14583. serializationObject.materials.push(serializeMaterial(material));
  14584. } else if (material instanceof BABYLON.MultiMaterial) {
  14585. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  14586. }
  14587. }
  14588. serializationObject.skeletons = [];
  14589. for (index = 0; index < scene.skeletons.length; index++) {
  14590. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  14591. }
  14592. serializationObject.geometries = {};
  14593. serializationObject.geometries.boxes = [];
  14594. serializationObject.geometries.spheres = [];
  14595. serializationObject.geometries.cylinders = [];
  14596. serializationObject.geometries.toruses = [];
  14597. serializationObject.geometries.grounds = [];
  14598. serializationObject.geometries.planes = [];
  14599. serializationObject.geometries.torusKnots = [];
  14600. serializationObject.geometries.vertexData = [];
  14601. serializedGeometries = [];
  14602. var geometries = scene.getGeometries();
  14603. for (var index = 0; index < geometries.length; index++) {
  14604. var geometry = geometries[index];
  14605. if (geometry.isReady()) {
  14606. serializeGeometry(geometry, serializationObject.geometries);
  14607. }
  14608. }
  14609. serializationObject.meshes = [];
  14610. for (index = 0; index < scene.meshes.length; index++) {
  14611. var abstractMesh = scene.meshes[index];
  14612. if (abstractMesh instanceof BABYLON.Mesh) {
  14613. var mesh = abstractMesh;
  14614. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  14615. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  14616. }
  14617. }
  14618. }
  14619. serializationObject.particleSystems = [];
  14620. for (index = 0; index < scene.particleSystems.length; index++) {
  14621. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  14622. }
  14623. serializationObject.lensFlareSystems = [];
  14624. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  14625. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  14626. }
  14627. serializationObject.shadowGenerators = [];
  14628. for (index = 0; index < scene.lights.length; index++) {
  14629. light = scene.lights[index];
  14630. if (light.getShadowGenerator()) {
  14631. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  14632. }
  14633. }
  14634. return serializationObject;
  14635. };
  14636. return SceneSerializer;
  14637. })();
  14638. BABYLON.SceneSerializer = SceneSerializer;
  14639. })(BABYLON || (BABYLON = {}));
  14640. var BABYLON;
  14641. (function (BABYLON) {
  14642. var SceneLoader = (function () {
  14643. function SceneLoader() {
  14644. }
  14645. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  14646. get: function () {
  14647. return SceneLoader._ForceFullSceneLoadingForIncremental;
  14648. },
  14649. set: function (value) {
  14650. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  14651. },
  14652. enumerable: true,
  14653. configurable: true
  14654. });
  14655. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  14656. get: function () {
  14657. return SceneLoader._ShowLoadingScreen;
  14658. },
  14659. set: function (value) {
  14660. SceneLoader._ShowLoadingScreen = value;
  14661. },
  14662. enumerable: true,
  14663. configurable: true
  14664. });
  14665. SceneLoader._getPluginForFilename = function (sceneFilename) {
  14666. var dotPosition = sceneFilename.lastIndexOf(".");
  14667. var queryStringPosition = sceneFilename.indexOf("?");
  14668. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  14669. for (var index = 0; index < this._registeredPlugins.length; index++) {
  14670. var plugin = this._registeredPlugins[index];
  14671. if (plugin.extensions.indexOf(extension) !== -1) {
  14672. return plugin;
  14673. }
  14674. }
  14675. return this._registeredPlugins[this._registeredPlugins.length - 1];
  14676. };
  14677. SceneLoader.RegisterPlugin = function (plugin) {
  14678. plugin.extensions = plugin.extensions.toLowerCase();
  14679. SceneLoader._registeredPlugins.push(plugin);
  14680. };
  14681. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  14682. var _this = this;
  14683. var manifestChecked = function (success) {
  14684. scene.database = database;
  14685. var plugin = _this._getPluginForFilename(sceneFilename);
  14686. var importMeshFromData = function (data) {
  14687. var meshes = [];
  14688. var particleSystems = [];
  14689. var skeletons = [];
  14690. try {
  14691. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  14692. if (onerror) {
  14693. onerror(scene);
  14694. }
  14695. return;
  14696. }
  14697. } catch (e) {
  14698. if (onerror) {
  14699. onerror(scene);
  14700. }
  14701. return;
  14702. }
  14703. if (onsuccess) {
  14704. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  14705. onsuccess(meshes, particleSystems, skeletons);
  14706. }
  14707. };
  14708. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  14709. importMeshFromData(sceneFilename.substr(5));
  14710. return;
  14711. }
  14712. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  14713. importMeshFromData(data);
  14714. }, progressCallBack, database);
  14715. };
  14716. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  14717. };
  14718. /**
  14719. * Load a scene
  14720. * @param rootUrl a string that defines the root url for scene and resources
  14721. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  14722. * @param engine is the instance of BABYLON.Engine to use to create the scene
  14723. */
  14724. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  14725. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  14726. };
  14727. /**
  14728. * Append a scene
  14729. * @param rootUrl a string that defines the root url for scene and resources
  14730. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  14731. * @param scene is the instance of BABYLON.Scene to append to
  14732. */
  14733. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  14734. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  14735. var database;
  14736. if (SceneLoader.ShowLoadingScreen) {
  14737. scene.getEngine().displayLoadingUI();
  14738. }
  14739. var loadSceneFromData = function (data) {
  14740. scene.database = database;
  14741. if (!plugin.load(scene, data, rootUrl)) {
  14742. if (onerror) {
  14743. onerror(scene);
  14744. }
  14745. scene.getEngine().hideLoadingUI();
  14746. return;
  14747. }
  14748. if (onsuccess) {
  14749. onsuccess(scene);
  14750. }
  14751. if (SceneLoader.ShowLoadingScreen) {
  14752. scene.executeWhenReady(function () {
  14753. scene.getEngine().hideLoadingUI();
  14754. });
  14755. }
  14756. };
  14757. var manifestChecked = function (success) {
  14758. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  14759. };
  14760. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  14761. loadSceneFromData(sceneFilename.substr(5));
  14762. return;
  14763. }
  14764. if (rootUrl.indexOf("file:") === -1) {
  14765. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  14766. } else {
  14767. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  14768. }
  14769. };
  14770. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  14771. SceneLoader._ShowLoadingScreen = true;
  14772. SceneLoader._registeredPlugins = new Array();
  14773. return SceneLoader;
  14774. })();
  14775. BABYLON.SceneLoader = SceneLoader;
  14776. ;
  14777. })(BABYLON || (BABYLON = {}));
  14778. var BABYLON;
  14779. (function (BABYLON) {
  14780. (function (Internals) {
  14781. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  14782. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  14783. texture.name = parsedTexture.name;
  14784. texture.hasAlpha = parsedTexture.hasAlpha;
  14785. texture.level = parsedTexture.level;
  14786. texture.coordinatesMode = parsedTexture.coordinatesMode;
  14787. return texture;
  14788. };
  14789. var loadTexture = function (rootUrl, parsedTexture, scene) {
  14790. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  14791. return null;
  14792. }
  14793. if (parsedTexture.isCube) {
  14794. return loadCubeTexture(rootUrl, parsedTexture, scene);
  14795. }
  14796. var texture;
  14797. if (parsedTexture.mirrorPlane) {
  14798. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  14799. texture._waitingRenderList = parsedTexture.renderList;
  14800. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  14801. } else if (parsedTexture.isRenderTarget) {
  14802. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  14803. texture._waitingRenderList = parsedTexture.renderList;
  14804. } else {
  14805. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  14806. }
  14807. texture.name = parsedTexture.name;
  14808. texture.hasAlpha = parsedTexture.hasAlpha;
  14809. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  14810. texture.level = parsedTexture.level;
  14811. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  14812. texture.coordinatesMode = parsedTexture.coordinatesMode;
  14813. texture.uOffset = parsedTexture.uOffset;
  14814. texture.vOffset = parsedTexture.vOffset;
  14815. texture.uScale = parsedTexture.uScale;
  14816. texture.vScale = parsedTexture.vScale;
  14817. texture.uAng = parsedTexture.uAng;
  14818. texture.vAng = parsedTexture.vAng;
  14819. texture.wAng = parsedTexture.wAng;
  14820. texture.wrapU = parsedTexture.wrapU;
  14821. texture.wrapV = parsedTexture.wrapV;
  14822. if (parsedTexture.animations) {
  14823. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  14824. var parsedAnimation = parsedTexture.animations[animationIndex];
  14825. texture.animations.push(parseAnimation(parsedAnimation));
  14826. }
  14827. }
  14828. return texture;
  14829. };
  14830. var parseSkeleton = function (parsedSkeleton, scene) {
  14831. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  14832. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  14833. var parsedBone = parsedSkeleton.bones[index];
  14834. var parentBone = null;
  14835. if (parsedBone.parentBoneIndex > -1) {
  14836. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  14837. }
  14838. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  14839. if (parsedBone.animation) {
  14840. bone.animations.push(parseAnimation(parsedBone.animation));
  14841. }
  14842. }
  14843. return skeleton;
  14844. };
  14845. var parseFresnelParameters = function (parsedFresnelParameters) {
  14846. var fresnelParameters = new BABYLON.FresnelParameters();
  14847. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  14848. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  14849. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  14850. fresnelParameters.bias = parsedFresnelParameters.bias;
  14851. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  14852. return fresnelParameters;
  14853. };
  14854. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  14855. var material;
  14856. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  14857. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  14858. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  14859. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  14860. material.specularPower = parsedMaterial.specularPower;
  14861. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  14862. material.alpha = parsedMaterial.alpha;
  14863. material.id = parsedMaterial.id;
  14864. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  14865. material.backFaceCulling = parsedMaterial.backFaceCulling;
  14866. material.wireframe = parsedMaterial.wireframe;
  14867. if (parsedMaterial.diffuseTexture) {
  14868. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  14869. }
  14870. if (parsedMaterial.diffuseFresnelParameters) {
  14871. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  14872. }
  14873. if (parsedMaterial.ambientTexture) {
  14874. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  14875. }
  14876. if (parsedMaterial.opacityTexture) {
  14877. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  14878. }
  14879. if (parsedMaterial.opacityFresnelParameters) {
  14880. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  14881. }
  14882. if (parsedMaterial.reflectionTexture) {
  14883. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  14884. }
  14885. if (parsedMaterial.reflectionFresnelParameters) {
  14886. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  14887. }
  14888. if (parsedMaterial.emissiveTexture) {
  14889. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  14890. }
  14891. if (parsedMaterial.emissiveFresnelParameters) {
  14892. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  14893. }
  14894. if (parsedMaterial.specularTexture) {
  14895. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  14896. }
  14897. if (parsedMaterial.bumpTexture) {
  14898. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  14899. }
  14900. return material;
  14901. };
  14902. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  14903. for (var index = 0; index < parsedData.materials.length; index++) {
  14904. var parsedMaterial = parsedData.materials[index];
  14905. if (parsedMaterial.id === id) {
  14906. return parseMaterial(parsedMaterial, scene, rootUrl);
  14907. }
  14908. }
  14909. return null;
  14910. };
  14911. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  14912. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  14913. multiMaterial.id = parsedMultiMaterial.id;
  14914. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  14915. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  14916. var subMatId = parsedMultiMaterial.materials[matIndex];
  14917. if (subMatId) {
  14918. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  14919. } else {
  14920. multiMaterial.subMaterials.push(null);
  14921. }
  14922. }
  14923. return multiMaterial;
  14924. };
  14925. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  14926. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  14927. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  14928. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  14929. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  14930. var parsedFlare = parsedLensFlareSystem.flares[index];
  14931. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  14932. }
  14933. return lensFlareSystem;
  14934. };
  14935. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  14936. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  14937. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  14938. if (parsedParticleSystem.textureName) {
  14939. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  14940. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  14941. }
  14942. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  14943. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  14944. particleSystem.minSize = parsedParticleSystem.minSize;
  14945. particleSystem.maxSize = parsedParticleSystem.maxSize;
  14946. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  14947. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  14948. particleSystem.emitter = emitter;
  14949. particleSystem.emitRate = parsedParticleSystem.emitRate;
  14950. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  14951. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  14952. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  14953. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  14954. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  14955. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  14956. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  14957. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  14958. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  14959. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  14960. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  14961. particleSystem.blendMode = parsedParticleSystem.blendMode;
  14962. particleSystem.start();
  14963. return particleSystem;
  14964. };
  14965. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  14966. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  14967. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  14968. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  14969. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  14970. shadowGenerator.getShadowMap().renderList.push(mesh);
  14971. }
  14972. if (parsedShadowGenerator.usePoissonSampling) {
  14973. shadowGenerator.usePoissonSampling = true;
  14974. } else {
  14975. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  14976. }
  14977. return shadowGenerator;
  14978. };
  14979. var parseAnimation = function (parsedAnimation) {
  14980. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  14981. var dataType = parsedAnimation.dataType;
  14982. var keys = [];
  14983. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  14984. var key = parsedAnimation.keys[index];
  14985. var data;
  14986. switch (dataType) {
  14987. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  14988. data = key.values[0];
  14989. break;
  14990. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  14991. data = BABYLON.Quaternion.FromArray(key.values);
  14992. break;
  14993. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  14994. data = BABYLON.Matrix.FromArray(key.values);
  14995. break;
  14996. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  14997. default:
  14998. data = BABYLON.Vector3.FromArray(key.values);
  14999. break;
  15000. }
  15001. keys.push({
  15002. frame: key.frame,
  15003. value: data
  15004. });
  15005. }
  15006. animation.setKeys(keys);
  15007. return animation;
  15008. };
  15009. var parseLight = function (parsedLight, scene) {
  15010. var light;
  15011. switch (parsedLight.type) {
  15012. case 0:
  15013. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  15014. break;
  15015. case 1:
  15016. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  15017. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  15018. break;
  15019. case 2:
  15020. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  15021. break;
  15022. case 3:
  15023. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  15024. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  15025. break;
  15026. }
  15027. light.id = parsedLight.id;
  15028. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  15029. if (parsedLight.intensity !== undefined) {
  15030. light.intensity = parsedLight.intensity;
  15031. }
  15032. if (parsedLight.range) {
  15033. light.range = parsedLight.range;
  15034. }
  15035. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  15036. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  15037. if (parsedLight.excludedMeshesIds) {
  15038. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  15039. }
  15040. if (parsedLight.includedOnlyMeshesIds) {
  15041. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  15042. }
  15043. if (parsedLight.animations) {
  15044. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  15045. var parsedAnimation = parsedLight.animations[animationIndex];
  15046. light.animations.push(parseAnimation(parsedAnimation));
  15047. }
  15048. }
  15049. if (parsedLight.autoAnimate) {
  15050. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  15051. }
  15052. };
  15053. var parseCamera = function (parsedCamera, scene) {
  15054. var camera;
  15055. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  15056. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  15057. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  15058. var alpha = parsedCamera.alpha;
  15059. var beta = parsedCamera.beta;
  15060. var radius = parsedCamera.radius;
  15061. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  15062. var eye_space = parsedCamera.eye_space;
  15063. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  15064. } else {
  15065. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  15066. }
  15067. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  15068. var eye_space = parsedCamera.eye_space;
  15069. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  15070. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  15071. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  15072. } else if (parsedCamera.type === "FollowCamera") {
  15073. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  15074. camera.heightOffset = parsedCamera.heightOffset;
  15075. camera.radius = parsedCamera.radius;
  15076. camera.rotationOffset = parsedCamera.rotationOffset;
  15077. if (lockedTargetMesh)
  15078. camera.target = lockedTargetMesh;
  15079. } else if (parsedCamera.type === "GamepadCamera") {
  15080. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  15081. } else if (parsedCamera.type === "OculusCamera") {
  15082. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  15083. } else if (parsedCamera.type === "TouchCamera") {
  15084. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  15085. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  15086. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  15087. } else if (parsedCamera.type === "WebVRCamera") {
  15088. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  15089. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  15090. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  15091. } else {
  15092. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  15093. }
  15094. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  15095. camera.lockedTarget = lockedTargetMesh;
  15096. }
  15097. camera.id = parsedCamera.id;
  15098. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  15099. if (parsedCamera.parentId) {
  15100. camera._waitingParentId = parsedCamera.parentId;
  15101. }
  15102. if (parsedCamera.target) {
  15103. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15104. } else {
  15105. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  15106. }
  15107. camera.fov = parsedCamera.fov;
  15108. camera.minZ = parsedCamera.minZ;
  15109. camera.maxZ = parsedCamera.maxZ;
  15110. camera.speed = parsedCamera.speed;
  15111. camera.inertia = parsedCamera.inertia;
  15112. camera.checkCollisions = parsedCamera.checkCollisions;
  15113. camera.applyGravity = parsedCamera.applyGravity;
  15114. if (parsedCamera.ellipsoid) {
  15115. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  15116. }
  15117. if (parsedCamera.animations) {
  15118. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15119. var parsedAnimation = parsedCamera.animations[animationIndex];
  15120. camera.animations.push(parseAnimation(parsedAnimation));
  15121. }
  15122. }
  15123. if (parsedCamera.autoAnimate) {
  15124. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  15125. }
  15126. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  15127. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  15128. } else {
  15129. camera.layerMask = 0xFFFFFFFF;
  15130. }
  15131. return camera;
  15132. };
  15133. var parseGeometry = function (parsedGeometry, scene) {
  15134. var id = parsedGeometry.id;
  15135. return scene.getGeometryByID(id);
  15136. };
  15137. var parseBox = function (parsedBox, scene) {
  15138. if (parseGeometry(parsedBox, scene)) {
  15139. return null;
  15140. }
  15141. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  15142. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  15143. scene.pushGeometry(box, true);
  15144. return box;
  15145. };
  15146. var parseSphere = function (parsedSphere, scene) {
  15147. if (parseGeometry(parsedSphere, scene)) {
  15148. return null;
  15149. }
  15150. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  15151. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  15152. scene.pushGeometry(sphere, true);
  15153. return sphere;
  15154. };
  15155. var parseCylinder = function (parsedCylinder, scene) {
  15156. if (parseGeometry(parsedCylinder, scene)) {
  15157. return null;
  15158. }
  15159. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  15160. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  15161. scene.pushGeometry(cylinder, true);
  15162. return cylinder;
  15163. };
  15164. var parseTorus = function (parsedTorus, scene) {
  15165. if (parseGeometry(parsedTorus, scene)) {
  15166. return null;
  15167. }
  15168. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  15169. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  15170. scene.pushGeometry(torus, true);
  15171. return torus;
  15172. };
  15173. var parseGround = function (parsedGround, scene) {
  15174. if (parseGeometry(parsedGround, scene)) {
  15175. return null;
  15176. }
  15177. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  15178. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  15179. scene.pushGeometry(ground, true);
  15180. return ground;
  15181. };
  15182. var parsePlane = function (parsedPlane, scene) {
  15183. if (parseGeometry(parsedPlane, scene)) {
  15184. return null;
  15185. }
  15186. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  15187. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  15188. scene.pushGeometry(plane, true);
  15189. return plane;
  15190. };
  15191. var parseTorusKnot = function (parsedTorusKnot, scene) {
  15192. if (parseGeometry(parsedTorusKnot, scene)) {
  15193. return null;
  15194. }
  15195. 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);
  15196. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  15197. scene.pushGeometry(torusKnot, true);
  15198. return torusKnot;
  15199. };
  15200. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  15201. if (parseGeometry(parsedVertexData, scene)) {
  15202. return null;
  15203. }
  15204. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  15205. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  15206. if (parsedVertexData.delayLoadingFile) {
  15207. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15208. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  15209. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  15210. geometry._delayInfo = [];
  15211. if (parsedVertexData.hasUVs) {
  15212. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15213. }
  15214. if (parsedVertexData.hasUVs2) {
  15215. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15216. }
  15217. if (parsedVertexData.hasColors) {
  15218. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15219. }
  15220. if (parsedVertexData.hasMatricesIndices) {
  15221. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15222. }
  15223. if (parsedVertexData.hasMatricesWeights) {
  15224. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15225. }
  15226. geometry._delayLoadingFunction = importVertexData;
  15227. } else {
  15228. importVertexData(parsedVertexData, geometry);
  15229. }
  15230. scene.pushGeometry(geometry, true);
  15231. return geometry;
  15232. };
  15233. var parseMesh = function (parsedMesh, scene, rootUrl) {
  15234. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  15235. mesh.id = parsedMesh.id;
  15236. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15237. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15238. if (parsedMesh.rotationQuaternion) {
  15239. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15240. } else if (parsedMesh.rotation) {
  15241. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15242. }
  15243. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15244. if (parsedMesh.localMatrix) {
  15245. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15246. } else if (parsedMesh.pivotMatrix) {
  15247. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15248. }
  15249. mesh.setEnabled(parsedMesh.isEnabled);
  15250. mesh.isVisible = parsedMesh.isVisible;
  15251. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15252. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15253. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15254. if (parsedMesh.pickable !== undefined) {
  15255. mesh.isPickable = parsedMesh.pickable;
  15256. }
  15257. mesh.receiveShadows = parsedMesh.receiveShadows;
  15258. mesh.billboardMode = parsedMesh.billboardMode;
  15259. if (parsedMesh.visibility !== undefined) {
  15260. mesh.visibility = parsedMesh.visibility;
  15261. }
  15262. mesh.checkCollisions = parsedMesh.checkCollisions;
  15263. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15264. if (parsedMesh.parentId) {
  15265. mesh._waitingParentId = parsedMesh.parentId;
  15266. }
  15267. if (parsedMesh.delayLoadingFile) {
  15268. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15269. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15270. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15271. if (parsedMesh._binaryInfo) {
  15272. mesh._binaryInfo = parsedMesh._binaryInfo;
  15273. }
  15274. mesh._delayInfo = [];
  15275. if (parsedMesh.hasUVs) {
  15276. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15277. }
  15278. if (parsedMesh.hasUVs2) {
  15279. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15280. }
  15281. if (parsedMesh.hasColors) {
  15282. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15283. }
  15284. if (parsedMesh.hasMatricesIndices) {
  15285. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15286. }
  15287. if (parsedMesh.hasMatricesWeights) {
  15288. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15289. }
  15290. mesh._delayLoadingFunction = importGeometry;
  15291. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15292. mesh._checkDelayState();
  15293. }
  15294. } else {
  15295. importGeometry(parsedMesh, mesh);
  15296. }
  15297. if (parsedMesh.materialId) {
  15298. mesh.setMaterialByID(parsedMesh.materialId);
  15299. } else {
  15300. mesh.material = null;
  15301. }
  15302. if (parsedMesh.skeletonId > -1) {
  15303. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15304. }
  15305. if (parsedMesh.physicsImpostor) {
  15306. if (!scene.isPhysicsEnabled()) {
  15307. scene.enablePhysics();
  15308. }
  15309. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15310. }
  15311. if (parsedMesh.animations) {
  15312. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15313. var parsedAnimation = parsedMesh.animations[animationIndex];
  15314. mesh.animations.push(parseAnimation(parsedAnimation));
  15315. }
  15316. }
  15317. if (parsedMesh.autoAnimate) {
  15318. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15319. }
  15320. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15321. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15322. } else {
  15323. mesh.layerMask = 0xFFFFFFFF;
  15324. }
  15325. if (parsedMesh.instances) {
  15326. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15327. var parsedInstance = parsedMesh.instances[index];
  15328. var instance = mesh.createInstance(parsedInstance.name);
  15329. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  15330. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  15331. if (parsedInstance.rotationQuaternion) {
  15332. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  15333. } else if (parsedInstance.rotation) {
  15334. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  15335. }
  15336. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  15337. instance.checkCollisions = mesh.checkCollisions;
  15338. if (parsedMesh.animations) {
  15339. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15340. parsedAnimation = parsedMesh.animations[animationIndex];
  15341. instance.animations.push(parseAnimation(parsedAnimation));
  15342. }
  15343. }
  15344. }
  15345. }
  15346. return mesh;
  15347. };
  15348. var isDescendantOf = function (mesh, names, hierarchyIds) {
  15349. names = (names instanceof Array) ? names : [names];
  15350. for (var i in names) {
  15351. if (mesh.name === names[i]) {
  15352. hierarchyIds.push(mesh.id);
  15353. return true;
  15354. }
  15355. }
  15356. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  15357. hierarchyIds.push(mesh.id);
  15358. return true;
  15359. }
  15360. return false;
  15361. };
  15362. var importVertexData = function (parsedVertexData, geometry) {
  15363. var vertexData = new BABYLON.VertexData();
  15364. var positions = parsedVertexData.positions;
  15365. if (positions) {
  15366. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  15367. }
  15368. var normals = parsedVertexData.normals;
  15369. if (normals) {
  15370. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  15371. }
  15372. var uvs = parsedVertexData.uvs;
  15373. if (uvs) {
  15374. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  15375. }
  15376. var uv2s = parsedVertexData.uv2s;
  15377. if (uv2s) {
  15378. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  15379. }
  15380. var colors = parsedVertexData.colors;
  15381. if (colors) {
  15382. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  15383. }
  15384. var matricesIndices = parsedVertexData.matricesIndices;
  15385. if (matricesIndices) {
  15386. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  15387. }
  15388. var matricesWeights = parsedVertexData.matricesWeights;
  15389. if (matricesWeights) {
  15390. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  15391. }
  15392. var indices = parsedVertexData.indices;
  15393. if (indices) {
  15394. vertexData.indices = indices;
  15395. }
  15396. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  15397. };
  15398. var importGeometry = function (parsedGeometry, mesh) {
  15399. var scene = mesh.getScene();
  15400. var geometryId = parsedGeometry.geometryId;
  15401. if (geometryId) {
  15402. var geometry = scene.getGeometryByID(geometryId);
  15403. if (geometry) {
  15404. geometry.applyToMesh(mesh);
  15405. }
  15406. } else if (parsedGeometry instanceof ArrayBuffer) {
  15407. var binaryInfo = mesh._binaryInfo;
  15408. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  15409. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  15410. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  15411. }
  15412. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  15413. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  15414. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  15415. }
  15416. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  15417. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  15418. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  15419. }
  15420. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  15421. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  15422. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  15423. }
  15424. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  15425. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  15426. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  15427. }
  15428. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  15429. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  15430. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  15431. }
  15432. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  15433. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  15434. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  15435. }
  15436. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  15437. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  15438. mesh.setIndices(indicesData);
  15439. }
  15440. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  15441. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  15442. mesh.subMeshes = [];
  15443. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  15444. var materialIndex = subMeshesData[(i * 5) + 0];
  15445. var verticesStart = subMeshesData[(i * 5) + 1];
  15446. var verticesCount = subMeshesData[(i * 5) + 2];
  15447. var indexStart = subMeshesData[(i * 5) + 3];
  15448. var indexCount = subMeshesData[(i * 5) + 4];
  15449. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  15450. }
  15451. }
  15452. return;
  15453. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  15454. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  15455. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  15456. if (parsedGeometry.uvs) {
  15457. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  15458. }
  15459. if (parsedGeometry.uvs2) {
  15460. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  15461. }
  15462. if (parsedGeometry.colors) {
  15463. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, parsedGeometry.colors, false);
  15464. }
  15465. if (parsedGeometry.matricesIndices) {
  15466. if (!parsedGeometry.matricesIndices._isExpanded) {
  15467. var floatIndices = [];
  15468. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  15469. var matricesIndex = parsedGeometry.matricesIndices[i];
  15470. floatIndices.push(matricesIndex & 0x000000FF);
  15471. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  15472. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  15473. floatIndices.push(matricesIndex >> 24);
  15474. }
  15475. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  15476. } else {
  15477. delete parsedGeometry.matricesIndices._isExpanded;
  15478. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  15479. }
  15480. }
  15481. if (parsedGeometry.matricesWeights) {
  15482. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  15483. }
  15484. mesh.setIndices(parsedGeometry.indices);
  15485. }
  15486. if (parsedGeometry.subMeshes) {
  15487. mesh.subMeshes = [];
  15488. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  15489. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  15490. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  15491. }
  15492. }
  15493. if (mesh._shouldGenerateFlatShading) {
  15494. mesh.convertToFlatShadedMesh();
  15495. delete mesh._shouldGenerateFlatShading;
  15496. }
  15497. mesh.computeWorldMatrix(true);
  15498. if (scene._selectionOctree) {
  15499. scene._selectionOctree.addMesh(mesh);
  15500. }
  15501. };
  15502. BABYLON.SceneLoader.RegisterPlugin({
  15503. extensions: ".babylon",
  15504. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  15505. var parsedData = JSON.parse(data);
  15506. var loadedSkeletonsIds = [];
  15507. var loadedMaterialsIds = [];
  15508. var hierarchyIds = [];
  15509. for (var index = 0; index < parsedData.meshes.length; index++) {
  15510. var parsedMesh = parsedData.meshes[index];
  15511. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  15512. if (meshesNames instanceof Array) {
  15513. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  15514. }
  15515. if (parsedMesh.materialId) {
  15516. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  15517. if (!materialFound) {
  15518. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  15519. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  15520. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  15521. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  15522. var subMatId = parsedMultiMaterial.materials[matIndex];
  15523. loadedMaterialsIds.push(subMatId);
  15524. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  15525. }
  15526. loadedMaterialsIds.push(parsedMultiMaterial.id);
  15527. parseMultiMaterial(parsedMultiMaterial, scene);
  15528. materialFound = true;
  15529. break;
  15530. }
  15531. }
  15532. }
  15533. if (!materialFound) {
  15534. loadedMaterialsIds.push(parsedMesh.materialId);
  15535. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  15536. }
  15537. }
  15538. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  15539. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  15540. if (!skeletonAlreadyLoaded) {
  15541. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  15542. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  15543. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  15544. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  15545. loadedSkeletonsIds.push(parsedSkeleton.id);
  15546. }
  15547. }
  15548. }
  15549. }
  15550. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  15551. meshes.push(mesh);
  15552. }
  15553. }
  15554. for (index = 0; index < scene.meshes.length; index++) {
  15555. var currentMesh = scene.meshes[index];
  15556. if (currentMesh._waitingParentId) {
  15557. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  15558. currentMesh._waitingParentId = undefined;
  15559. }
  15560. }
  15561. if (parsedData.particleSystems) {
  15562. for (index = 0; index < parsedData.particleSystems.length; index++) {
  15563. var parsedParticleSystem = parsedData.particleSystems[index];
  15564. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  15565. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  15566. }
  15567. }
  15568. }
  15569. return true;
  15570. },
  15571. load: function (scene, data, rootUrl) {
  15572. var parsedData = JSON.parse(data);
  15573. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  15574. scene.autoClear = parsedData.autoClear;
  15575. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  15576. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  15577. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  15578. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  15579. scene.fogMode = parsedData.fogMode;
  15580. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  15581. scene.fogStart = parsedData.fogStart;
  15582. scene.fogEnd = parsedData.fogEnd;
  15583. scene.fogDensity = parsedData.fogDensity;
  15584. }
  15585. for (var index = 0; index < parsedData.lights.length; index++) {
  15586. var parsedLight = parsedData.lights[index];
  15587. parseLight(parsedLight, scene);
  15588. }
  15589. if (parsedData.materials) {
  15590. for (index = 0; index < parsedData.materials.length; index++) {
  15591. var parsedMaterial = parsedData.materials[index];
  15592. parseMaterial(parsedMaterial, scene, rootUrl);
  15593. }
  15594. }
  15595. if (parsedData.multiMaterials) {
  15596. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  15597. var parsedMultiMaterial = parsedData.multiMaterials[index];
  15598. parseMultiMaterial(parsedMultiMaterial, scene);
  15599. }
  15600. }
  15601. if (parsedData.skeletons) {
  15602. for (index = 0; index < parsedData.skeletons.length; index++) {
  15603. var parsedSkeleton = parsedData.skeletons[index];
  15604. parseSkeleton(parsedSkeleton, scene);
  15605. }
  15606. }
  15607. var geometries = parsedData.geometries;
  15608. if (geometries) {
  15609. var boxes = geometries.boxes;
  15610. if (boxes) {
  15611. for (index = 0; index < boxes.length; index++) {
  15612. var parsedBox = boxes[index];
  15613. parseBox(parsedBox, scene);
  15614. }
  15615. }
  15616. var spheres = geometries.spheres;
  15617. if (spheres) {
  15618. for (index = 0; index < spheres.length; index++) {
  15619. var parsedSphere = spheres[index];
  15620. parseSphere(parsedSphere, scene);
  15621. }
  15622. }
  15623. var cylinders = geometries.cylinders;
  15624. if (cylinders) {
  15625. for (index = 0; index < cylinders.length; index++) {
  15626. var parsedCylinder = cylinders[index];
  15627. parseCylinder(parsedCylinder, scene);
  15628. }
  15629. }
  15630. var toruses = geometries.toruses;
  15631. if (toruses) {
  15632. for (index = 0; index < toruses.length; index++) {
  15633. var parsedTorus = toruses[index];
  15634. parseTorus(parsedTorus, scene);
  15635. }
  15636. }
  15637. var grounds = geometries.grounds;
  15638. if (grounds) {
  15639. for (index = 0; index < grounds.length; index++) {
  15640. var parsedGround = grounds[index];
  15641. parseGround(parsedGround, scene);
  15642. }
  15643. }
  15644. var planes = geometries.planes;
  15645. if (planes) {
  15646. for (index = 0; index < planes.length; index++) {
  15647. var parsedPlane = planes[index];
  15648. parsePlane(parsedPlane, scene);
  15649. }
  15650. }
  15651. var torusKnots = geometries.torusKnots;
  15652. if (torusKnots) {
  15653. for (index = 0; index < torusKnots.length; index++) {
  15654. var parsedTorusKnot = torusKnots[index];
  15655. parseTorusKnot(parsedTorusKnot, scene);
  15656. }
  15657. }
  15658. var vertexData = geometries.vertexData;
  15659. if (vertexData) {
  15660. for (index = 0; index < vertexData.length; index++) {
  15661. var parsedVertexData = vertexData[index];
  15662. parseVertexData(parsedVertexData, scene, rootUrl);
  15663. }
  15664. }
  15665. }
  15666. for (index = 0; index < parsedData.meshes.length; index++) {
  15667. var parsedMesh = parsedData.meshes[index];
  15668. parseMesh(parsedMesh, scene, rootUrl);
  15669. }
  15670. for (index = 0; index < parsedData.cameras.length; index++) {
  15671. var parsedCamera = parsedData.cameras[index];
  15672. parseCamera(parsedCamera, scene);
  15673. }
  15674. if (parsedData.activeCameraID) {
  15675. scene.setActiveCameraByID(parsedData.activeCameraID);
  15676. }
  15677. for (index = 0; index < scene.cameras.length; index++) {
  15678. var camera = scene.cameras[index];
  15679. if (camera._waitingParentId) {
  15680. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  15681. camera._waitingParentId = undefined;
  15682. }
  15683. }
  15684. for (index = 0; index < scene.meshes.length; index++) {
  15685. var mesh = scene.meshes[index];
  15686. if (mesh._waitingParentId) {
  15687. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  15688. mesh._waitingParentId = undefined;
  15689. }
  15690. }
  15691. if (parsedData.particleSystems) {
  15692. for (index = 0; index < parsedData.particleSystems.length; index++) {
  15693. var parsedParticleSystem = parsedData.particleSystems[index];
  15694. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  15695. }
  15696. }
  15697. if (parsedData.lensFlareSystems) {
  15698. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  15699. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  15700. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  15701. }
  15702. }
  15703. if (parsedData.shadowGenerators) {
  15704. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  15705. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  15706. parseShadowGenerator(parsedShadowGenerator, scene);
  15707. }
  15708. }
  15709. return true;
  15710. }
  15711. });
  15712. })(BABYLON.Internals || (BABYLON.Internals = {}));
  15713. var Internals = BABYLON.Internals;
  15714. })(BABYLON || (BABYLON = {}));
  15715. var BABYLON;
  15716. (function (BABYLON) {
  15717. var currentCSGMeshId = 0;
  15718. var Vertex = (function () {
  15719. function Vertex(pos, normal, uv) {
  15720. this.pos = pos;
  15721. this.normal = normal;
  15722. this.uv = uv;
  15723. }
  15724. Vertex.prototype.clone = function () {
  15725. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  15726. };
  15727. Vertex.prototype.flip = function () {
  15728. this.normal = this.normal.scale(-1);
  15729. };
  15730. Vertex.prototype.interpolate = function (other, t) {
  15731. 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));
  15732. };
  15733. return Vertex;
  15734. })();
  15735. var Plane = (function () {
  15736. function Plane(normal, w) {
  15737. this.normal = normal;
  15738. this.w = w;
  15739. }
  15740. Plane.FromPoints = function (a, b, c) {
  15741. var v0 = c.subtract(a);
  15742. var v1 = b.subtract(a);
  15743. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  15744. return null;
  15745. }
  15746. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  15747. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  15748. };
  15749. Plane.prototype.clone = function () {
  15750. return new Plane(this.normal.clone(), this.w);
  15751. };
  15752. Plane.prototype.flip = function () {
  15753. this.normal.scaleInPlace(-1);
  15754. this.w = -this.w;
  15755. };
  15756. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  15757. var COPLANAR = 0;
  15758. var FRONT = 1;
  15759. var BACK = 2;
  15760. var SPANNING = 3;
  15761. var polygonType = 0;
  15762. var types = [];
  15763. for (var i = 0; i < polygon.vertices.length; i++) {
  15764. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  15765. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  15766. polygonType |= type;
  15767. types.push(type);
  15768. }
  15769. switch (polygonType) {
  15770. case COPLANAR:
  15771. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  15772. break;
  15773. case FRONT:
  15774. front.push(polygon);
  15775. break;
  15776. case BACK:
  15777. back.push(polygon);
  15778. break;
  15779. case SPANNING:
  15780. var f = [], b = [];
  15781. for (i = 0; i < polygon.vertices.length; i++) {
  15782. var j = (i + 1) % polygon.vertices.length;
  15783. var ti = types[i], tj = types[j];
  15784. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  15785. if (ti != BACK)
  15786. f.push(vi);
  15787. if (ti != FRONT)
  15788. b.push(ti != BACK ? vi.clone() : vi);
  15789. if ((ti | tj) == SPANNING) {
  15790. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  15791. var v = vi.interpolate(vj, t);
  15792. f.push(v);
  15793. b.push(v.clone());
  15794. }
  15795. }
  15796. if (f.length >= 3) {
  15797. var poly = new Polygon(f, polygon.shared);
  15798. if (poly.plane)
  15799. front.push(poly);
  15800. }
  15801. if (b.length >= 3) {
  15802. poly = new Polygon(b, polygon.shared);
  15803. if (poly.plane)
  15804. back.push(poly);
  15805. }
  15806. break;
  15807. }
  15808. };
  15809. Plane.EPSILON = 1e-5;
  15810. return Plane;
  15811. })();
  15812. var Polygon = (function () {
  15813. function Polygon(vertices, shared) {
  15814. this.vertices = vertices;
  15815. this.shared = shared;
  15816. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  15817. }
  15818. Polygon.prototype.clone = function () {
  15819. var vertices = this.vertices.map(function (v) {
  15820. return v.clone();
  15821. });
  15822. return new Polygon(vertices, this.shared);
  15823. };
  15824. Polygon.prototype.flip = function () {
  15825. this.vertices.reverse().map(function (v) {
  15826. v.flip();
  15827. });
  15828. this.plane.flip();
  15829. };
  15830. return Polygon;
  15831. })();
  15832. var Node = (function () {
  15833. function Node(polygons) {
  15834. this.plane = null;
  15835. this.front = null;
  15836. this.back = null;
  15837. this.polygons = [];
  15838. if (polygons) {
  15839. this.build(polygons);
  15840. }
  15841. }
  15842. Node.prototype.clone = function () {
  15843. var node = new Node();
  15844. node.plane = this.plane && this.plane.clone();
  15845. node.front = this.front && this.front.clone();
  15846. node.back = this.back && this.back.clone();
  15847. node.polygons = this.polygons.map(function (p) {
  15848. return p.clone();
  15849. });
  15850. return node;
  15851. };
  15852. Node.prototype.invert = function () {
  15853. for (var i = 0; i < this.polygons.length; i++) {
  15854. this.polygons[i].flip();
  15855. }
  15856. if (this.plane) {
  15857. this.plane.flip();
  15858. }
  15859. if (this.front) {
  15860. this.front.invert();
  15861. }
  15862. if (this.back) {
  15863. this.back.invert();
  15864. }
  15865. var temp = this.front;
  15866. this.front = this.back;
  15867. this.back = temp;
  15868. };
  15869. Node.prototype.clipPolygons = function (polygons) {
  15870. if (!this.plane)
  15871. return polygons.slice();
  15872. var front = [], back = [];
  15873. for (var i = 0; i < polygons.length; i++) {
  15874. this.plane.splitPolygon(polygons[i], front, back, front, back);
  15875. }
  15876. if (this.front) {
  15877. front = this.front.clipPolygons(front);
  15878. }
  15879. if (this.back) {
  15880. back = this.back.clipPolygons(back);
  15881. } else {
  15882. back = [];
  15883. }
  15884. return front.concat(back);
  15885. };
  15886. Node.prototype.clipTo = function (bsp) {
  15887. this.polygons = bsp.clipPolygons(this.polygons);
  15888. if (this.front)
  15889. this.front.clipTo(bsp);
  15890. if (this.back)
  15891. this.back.clipTo(bsp);
  15892. };
  15893. Node.prototype.allPolygons = function () {
  15894. var polygons = this.polygons.slice();
  15895. if (this.front)
  15896. polygons = polygons.concat(this.front.allPolygons());
  15897. if (this.back)
  15898. polygons = polygons.concat(this.back.allPolygons());
  15899. return polygons;
  15900. };
  15901. Node.prototype.build = function (polygons) {
  15902. if (!polygons.length)
  15903. return;
  15904. if (!this.plane)
  15905. this.plane = polygons[0].plane.clone();
  15906. var front = [], back = [];
  15907. for (var i = 0; i < polygons.length; i++) {
  15908. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  15909. }
  15910. if (front.length) {
  15911. if (!this.front)
  15912. this.front = new Node();
  15913. this.front.build(front);
  15914. }
  15915. if (back.length) {
  15916. if (!this.back)
  15917. this.back = new Node();
  15918. this.back.build(back);
  15919. }
  15920. };
  15921. return Node;
  15922. })();
  15923. var CSG = (function () {
  15924. function CSG() {
  15925. this.polygons = new Array();
  15926. }
  15927. CSG.FromMesh = function (mesh) {
  15928. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  15929. if (mesh instanceof BABYLON.Mesh) {
  15930. mesh.computeWorldMatrix(true);
  15931. var matrix = mesh.getWorldMatrix();
  15932. var meshPosition = mesh.position.clone();
  15933. var meshRotation = mesh.rotation.clone();
  15934. var meshScaling = mesh.scaling.clone();
  15935. } else {
  15936. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  15937. }
  15938. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15939. var subMeshes = mesh.subMeshes;
  15940. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  15941. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  15942. vertices = [];
  15943. for (var j = 0; j < 3; j++) {
  15944. normal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  15945. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  15946. position = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  15947. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, position);
  15948. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  15949. vertex = new Vertex(position, normal, uv);
  15950. vertices.push(vertex);
  15951. }
  15952. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  15953. if (polygon.plane)
  15954. polygons.push(polygon);
  15955. }
  15956. }
  15957. var csg = CSG.FromPolygons(polygons);
  15958. csg.matrix = matrix;
  15959. csg.position = meshPosition;
  15960. csg.rotation = meshRotation;
  15961. csg.scaling = meshScaling;
  15962. currentCSGMeshId++;
  15963. return csg;
  15964. };
  15965. CSG.FromPolygons = function (polygons) {
  15966. var csg = new BABYLON.CSG();
  15967. csg.polygons = polygons;
  15968. return csg;
  15969. };
  15970. CSG.prototype.clone = function () {
  15971. var csg = new BABYLON.CSG();
  15972. csg.polygons = this.polygons.map(function (p) {
  15973. return p.clone();
  15974. });
  15975. csg.copyTransformAttributes(this);
  15976. return csg;
  15977. };
  15978. CSG.prototype.toPolygons = function () {
  15979. return this.polygons;
  15980. };
  15981. CSG.prototype.union = function (csg) {
  15982. var a = new Node(this.clone().polygons);
  15983. var b = new Node(csg.clone().polygons);
  15984. a.clipTo(b);
  15985. b.clipTo(a);
  15986. b.invert();
  15987. b.clipTo(a);
  15988. b.invert();
  15989. a.build(b.allPolygons());
  15990. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  15991. };
  15992. CSG.prototype.unionInPlace = function (csg) {
  15993. var a = new Node(this.polygons);
  15994. var b = new Node(csg.polygons);
  15995. a.clipTo(b);
  15996. b.clipTo(a);
  15997. b.invert();
  15998. b.clipTo(a);
  15999. b.invert();
  16000. a.build(b.allPolygons());
  16001. this.polygons = a.allPolygons();
  16002. };
  16003. CSG.prototype.subtract = function (csg) {
  16004. var a = new Node(this.clone().polygons);
  16005. var b = new Node(csg.clone().polygons);
  16006. a.invert();
  16007. a.clipTo(b);
  16008. b.clipTo(a);
  16009. b.invert();
  16010. b.clipTo(a);
  16011. b.invert();
  16012. a.build(b.allPolygons());
  16013. a.invert();
  16014. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  16015. };
  16016. CSG.prototype.subtractInPlace = function (csg) {
  16017. var a = new Node(this.polygons);
  16018. var b = new Node(csg.polygons);
  16019. a.invert();
  16020. a.clipTo(b);
  16021. b.clipTo(a);
  16022. b.invert();
  16023. b.clipTo(a);
  16024. b.invert();
  16025. a.build(b.allPolygons());
  16026. a.invert();
  16027. this.polygons = a.allPolygons();
  16028. };
  16029. CSG.prototype.intersect = function (csg) {
  16030. var a = new Node(this.clone().polygons);
  16031. var b = new Node(csg.clone().polygons);
  16032. a.invert();
  16033. b.clipTo(a);
  16034. b.invert();
  16035. a.clipTo(b);
  16036. b.clipTo(a);
  16037. a.build(b.allPolygons());
  16038. a.invert();
  16039. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  16040. };
  16041. CSG.prototype.intersectInPlace = function (csg) {
  16042. var a = new Node(this.polygons);
  16043. var b = new Node(csg.polygons);
  16044. a.invert();
  16045. b.clipTo(a);
  16046. b.invert();
  16047. a.clipTo(b);
  16048. b.clipTo(a);
  16049. a.build(b.allPolygons());
  16050. a.invert();
  16051. this.polygons = a.allPolygons();
  16052. };
  16053. CSG.prototype.inverse = function () {
  16054. var csg = this.clone();
  16055. csg.inverseInPlace();
  16056. return csg;
  16057. };
  16058. CSG.prototype.inverseInPlace = function () {
  16059. this.polygons.map(function (p) {
  16060. p.flip();
  16061. });
  16062. };
  16063. CSG.prototype.copyTransformAttributes = function (csg) {
  16064. this.matrix = csg.matrix;
  16065. this.position = csg.position;
  16066. this.rotation = csg.rotation;
  16067. this.scaling = csg.scaling;
  16068. return this;
  16069. };
  16070. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  16071. var matrix = this.matrix.clone();
  16072. matrix.invert();
  16073. 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;
  16074. if (keepSubMeshes) {
  16075. polygons.sort(function (a, b) {
  16076. if (a.shared.meshId === b.shared.meshId) {
  16077. return a.shared.subMeshId - b.shared.subMeshId;
  16078. } else {
  16079. return a.shared.meshId - b.shared.meshId;
  16080. }
  16081. });
  16082. }
  16083. for (var i = 0, il = polygons.length; i < il; i++) {
  16084. polygon = polygons[i];
  16085. if (!subMesh_dict[polygon.shared.meshId]) {
  16086. subMesh_dict[polygon.shared.meshId] = {};
  16087. }
  16088. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  16089. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  16090. indexStart: +Infinity,
  16091. indexEnd: -Infinity,
  16092. materialIndex: polygon.shared.materialIndex
  16093. };
  16094. }
  16095. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  16096. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  16097. polygonIndices[0] = 0;
  16098. polygonIndices[1] = j - 1;
  16099. polygonIndices[2] = j;
  16100. for (var k = 0; k < 3; k++) {
  16101. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  16102. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  16103. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  16104. BABYLON.Vector3.TransformCoordinatesToRef(vertex, matrix, vertex);
  16105. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  16106. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z];
  16107. 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)) {
  16108. vertices.push(vertex.x, vertex.y, vertex.z);
  16109. uvs.push(uv.x, uv.y);
  16110. normals.push(normal.x, normal.y, normal.z);
  16111. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z] = (vertices.length / 3) - 1;
  16112. }
  16113. indices.push(vertex_idx);
  16114. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  16115. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  16116. currentIndex++;
  16117. }
  16118. }
  16119. }
  16120. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  16121. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  16122. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  16123. mesh.setIndices(indices);
  16124. if (keepSubMeshes) {
  16125. var materialIndexOffset = 0, materialMaxIndex;
  16126. mesh.subMeshes.length = 0;
  16127. for (var m in subMesh_dict) {
  16128. materialMaxIndex = -1;
  16129. for (var sm in subMesh_dict[m]) {
  16130. subMesh_obj = subMesh_dict[m][sm];
  16131. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  16132. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  16133. }
  16134. materialIndexOffset += ++materialMaxIndex;
  16135. }
  16136. }
  16137. return mesh;
  16138. };
  16139. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  16140. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  16141. mesh.material = material;
  16142. mesh.position.copyFrom(this.position);
  16143. mesh.rotation.copyFrom(this.rotation);
  16144. mesh.scaling.copyFrom(this.scaling);
  16145. mesh.computeWorldMatrix(true);
  16146. return mesh;
  16147. };
  16148. return CSG;
  16149. })();
  16150. BABYLON.CSG = CSG;
  16151. })(BABYLON || (BABYLON = {}));
  16152. var __extends = this.__extends || function (d, b) {
  16153. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16154. function __() { this.constructor = d; }
  16155. __.prototype = b.prototype;
  16156. d.prototype = new __();
  16157. };
  16158. var BABYLON;
  16159. (function (BABYLON) {
  16160. var OculusDistortionCorrectionPostProcess = (function (_super) {
  16161. __extends(OculusDistortionCorrectionPostProcess, _super);
  16162. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  16163. var _this = this;
  16164. _super.call(this, name, "oculusDistortionCorrection", [
  16165. 'LensCenter',
  16166. 'Scale',
  16167. 'ScaleIn',
  16168. 'HmdWarpParam'
  16169. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  16170. this._isRightEye = isRightEye;
  16171. this._distortionFactors = cameraSettings.DistortionK;
  16172. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  16173. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  16174. this.onSizeChanged = function () {
  16175. _this.aspectRatio = _this.width * .5 / _this.height;
  16176. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  16177. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  16178. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  16179. };
  16180. this.onApply = function (effect) {
  16181. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  16182. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  16183. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  16184. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  16185. };
  16186. }
  16187. return OculusDistortionCorrectionPostProcess;
  16188. })(BABYLON.PostProcess);
  16189. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  16190. })(BABYLON || (BABYLON = {}));
  16191. var BABYLON;
  16192. (function (BABYLON) {
  16193. (function (JoystickAxis) {
  16194. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  16195. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  16196. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  16197. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  16198. var JoystickAxis = BABYLON.JoystickAxis;
  16199. var VirtualJoystick = (function () {
  16200. function VirtualJoystick(leftJoystick) {
  16201. var _this = this;
  16202. if (leftJoystick) {
  16203. this._leftJoystick = true;
  16204. } else {
  16205. this._leftJoystick = false;
  16206. }
  16207. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  16208. VirtualJoystick._globalJoystickIndex++;
  16209. this._axisTargetedByLeftAndRight = 0 /* X */;
  16210. this._axisTargetedByUpAndDown = 1 /* Y */;
  16211. this.reverseLeftRight = false;
  16212. this.reverseUpDown = false;
  16213. this._touches = new BABYLON.VirtualJoystick.Collection();
  16214. this.deltaPosition = BABYLON.Vector3.Zero();
  16215. this._joystickSensibility = 25;
  16216. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  16217. this._rotationSpeed = 25;
  16218. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  16219. this._rotateOnAxisRelativeToMesh = false;
  16220. if (!VirtualJoystick.vjCanvas) {
  16221. window.addEventListener("resize", function () {
  16222. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  16223. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  16224. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  16225. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  16226. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  16227. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  16228. }, false);
  16229. VirtualJoystick.vjCanvas = document.createElement("canvas");
  16230. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  16231. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  16232. VirtualJoystick.vjCanvas.width = window.innerWidth;
  16233. VirtualJoystick.vjCanvas.height = window.innerHeight;
  16234. VirtualJoystick.vjCanvas.style.width = "100%";
  16235. VirtualJoystick.vjCanvas.style.height = "100%";
  16236. VirtualJoystick.vjCanvas.style.position = "absolute";
  16237. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  16238. VirtualJoystick.vjCanvas.style.top = "0px";
  16239. VirtualJoystick.vjCanvas.style.left = "0px";
  16240. VirtualJoystick.vjCanvas.style.zIndex = "5";
  16241. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  16242. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  16243. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  16244. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  16245. document.body.appendChild(VirtualJoystick.vjCanvas);
  16246. }
  16247. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  16248. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  16249. this.pressed = false;
  16250. this._joystickColor = "cyan";
  16251. this._joystickPointerID = -1;
  16252. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  16253. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  16254. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  16255. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  16256. _this._onPointerDown(evt);
  16257. }, false);
  16258. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  16259. _this._onPointerMove(evt);
  16260. }, false);
  16261. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  16262. _this._onPointerUp(evt);
  16263. }, false);
  16264. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  16265. _this._onPointerUp(evt);
  16266. }, false);
  16267. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  16268. evt.preventDefault();
  16269. }, false);
  16270. requestAnimationFrame(function () {
  16271. _this._drawVirtualJoystick();
  16272. });
  16273. }
  16274. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  16275. this._joystickSensibility = newJoystickSensibility;
  16276. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  16277. };
  16278. VirtualJoystick.prototype._onPointerDown = function (e) {
  16279. var positionOnScreenCondition;
  16280. e.preventDefault();
  16281. if (this._leftJoystick === true) {
  16282. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  16283. } else {
  16284. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  16285. }
  16286. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  16287. this._joystickPointerID = e.pointerId;
  16288. this._joystickPointerStartPos.x = e.clientX;
  16289. this._joystickPointerStartPos.y = e.clientY;
  16290. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  16291. this._deltaJoystickVector.x = 0;
  16292. this._deltaJoystickVector.y = 0;
  16293. this.pressed = true;
  16294. this._touches.add(e.pointerId.toString(), e);
  16295. } else {
  16296. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  16297. this._action();
  16298. this._touches.add(e.pointerId.toString(), e);
  16299. }
  16300. }
  16301. };
  16302. VirtualJoystick.prototype._onPointerMove = function (e) {
  16303. if (this._joystickPointerID == e.pointerId) {
  16304. this._joystickPointerPos.x = e.clientX;
  16305. this._joystickPointerPos.y = e.clientY;
  16306. this._deltaJoystickVector = this._joystickPointerPos.clone();
  16307. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  16308. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  16309. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  16310. switch (this._axisTargetedByLeftAndRight) {
  16311. case 0 /* X */:
  16312. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  16313. break;
  16314. case 1 /* Y */:
  16315. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  16316. break;
  16317. case 2 /* Z */:
  16318. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  16319. break;
  16320. }
  16321. var directionUpDown = this.reverseUpDown ? 1 : -1;
  16322. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  16323. switch (this._axisTargetedByUpAndDown) {
  16324. case 0 /* X */:
  16325. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  16326. break;
  16327. case 1 /* Y */:
  16328. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  16329. break;
  16330. case 2 /* Z */:
  16331. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  16332. break;
  16333. }
  16334. } else {
  16335. if (this._touches.item(e.pointerId.toString())) {
  16336. this._touches.item(e.pointerId.toString()).x = e.clientX;
  16337. this._touches.item(e.pointerId.toString()).y = e.clientY;
  16338. }
  16339. }
  16340. };
  16341. VirtualJoystick.prototype._onPointerUp = function (e) {
  16342. this._clearCanvas();
  16343. if (this._joystickPointerID == e.pointerId) {
  16344. this._joystickPointerID = -1;
  16345. this.pressed = false;
  16346. }
  16347. this._deltaJoystickVector.x = 0;
  16348. this._deltaJoystickVector.y = 0;
  16349. this._touches.remove(e.pointerId.toString());
  16350. };
  16351. /**
  16352. * Change the color of the virtual joystick
  16353. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  16354. */
  16355. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  16356. this._joystickColor = newColor;
  16357. };
  16358. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  16359. this._action = action;
  16360. };
  16361. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  16362. switch (axis) {
  16363. case 0 /* X */:
  16364. case 1 /* Y */:
  16365. case 2 /* Z */:
  16366. this._axisTargetedByLeftAndRight = axis;
  16367. break;
  16368. default:
  16369. this._axisTargetedByLeftAndRight = 0 /* X */;
  16370. break;
  16371. }
  16372. };
  16373. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  16374. switch (axis) {
  16375. case 0 /* X */:
  16376. case 1 /* Y */:
  16377. case 2 /* Z */:
  16378. this._axisTargetedByUpAndDown = axis;
  16379. break;
  16380. default:
  16381. this._axisTargetedByUpAndDown = 1 /* Y */;
  16382. break;
  16383. }
  16384. };
  16385. VirtualJoystick.prototype._clearCanvas = function () {
  16386. if (this._leftJoystick) {
  16387. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  16388. } else {
  16389. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  16390. }
  16391. };
  16392. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  16393. var _this = this;
  16394. if (this.pressed) {
  16395. this._clearCanvas();
  16396. this._touches.forEach(function (touch) {
  16397. if (touch.pointerId === _this._joystickPointerID) {
  16398. VirtualJoystick.vjCanvasContext.beginPath();
  16399. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16400. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  16401. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  16402. VirtualJoystick.vjCanvasContext.stroke();
  16403. VirtualJoystick.vjCanvasContext.beginPath();
  16404. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16405. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  16406. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  16407. VirtualJoystick.vjCanvasContext.stroke();
  16408. VirtualJoystick.vjCanvasContext.beginPath();
  16409. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16410. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  16411. VirtualJoystick.vjCanvasContext.stroke();
  16412. } else {
  16413. VirtualJoystick.vjCanvasContext.beginPath();
  16414. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  16415. VirtualJoystick.vjCanvasContext.beginPath();
  16416. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  16417. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  16418. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  16419. VirtualJoystick.vjCanvasContext.stroke();
  16420. }
  16421. ;
  16422. });
  16423. }
  16424. requestAnimationFrame(function () {
  16425. _this._drawVirtualJoystick();
  16426. });
  16427. };
  16428. VirtualJoystick.prototype.releaseCanvas = function () {
  16429. if (VirtualJoystick.vjCanvas) {
  16430. document.body.removeChild(VirtualJoystick.vjCanvas);
  16431. VirtualJoystick.vjCanvas = null;
  16432. }
  16433. };
  16434. VirtualJoystick._globalJoystickIndex = 0;
  16435. return VirtualJoystick;
  16436. })();
  16437. BABYLON.VirtualJoystick = VirtualJoystick;
  16438. })(BABYLON || (BABYLON = {}));
  16439. var BABYLON;
  16440. (function (BABYLON) {
  16441. (function (VirtualJoystick) {
  16442. var Collection = (function () {
  16443. function Collection() {
  16444. this._count = 0;
  16445. this._collection = new Array();
  16446. }
  16447. Collection.prototype.Count = function () {
  16448. return this._count;
  16449. };
  16450. Collection.prototype.add = function (key, item) {
  16451. if (this._collection[key] != undefined) {
  16452. return undefined;
  16453. }
  16454. this._collection[key] = item;
  16455. return ++this._count;
  16456. };
  16457. Collection.prototype.remove = function (key) {
  16458. if (this._collection[key] == undefined) {
  16459. return undefined;
  16460. }
  16461. delete this._collection[key];
  16462. return --this._count;
  16463. };
  16464. Collection.prototype.item = function (key) {
  16465. return this._collection[key];
  16466. };
  16467. Collection.prototype.forEach = function (block) {
  16468. var key;
  16469. for (key in this._collection) {
  16470. if (this._collection.hasOwnProperty(key)) {
  16471. block(this._collection[key]);
  16472. }
  16473. }
  16474. };
  16475. return Collection;
  16476. })();
  16477. VirtualJoystick.Collection = Collection;
  16478. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  16479. var VirtualJoystick = BABYLON.VirtualJoystick;
  16480. })(BABYLON || (BABYLON = {}));
  16481. var __extends = this.__extends || function (d, b) {
  16482. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16483. function __() { this.constructor = d; }
  16484. __.prototype = b.prototype;
  16485. d.prototype = new __();
  16486. };
  16487. var BABYLON;
  16488. (function (BABYLON) {
  16489. var OculusRiftDevKit2013_Metric = {
  16490. HResolution: 1280,
  16491. VResolution: 800,
  16492. HScreenSize: 0.149759993,
  16493. VScreenSize: 0.0935999975,
  16494. VScreenCenter: 0.0467999987,
  16495. EyeToScreenDistance: 0.0410000011,
  16496. LensSeparationDistance: 0.0635000020,
  16497. InterpupillaryDistance: 0.0640000030,
  16498. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  16499. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  16500. PostProcessScaleFactor: 1.714605507808412,
  16501. LensCenterOffset: 0.151976421
  16502. };
  16503. var _OculusInnerCamera = (function (_super) {
  16504. __extends(_OculusInnerCamera, _super);
  16505. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  16506. _super.call(this, name, position, scene);
  16507. this._workMatrix = new BABYLON.Matrix();
  16508. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  16509. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  16510. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  16511. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  16512. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  16513. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  16514. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  16515. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  16516. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  16517. }
  16518. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  16519. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  16520. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  16521. return this._projectionMatrix;
  16522. };
  16523. _OculusInnerCamera.prototype._getViewMatrix = function () {
  16524. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  16525. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  16526. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  16527. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  16528. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  16529. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  16530. return this._viewMatrix;
  16531. };
  16532. return _OculusInnerCamera;
  16533. })(BABYLON.FreeCamera);
  16534. var OculusCamera = (function (_super) {
  16535. __extends(OculusCamera, _super);
  16536. function OculusCamera(name, position, scene) {
  16537. _super.call(this, name, position, scene);
  16538. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  16539. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  16540. this.subCameras.push(this._leftCamera);
  16541. this.subCameras.push(this._rightCamera);
  16542. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  16543. }
  16544. OculusCamera.prototype._update = function () {
  16545. this._leftCamera.position.copyFrom(this.position);
  16546. this._rightCamera.position.copyFrom(this.position);
  16547. this._updateCamera(this._leftCamera);
  16548. this._updateCamera(this._rightCamera);
  16549. _super.prototype._update.call(this);
  16550. };
  16551. OculusCamera.prototype._updateCamera = function (camera) {
  16552. camera.minZ = this.minZ;
  16553. camera.maxZ = this.maxZ;
  16554. camera.rotation.x = this.rotation.x;
  16555. camera.rotation.y = this.rotation.y;
  16556. camera.rotation.z = this.rotation.z;
  16557. };
  16558. OculusCamera.prototype._onOrientationEvent = function (evt) {
  16559. var yaw = evt.alpha / 180 * Math.PI;
  16560. var pitch = evt.beta / 180 * Math.PI;
  16561. var roll = evt.gamma / 180 * Math.PI;
  16562. if (!this._offsetOrientation) {
  16563. this._offsetOrientation = {
  16564. yaw: yaw,
  16565. pitch: pitch,
  16566. roll: roll
  16567. };
  16568. return;
  16569. } else {
  16570. this.rotation.y += yaw - this._offsetOrientation.yaw;
  16571. this.rotation.x += pitch - this._offsetOrientation.pitch;
  16572. this.rotation.z += this._offsetOrientation.roll - roll;
  16573. this._offsetOrientation.yaw = yaw;
  16574. this._offsetOrientation.pitch = pitch;
  16575. this._offsetOrientation.roll = roll;
  16576. }
  16577. };
  16578. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  16579. _super.prototype.attachControl.call(this, element, noPreventDefault);
  16580. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  16581. };
  16582. OculusCamera.prototype.detachControl = function (element) {
  16583. _super.prototype.detachControl.call(this, element);
  16584. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  16585. };
  16586. return OculusCamera;
  16587. })(BABYLON.FreeCamera);
  16588. BABYLON.OculusCamera = OculusCamera;
  16589. })(BABYLON || (BABYLON = {}));
  16590. var __extends = this.__extends || function (d, b) {
  16591. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16592. function __() { this.constructor = d; }
  16593. __.prototype = b.prototype;
  16594. d.prototype = new __();
  16595. };
  16596. var BABYLON;
  16597. (function (BABYLON) {
  16598. var OculusRiftDevKit2013_Metric = {
  16599. HResolution: 1280,
  16600. VResolution: 800,
  16601. HScreenSize: 0.149759993,
  16602. VScreenSize: 0.0935999975,
  16603. VScreenCenter: 0.0467999987,
  16604. EyeToScreenDistance: 0.0410000011,
  16605. LensSeparationDistance: 0.0635000020,
  16606. InterpupillaryDistance: 0.0640000030,
  16607. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  16608. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  16609. PostProcessScaleFactor: 1.714605507808412,
  16610. LensCenterOffset: 0.151976421
  16611. };
  16612. var _OculusInnerGamepadCamera = (function (_super) {
  16613. __extends(_OculusInnerGamepadCamera, _super);
  16614. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  16615. _super.call(this, name, position, scene);
  16616. this._workMatrix = new BABYLON.Matrix();
  16617. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  16618. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  16619. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  16620. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  16621. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  16622. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  16623. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  16624. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  16625. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  16626. }
  16627. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  16628. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  16629. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  16630. return this._projectionMatrix;
  16631. };
  16632. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  16633. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  16634. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  16635. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  16636. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  16637. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  16638. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  16639. return this._viewMatrix;
  16640. };
  16641. return _OculusInnerGamepadCamera;
  16642. })(BABYLON.FreeCamera);
  16643. var OculusGamepadCamera = (function (_super) {
  16644. __extends(OculusGamepadCamera, _super);
  16645. function OculusGamepadCamera(name, position, scene) {
  16646. var _this = this;
  16647. _super.call(this, name, position, scene);
  16648. this.angularSensibility = 200;
  16649. this.moveSensibility = 75;
  16650. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  16651. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  16652. this.subCameras.push(this._leftCamera);
  16653. this.subCameras.push(this._rightCamera);
  16654. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  16655. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  16656. _this._onNewGameConnected(gamepad);
  16657. });
  16658. }
  16659. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  16660. if (gamepad.index === 0) {
  16661. this._gamepad = gamepad;
  16662. }
  16663. };
  16664. OculusGamepadCamera.prototype._update = function () {
  16665. this._leftCamera.position.copyFrom(this.position);
  16666. this._rightCamera.position.copyFrom(this.position);
  16667. this._updateCamera(this._leftCamera);
  16668. this._updateCamera(this._rightCamera);
  16669. _super.prototype._update.call(this);
  16670. };
  16671. OculusGamepadCamera.prototype._checkInputs = function () {
  16672. if (!this._gamepad) {
  16673. return;
  16674. }
  16675. var LSValues = this._gamepad.leftStick;
  16676. var normalizedLX = LSValues.x / this.moveSensibility;
  16677. var normalizedLY = LSValues.y / this.moveSensibility;
  16678. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  16679. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  16680. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  16681. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  16682. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  16683. };
  16684. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  16685. camera.minZ = this.minZ;
  16686. camera.maxZ = this.maxZ;
  16687. camera.rotation.x = this.rotation.x;
  16688. camera.rotation.y = this.rotation.y;
  16689. camera.rotation.z = this.rotation.z;
  16690. };
  16691. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  16692. var yaw = evt.alpha / 180 * Math.PI;
  16693. var pitch = evt.beta / 180 * Math.PI;
  16694. var roll = evt.gamma / 180 * Math.PI;
  16695. if (!this._offsetOrientation) {
  16696. this._offsetOrientation = {
  16697. yaw: yaw,
  16698. pitch: pitch,
  16699. roll: roll
  16700. };
  16701. return;
  16702. } else {
  16703. this.rotation.y += yaw - this._offsetOrientation.yaw;
  16704. this.rotation.x += pitch - this._offsetOrientation.pitch;
  16705. this.rotation.z += this._offsetOrientation.roll - roll;
  16706. this._offsetOrientation.yaw = yaw;
  16707. this._offsetOrientation.pitch = pitch;
  16708. this._offsetOrientation.roll = roll;
  16709. }
  16710. };
  16711. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  16712. _super.prototype.attachControl.call(this, element, noPreventDefault);
  16713. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  16714. };
  16715. OculusGamepadCamera.prototype.detachControl = function (element) {
  16716. _super.prototype.detachControl.call(this, element);
  16717. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  16718. };
  16719. OculusGamepadCamera.prototype.dispose = function () {
  16720. this._gamepads.dispose();
  16721. _super.prototype.dispose.call(this);
  16722. };
  16723. return OculusGamepadCamera;
  16724. })(BABYLON.FreeCamera);
  16725. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  16726. })(BABYLON || (BABYLON = {}));
  16727. var __extends = this.__extends || function (d, b) {
  16728. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16729. function __() { this.constructor = d; }
  16730. __.prototype = b.prototype;
  16731. d.prototype = new __();
  16732. };
  16733. var BABYLON;
  16734. (function (BABYLON) {
  16735. var VirtualJoysticksCamera = (function (_super) {
  16736. __extends(VirtualJoysticksCamera, _super);
  16737. function VirtualJoysticksCamera(name, position, scene) {
  16738. _super.call(this, name, position, scene);
  16739. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  16740. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  16741. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  16742. this._leftjoystick.setJoystickSensibility(0.15);
  16743. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  16744. this._rightjoystick.setAxisForUpDown(0 /* X */);
  16745. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  16746. this._rightjoystick.reverseUpDown = true;
  16747. this._rightjoystick.setJoystickSensibility(0.05);
  16748. this._rightjoystick.setJoystickColor("yellow");
  16749. }
  16750. VirtualJoysticksCamera.prototype._checkInputs = function () {
  16751. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  16752. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  16753. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  16754. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  16755. if (!this._leftjoystick.pressed) {
  16756. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  16757. }
  16758. if (!this._rightjoystick.pressed) {
  16759. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  16760. }
  16761. };
  16762. VirtualJoysticksCamera.prototype.dispose = function () {
  16763. this._leftjoystick.releaseCanvas();
  16764. _super.prototype.dispose.call(this);
  16765. };
  16766. return VirtualJoysticksCamera;
  16767. })(BABYLON.FreeCamera);
  16768. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  16769. })(BABYLON || (BABYLON = {}));
  16770. var __extends = this.__extends || function (d, b) {
  16771. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16772. function __() { this.constructor = d; }
  16773. __.prototype = b.prototype;
  16774. d.prototype = new __();
  16775. };
  16776. var BABYLON;
  16777. (function (BABYLON) {
  16778. var ShaderMaterial = (function (_super) {
  16779. __extends(ShaderMaterial, _super);
  16780. function ShaderMaterial(name, scene, shaderPath, options) {
  16781. _super.call(this, name, scene);
  16782. this._textures = new Array();
  16783. this._floats = new Array();
  16784. this._floatsArrays = {};
  16785. this._colors3 = new Array();
  16786. this._colors4 = new Array();
  16787. this._vectors2 = new Array();
  16788. this._vectors3 = new Array();
  16789. this._matrices = new Array();
  16790. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  16791. this._shaderPath = shaderPath;
  16792. options.needAlphaBlending = options.needAlphaBlending || false;
  16793. options.needAlphaTesting = options.needAlphaTesting || false;
  16794. options.attributes = options.attributes || ["position", "normal", "uv"];
  16795. options.uniforms = options.uniforms || ["worldViewProjection"];
  16796. options.samplers = options.samplers || [];
  16797. this._options = options;
  16798. }
  16799. ShaderMaterial.prototype.needAlphaBlending = function () {
  16800. return this._options.needAlphaBlending;
  16801. };
  16802. ShaderMaterial.prototype.needAlphaTesting = function () {
  16803. return this._options.needAlphaTesting;
  16804. };
  16805. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  16806. if (this._options.uniforms.indexOf(uniformName) === -1) {
  16807. this._options.uniforms.push(uniformName);
  16808. }
  16809. };
  16810. ShaderMaterial.prototype.setTexture = function (name, texture) {
  16811. if (this._options.samplers.indexOf(name) === -1) {
  16812. this._options.samplers.push(name);
  16813. }
  16814. this._textures[name] = texture;
  16815. return this;
  16816. };
  16817. ShaderMaterial.prototype.setFloat = function (name, value) {
  16818. this._checkUniform(name);
  16819. this._floats[name] = value;
  16820. return this;
  16821. };
  16822. ShaderMaterial.prototype.setFloats = function (name, value) {
  16823. this._checkUniform(name);
  16824. this._floatsArrays[name] = value;
  16825. return this;
  16826. };
  16827. ShaderMaterial.prototype.setColor3 = function (name, value) {
  16828. this._checkUniform(name);
  16829. this._colors3[name] = value;
  16830. return this;
  16831. };
  16832. ShaderMaterial.prototype.setColor4 = function (name, value) {
  16833. this._checkUniform(name);
  16834. this._colors4[name] = value;
  16835. return this;
  16836. };
  16837. ShaderMaterial.prototype.setVector2 = function (name, value) {
  16838. this._checkUniform(name);
  16839. this._vectors2[name] = value;
  16840. return this;
  16841. };
  16842. ShaderMaterial.prototype.setVector3 = function (name, value) {
  16843. this._checkUniform(name);
  16844. this._vectors3[name] = value;
  16845. return this;
  16846. };
  16847. ShaderMaterial.prototype.setMatrix = function (name, value) {
  16848. this._checkUniform(name);
  16849. this._matrices[name] = value;
  16850. return this;
  16851. };
  16852. ShaderMaterial.prototype.isReady = function () {
  16853. var engine = this.getScene().getEngine();
  16854. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  16855. if (!this._effect.isReady()) {
  16856. return false;
  16857. }
  16858. return true;
  16859. };
  16860. ShaderMaterial.prototype.bind = function (world) {
  16861. if (this._options.uniforms.indexOf("world") !== -1) {
  16862. this._effect.setMatrix("world", world);
  16863. }
  16864. if (this._options.uniforms.indexOf("view") !== -1) {
  16865. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  16866. }
  16867. if (this._options.uniforms.indexOf("worldView") !== -1) {
  16868. world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
  16869. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  16870. }
  16871. if (this._options.uniforms.indexOf("projection") !== -1) {
  16872. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  16873. }
  16874. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  16875. this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
  16876. }
  16877. for (var name in this._textures) {
  16878. this._effect.setTexture(name, this._textures[name]);
  16879. }
  16880. for (name in this._floats) {
  16881. this._effect.setFloat(name, this._floats[name]);
  16882. }
  16883. for (name in this._floatsArrays) {
  16884. this._effect.setArray(name, this._floatsArrays[name]);
  16885. }
  16886. for (name in this._colors3) {
  16887. this._effect.setColor3(name, this._colors3[name]);
  16888. }
  16889. for (name in this._colors4) {
  16890. var color = this._colors4[name];
  16891. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16892. }
  16893. for (name in this._vectors2) {
  16894. this._effect.setVector2(name, this._vectors2[name]);
  16895. }
  16896. for (name in this._vectors3) {
  16897. this._effect.setVector3(name, this._vectors3[name]);
  16898. }
  16899. for (name in this._matrices) {
  16900. this._effect.setMatrix(name, this._matrices[name]);
  16901. }
  16902. };
  16903. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  16904. for (var name in this._textures) {
  16905. this._textures[name].dispose();
  16906. }
  16907. this._textures = [];
  16908. _super.prototype.dispose.call(this, forceDisposeEffect);
  16909. };
  16910. return ShaderMaterial;
  16911. })(BABYLON.Material);
  16912. BABYLON.ShaderMaterial = ShaderMaterial;
  16913. })(BABYLON || (BABYLON = {}));
  16914. var BABYLON;
  16915. (function (BABYLON) {
  16916. var VertexData = (function () {
  16917. function VertexData() {
  16918. }
  16919. VertexData.prototype.set = function (data, kind) {
  16920. switch (kind) {
  16921. case BABYLON.VertexBuffer.PositionKind:
  16922. this.positions = data;
  16923. break;
  16924. case BABYLON.VertexBuffer.NormalKind:
  16925. this.normals = data;
  16926. break;
  16927. case BABYLON.VertexBuffer.UVKind:
  16928. this.uvs = data;
  16929. break;
  16930. case BABYLON.VertexBuffer.UV2Kind:
  16931. this.uv2s = data;
  16932. break;
  16933. case BABYLON.VertexBuffer.ColorKind:
  16934. this.colors = data;
  16935. break;
  16936. case BABYLON.VertexBuffer.MatricesIndicesKind:
  16937. this.matricesIndices = data;
  16938. break;
  16939. case BABYLON.VertexBuffer.MatricesWeightsKind:
  16940. this.matricesWeights = data;
  16941. break;
  16942. }
  16943. };
  16944. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  16945. this._applyTo(mesh, updatable);
  16946. };
  16947. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  16948. this._applyTo(geometry, updatable);
  16949. };
  16950. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  16951. this._update(mesh);
  16952. };
  16953. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  16954. this._update(geometry);
  16955. };
  16956. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  16957. if (this.positions) {
  16958. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  16959. }
  16960. if (this.normals) {
  16961. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  16962. }
  16963. if (this.uvs) {
  16964. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  16965. }
  16966. if (this.uv2s) {
  16967. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  16968. }
  16969. if (this.colors) {
  16970. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  16971. }
  16972. if (this.matricesIndices) {
  16973. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  16974. }
  16975. if (this.matricesWeights) {
  16976. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  16977. }
  16978. if (this.indices) {
  16979. meshOrGeometry.setIndices(this.indices);
  16980. }
  16981. };
  16982. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  16983. if (this.positions) {
  16984. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  16985. }
  16986. if (this.normals) {
  16987. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  16988. }
  16989. if (this.uvs) {
  16990. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  16991. }
  16992. if (this.uv2s) {
  16993. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  16994. }
  16995. if (this.colors) {
  16996. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  16997. }
  16998. if (this.matricesIndices) {
  16999. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  17000. }
  17001. if (this.matricesWeights) {
  17002. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  17003. }
  17004. if (this.indices) {
  17005. meshOrGeometry.setIndices(this.indices);
  17006. }
  17007. };
  17008. VertexData.prototype.transform = function (matrix) {
  17009. var transformed = BABYLON.Vector3.Zero();
  17010. if (this.positions) {
  17011. var position = BABYLON.Vector3.Zero();
  17012. for (var index = 0; index < this.positions.length; index += 3) {
  17013. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  17014. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  17015. this.positions[index] = transformed.x;
  17016. this.positions[index + 1] = transformed.y;
  17017. this.positions[index + 2] = transformed.z;
  17018. }
  17019. }
  17020. if (this.normals) {
  17021. var normal = BABYLON.Vector3.Zero();
  17022. for (index = 0; index < this.normals.length; index += 3) {
  17023. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  17024. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  17025. this.normals[index] = transformed.x;
  17026. this.normals[index + 1] = transformed.y;
  17027. this.normals[index + 2] = transformed.z;
  17028. }
  17029. }
  17030. };
  17031. VertexData.prototype.merge = function (other) {
  17032. if (other.indices) {
  17033. if (!this.indices) {
  17034. this.indices = [];
  17035. }
  17036. var offset = this.positions ? this.positions.length / 3 : 0;
  17037. for (var index = 0; index < other.indices.length; index++) {
  17038. this.indices.push(other.indices[index] + offset);
  17039. }
  17040. }
  17041. if (other.positions) {
  17042. if (!this.positions) {
  17043. this.positions = [];
  17044. }
  17045. for (index = 0; index < other.positions.length; index++) {
  17046. this.positions.push(other.positions[index]);
  17047. }
  17048. }
  17049. if (other.normals) {
  17050. if (!this.normals) {
  17051. this.normals = [];
  17052. }
  17053. for (index = 0; index < other.normals.length; index++) {
  17054. this.normals.push(other.normals[index]);
  17055. }
  17056. }
  17057. if (other.uvs) {
  17058. if (!this.uvs) {
  17059. this.uvs = [];
  17060. }
  17061. for (index = 0; index < other.uvs.length; index++) {
  17062. this.uvs.push(other.uvs[index]);
  17063. }
  17064. }
  17065. if (other.uv2s) {
  17066. if (!this.uv2s) {
  17067. this.uv2s = [];
  17068. }
  17069. for (index = 0; index < other.uv2s.length; index++) {
  17070. this.uv2s.push(other.uv2s[index]);
  17071. }
  17072. }
  17073. if (other.matricesIndices) {
  17074. if (!this.matricesIndices) {
  17075. this.matricesIndices = [];
  17076. }
  17077. for (index = 0; index < other.matricesIndices.length; index++) {
  17078. this.matricesIndices.push(other.matricesIndices[index]);
  17079. }
  17080. }
  17081. if (other.matricesWeights) {
  17082. if (!this.matricesWeights) {
  17083. this.matricesWeights = [];
  17084. }
  17085. for (index = 0; index < other.matricesWeights.length; index++) {
  17086. this.matricesWeights.push(other.matricesWeights[index]);
  17087. }
  17088. }
  17089. if (other.colors) {
  17090. if (!this.colors) {
  17091. this.colors = [];
  17092. }
  17093. for (index = 0; index < other.colors.length; index++) {
  17094. this.colors.push(other.colors[index]);
  17095. }
  17096. }
  17097. };
  17098. VertexData.ExtractFromMesh = function (mesh) {
  17099. return VertexData._ExtractFrom(mesh);
  17100. };
  17101. VertexData.ExtractFromGeometry = function (geometry) {
  17102. return VertexData._ExtractFrom(geometry);
  17103. };
  17104. VertexData._ExtractFrom = function (meshOrGeometry) {
  17105. var result = new BABYLON.VertexData();
  17106. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17107. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17108. }
  17109. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17110. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17111. }
  17112. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17113. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17114. }
  17115. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17116. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  17117. }
  17118. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17119. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  17120. }
  17121. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17122. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17123. }
  17124. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17125. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17126. }
  17127. result.indices = meshOrGeometry.getIndices();
  17128. return result;
  17129. };
  17130. VertexData.CreateBox = function (size) {
  17131. var normalsSource = [
  17132. new BABYLON.Vector3(0, 0, 1),
  17133. new BABYLON.Vector3(0, 0, -1),
  17134. new BABYLON.Vector3(1, 0, 0),
  17135. new BABYLON.Vector3(-1, 0, 0),
  17136. new BABYLON.Vector3(0, 1, 0),
  17137. new BABYLON.Vector3(0, -1, 0)
  17138. ];
  17139. var indices = [];
  17140. var positions = [];
  17141. var normals = [];
  17142. var uvs = [];
  17143. size = size || 1;
  17144. for (var index = 0; index < normalsSource.length; index++) {
  17145. var normal = normalsSource[index];
  17146. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  17147. var side2 = BABYLON.Vector3.Cross(normal, side1);
  17148. var verticesLength = positions.length / 3;
  17149. indices.push(verticesLength);
  17150. indices.push(verticesLength + 1);
  17151. indices.push(verticesLength + 2);
  17152. indices.push(verticesLength);
  17153. indices.push(verticesLength + 2);
  17154. indices.push(verticesLength + 3);
  17155. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  17156. positions.push(vertex.x, vertex.y, vertex.z);
  17157. normals.push(normal.x, normal.y, normal.z);
  17158. uvs.push(1.0, 1.0);
  17159. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  17160. positions.push(vertex.x, vertex.y, vertex.z);
  17161. normals.push(normal.x, normal.y, normal.z);
  17162. uvs.push(0.0, 1.0);
  17163. vertex = normal.add(side1).add(side2).scale(size / 2);
  17164. positions.push(vertex.x, vertex.y, vertex.z);
  17165. normals.push(normal.x, normal.y, normal.z);
  17166. uvs.push(0.0, 0.0);
  17167. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  17168. positions.push(vertex.x, vertex.y, vertex.z);
  17169. normals.push(normal.x, normal.y, normal.z);
  17170. uvs.push(1.0, 0.0);
  17171. }
  17172. var vertexData = new BABYLON.VertexData();
  17173. vertexData.indices = indices;
  17174. vertexData.positions = positions;
  17175. vertexData.normals = normals;
  17176. vertexData.uvs = uvs;
  17177. return vertexData;
  17178. };
  17179. VertexData.CreateSphere = function (segments, diameter) {
  17180. segments = segments || 32;
  17181. diameter = diameter || 1;
  17182. var radius = diameter / 2;
  17183. var totalZRotationSteps = 2 + segments;
  17184. var totalYRotationSteps = 2 * totalZRotationSteps;
  17185. var indices = [];
  17186. var positions = [];
  17187. var normals = [];
  17188. var uvs = [];
  17189. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  17190. var normalizedZ = zRotationStep / totalZRotationSteps;
  17191. var angleZ = (normalizedZ * Math.PI);
  17192. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  17193. var normalizedY = yRotationStep / totalYRotationSteps;
  17194. var angleY = normalizedY * Math.PI * 2;
  17195. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  17196. var rotationY = BABYLON.Matrix.RotationY(angleY);
  17197. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  17198. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  17199. var vertex = complete.scale(radius);
  17200. var normal = BABYLON.Vector3.Normalize(vertex);
  17201. positions.push(vertex.x, vertex.y, vertex.z);
  17202. normals.push(normal.x, normal.y, normal.z);
  17203. uvs.push(normalizedZ, normalizedY);
  17204. }
  17205. if (zRotationStep > 0) {
  17206. var verticesCount = positions.length / 3;
  17207. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  17208. indices.push((firstIndex));
  17209. indices.push((firstIndex + 1));
  17210. indices.push(firstIndex + totalYRotationSteps + 1);
  17211. indices.push((firstIndex + totalYRotationSteps + 1));
  17212. indices.push((firstIndex + 1));
  17213. indices.push((firstIndex + totalYRotationSteps + 2));
  17214. }
  17215. }
  17216. }
  17217. var vertexData = new BABYLON.VertexData();
  17218. vertexData.indices = indices;
  17219. vertexData.positions = positions;
  17220. vertexData.normals = normals;
  17221. vertexData.uvs = uvs;
  17222. return vertexData;
  17223. };
  17224. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  17225. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  17226. var radiusTop = diameterTop / 2;
  17227. var radiusBottom = diameterBottom / 2;
  17228. var indices = [];
  17229. var positions = [];
  17230. var normals = [];
  17231. var uvs = [];
  17232. height = height || 1;
  17233. diameterTop = diameterTop || 0.5;
  17234. diameterBottom = diameterBottom || 1;
  17235. tessellation = tessellation || 16;
  17236. subdivisions = subdivisions || 1;
  17237. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  17238. var getCircleVector = function (i) {
  17239. var angle = (i * 2.0 * Math.PI / tessellation);
  17240. var dx = Math.cos(angle);
  17241. var dz = Math.sin(angle);
  17242. return new BABYLON.Vector3(dx, 0, dz);
  17243. };
  17244. var createCylinderCap = function (isTop) {
  17245. var radius = isTop ? radiusTop : radiusBottom;
  17246. if (radius == 0) {
  17247. return;
  17248. }
  17249. var vbase = positions.length / 3;
  17250. var offset = new BABYLON.Vector3(0, height / 2, 0);
  17251. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  17252. if (!isTop) {
  17253. offset.scaleInPlace(-1);
  17254. textureScale.x = -textureScale.x;
  17255. }
  17256. for (i = 0; i < tessellation; i++) {
  17257. var circleVector = getCircleVector(i);
  17258. var position = circleVector.scale(radius).add(offset);
  17259. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  17260. positions.push(position.x, position.y, position.z);
  17261. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17262. }
  17263. for (var i = 0; i < tessellation - 2; i++) {
  17264. if (!isTop) {
  17265. indices.push(vbase);
  17266. indices.push(vbase + (i + 2) % tessellation);
  17267. indices.push(vbase + (i + 1) % tessellation);
  17268. } else {
  17269. indices.push(vbase);
  17270. indices.push(vbase + (i + 1) % tessellation);
  17271. indices.push(vbase + (i + 2) % tessellation);
  17272. }
  17273. }
  17274. };
  17275. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  17276. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  17277. var stride = tessellation + 1;
  17278. for (var i = 0; i <= tessellation; i++) {
  17279. var circleVector = getCircleVector(i);
  17280. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  17281. var position, radius = radiusBottom;
  17282. for (var s = 0; s <= subdivisions; s++) {
  17283. position = circleVector.scale(radius);
  17284. position.addInPlace(base.add(offset.scale(s)));
  17285. textureCoordinate.y += 1 / subdivisions;
  17286. radius += (radiusTop - radiusBottom) / subdivisions;
  17287. positions.push(position.x, position.y, position.z);
  17288. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17289. }
  17290. }
  17291. subdivisions += 1;
  17292. for (var s = 0; s < subdivisions - 1; s++) {
  17293. for (var i = 0; i <= tessellation; i++) {
  17294. indices.push(i * subdivisions + s);
  17295. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  17296. indices.push(i * subdivisions + (s + 1));
  17297. indices.push(i * subdivisions + (s + 1));
  17298. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  17299. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  17300. }
  17301. }
  17302. createCylinderCap(true);
  17303. createCylinderCap(false);
  17304. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17305. var vertexData = new BABYLON.VertexData();
  17306. vertexData.indices = indices;
  17307. vertexData.positions = positions;
  17308. vertexData.normals = normals;
  17309. vertexData.uvs = uvs;
  17310. return vertexData;
  17311. };
  17312. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  17313. var indices = [];
  17314. var positions = [];
  17315. var normals = [];
  17316. var uvs = [];
  17317. diameter = diameter || 1;
  17318. thickness = thickness || 0.5;
  17319. tessellation = tessellation || 16;
  17320. var stride = tessellation + 1;
  17321. for (var i = 0; i <= tessellation; i++) {
  17322. var u = i / tessellation;
  17323. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  17324. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  17325. for (var j = 0; j <= tessellation; j++) {
  17326. var v = 1 - j / tessellation;
  17327. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  17328. var dx = Math.cos(innerAngle);
  17329. var dy = Math.sin(innerAngle);
  17330. var normal = new BABYLON.Vector3(dx, dy, 0);
  17331. var position = normal.scale(thickness / 2);
  17332. var textureCoordinate = new BABYLON.Vector2(u, v);
  17333. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  17334. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  17335. positions.push(position.x, position.y, position.z);
  17336. normals.push(normal.x, normal.y, normal.z);
  17337. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17338. var nextI = (i + 1) % stride;
  17339. var nextJ = (j + 1) % stride;
  17340. indices.push(i * stride + j);
  17341. indices.push(i * stride + nextJ);
  17342. indices.push(nextI * stride + j);
  17343. indices.push(i * stride + nextJ);
  17344. indices.push(nextI * stride + nextJ);
  17345. indices.push(nextI * stride + j);
  17346. }
  17347. }
  17348. var vertexData = new BABYLON.VertexData();
  17349. vertexData.indices = indices;
  17350. vertexData.positions = positions;
  17351. vertexData.normals = normals;
  17352. vertexData.uvs = uvs;
  17353. return vertexData;
  17354. };
  17355. VertexData.CreateLines = function (points) {
  17356. var indices = [];
  17357. var positions = [];
  17358. for (var index = 0; index < points.length; index++) {
  17359. positions.push(points[index].x, points[index].y, points[index].z);
  17360. if (index > 0) {
  17361. indices.push(index - 1);
  17362. indices.push(index);
  17363. }
  17364. }
  17365. var vertexData = new BABYLON.VertexData();
  17366. vertexData.indices = indices;
  17367. vertexData.positions = positions;
  17368. return vertexData;
  17369. };
  17370. VertexData.CreateGround = function (width, height, subdivisions) {
  17371. var indices = [];
  17372. var positions = [];
  17373. var normals = [];
  17374. var uvs = [];
  17375. var row, col;
  17376. width = width || 1;
  17377. height = height || 1;
  17378. subdivisions = subdivisions || 1;
  17379. for (row = 0; row <= subdivisions; row++) {
  17380. for (col = 0; col <= subdivisions; col++) {
  17381. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  17382. var normal = new BABYLON.Vector3(0, 1.0, 0);
  17383. positions.push(position.x, position.y, position.z);
  17384. normals.push(normal.x, normal.y, normal.z);
  17385. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  17386. }
  17387. }
  17388. for (row = 0; row < subdivisions; row++) {
  17389. for (col = 0; col < subdivisions; col++) {
  17390. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17391. indices.push(col + 1 + row * (subdivisions + 1));
  17392. indices.push(col + row * (subdivisions + 1));
  17393. indices.push(col + (row + 1) * (subdivisions + 1));
  17394. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17395. indices.push(col + row * (subdivisions + 1));
  17396. }
  17397. }
  17398. var vertexData = new BABYLON.VertexData();
  17399. vertexData.indices = indices;
  17400. vertexData.positions = positions;
  17401. vertexData.normals = normals;
  17402. vertexData.uvs = uvs;
  17403. return vertexData;
  17404. };
  17405. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  17406. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  17407. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  17408. var indices = [];
  17409. var positions = [];
  17410. var normals = [];
  17411. var uvs = [];
  17412. var row, col, tileRow, tileCol;
  17413. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  17414. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  17415. precision.w = (precision.w < 1) ? 1 : precision.w;
  17416. precision.h = (precision.h < 1) ? 1 : precision.h;
  17417. var tileSize = {
  17418. 'w': (xmax - xmin) / subdivisions.w,
  17419. 'h': (zmax - zmin) / subdivisions.h
  17420. };
  17421. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  17422. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  17423. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  17424. }
  17425. }
  17426. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  17427. var base = positions.length / 3;
  17428. var rowLength = precision.w + 1;
  17429. for (row = 0; row < precision.h; row++) {
  17430. for (col = 0; col < precision.w; col++) {
  17431. var square = [
  17432. base + col + row * rowLength,
  17433. base + (col + 1) + row * rowLength,
  17434. base + (col + 1) + (row + 1) * rowLength,
  17435. base + col + (row + 1) * rowLength
  17436. ];
  17437. indices.push(square[1]);
  17438. indices.push(square[2]);
  17439. indices.push(square[3]);
  17440. indices.push(square[0]);
  17441. indices.push(square[1]);
  17442. indices.push(square[3]);
  17443. }
  17444. }
  17445. var position = BABYLON.Vector3.Zero();
  17446. var normal = new BABYLON.Vector3(0, 1.0, 0);
  17447. for (row = 0; row <= precision.h; row++) {
  17448. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  17449. for (col = 0; col <= precision.w; col++) {
  17450. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  17451. position.y = 0;
  17452. positions.push(position.x, position.y, position.z);
  17453. normals.push(normal.x, normal.y, normal.z);
  17454. uvs.push(col / precision.w, row / precision.h);
  17455. }
  17456. }
  17457. }
  17458. var vertexData = new BABYLON.VertexData();
  17459. vertexData.indices = indices;
  17460. vertexData.positions = positions;
  17461. vertexData.normals = normals;
  17462. vertexData.uvs = uvs;
  17463. return vertexData;
  17464. };
  17465. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  17466. var indices = [];
  17467. var positions = [];
  17468. var normals = [];
  17469. var uvs = [];
  17470. var row, col;
  17471. for (row = 0; row <= subdivisions; row++) {
  17472. for (col = 0; col <= subdivisions; col++) {
  17473. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  17474. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  17475. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  17476. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  17477. var r = buffer[pos] / 255.0;
  17478. var g = buffer[pos + 1] / 255.0;
  17479. var b = buffer[pos + 2] / 255.0;
  17480. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  17481. position.y = minHeight + (maxHeight - minHeight) * gradient;
  17482. positions.push(position.x, position.y, position.z);
  17483. normals.push(0, 0, 0);
  17484. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  17485. }
  17486. }
  17487. for (row = 0; row < subdivisions; row++) {
  17488. for (col = 0; col < subdivisions; col++) {
  17489. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17490. indices.push(col + 1 + row * (subdivisions + 1));
  17491. indices.push(col + row * (subdivisions + 1));
  17492. indices.push(col + (row + 1) * (subdivisions + 1));
  17493. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17494. indices.push(col + row * (subdivisions + 1));
  17495. }
  17496. }
  17497. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17498. var vertexData = new BABYLON.VertexData();
  17499. vertexData.indices = indices;
  17500. vertexData.positions = positions;
  17501. vertexData.normals = normals;
  17502. vertexData.uvs = uvs;
  17503. return vertexData;
  17504. };
  17505. VertexData.CreatePlane = function (size) {
  17506. var indices = [];
  17507. var positions = [];
  17508. var normals = [];
  17509. var uvs = [];
  17510. size = size || 1;
  17511. var halfSize = size / 2.0;
  17512. positions.push(-halfSize, -halfSize, 0);
  17513. normals.push(0, 0, -1.0);
  17514. uvs.push(0.0, 0.0);
  17515. positions.push(halfSize, -halfSize, 0);
  17516. normals.push(0, 0, -1.0);
  17517. uvs.push(1.0, 0.0);
  17518. positions.push(halfSize, halfSize, 0);
  17519. normals.push(0, 0, -1.0);
  17520. uvs.push(1.0, 1.0);
  17521. positions.push(-halfSize, halfSize, 0);
  17522. normals.push(0, 0, -1.0);
  17523. uvs.push(0.0, 1.0);
  17524. indices.push(0);
  17525. indices.push(1);
  17526. indices.push(2);
  17527. indices.push(0);
  17528. indices.push(2);
  17529. indices.push(3);
  17530. var vertexData = new BABYLON.VertexData();
  17531. vertexData.indices = indices;
  17532. vertexData.positions = positions;
  17533. vertexData.normals = normals;
  17534. vertexData.uvs = uvs;
  17535. return vertexData;
  17536. };
  17537. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  17538. var indices = [];
  17539. var positions = [];
  17540. var normals = [];
  17541. var uvs = [];
  17542. radius = radius || 2;
  17543. tube = tube || 0.5;
  17544. radialSegments = radialSegments || 32;
  17545. tubularSegments = tubularSegments || 32;
  17546. p = p || 2;
  17547. q = q || 3;
  17548. var getPos = function (angle) {
  17549. var cu = Math.cos(angle);
  17550. var su = Math.sin(angle);
  17551. var quOverP = q / p * angle;
  17552. var cs = Math.cos(quOverP);
  17553. var tx = radius * (2 + cs) * 0.5 * cu;
  17554. var ty = radius * (2 + cs) * su * 0.5;
  17555. var tz = radius * Math.sin(quOverP) * 0.5;
  17556. return new BABYLON.Vector3(tx, ty, tz);
  17557. };
  17558. for (var i = 0; i <= radialSegments; i++) {
  17559. var modI = i % radialSegments;
  17560. var u = modI / radialSegments * 2 * p * Math.PI;
  17561. var p1 = getPos(u);
  17562. var p2 = getPos(u + 0.01);
  17563. var tang = p2.subtract(p1);
  17564. var n = p2.add(p1);
  17565. var bitan = BABYLON.Vector3.Cross(tang, n);
  17566. n = BABYLON.Vector3.Cross(bitan, tang);
  17567. bitan.normalize();
  17568. n.normalize();
  17569. for (var j = 0; j < tubularSegments; j++) {
  17570. var modJ = j % tubularSegments;
  17571. var v = modJ / tubularSegments * 2 * Math.PI;
  17572. var cx = -tube * Math.cos(v);
  17573. var cy = tube * Math.sin(v);
  17574. positions.push(p1.x + cx * n.x + cy * bitan.x);
  17575. positions.push(p1.y + cx * n.y + cy * bitan.y);
  17576. positions.push(p1.z + cx * n.z + cy * bitan.z);
  17577. uvs.push(i / radialSegments);
  17578. uvs.push(j / tubularSegments);
  17579. }
  17580. }
  17581. for (i = 0; i < radialSegments; i++) {
  17582. for (j = 0; j < tubularSegments; j++) {
  17583. var jNext = (j + 1) % tubularSegments;
  17584. var a = i * tubularSegments + j;
  17585. var b = (i + 1) * tubularSegments + j;
  17586. var c = (i + 1) * tubularSegments + jNext;
  17587. var d = i * tubularSegments + jNext;
  17588. indices.push(d);
  17589. indices.push(b);
  17590. indices.push(a);
  17591. indices.push(d);
  17592. indices.push(c);
  17593. indices.push(b);
  17594. }
  17595. }
  17596. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17597. var vertexData = new BABYLON.VertexData();
  17598. vertexData.indices = indices;
  17599. vertexData.positions = positions;
  17600. vertexData.normals = normals;
  17601. vertexData.uvs = uvs;
  17602. return vertexData;
  17603. };
  17604. VertexData.ComputeNormals = function (positions, indices, normals) {
  17605. var positionVectors = [];
  17606. var facesOfVertices = [];
  17607. var index;
  17608. for (index = 0; index < positions.length; index += 3) {
  17609. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  17610. positionVectors.push(vector3);
  17611. facesOfVertices.push([]);
  17612. }
  17613. var facesNormals = [];
  17614. for (index = 0; index < indices.length / 3; index++) {
  17615. var i1 = indices[index * 3];
  17616. var i2 = indices[index * 3 + 1];
  17617. var i3 = indices[index * 3 + 2];
  17618. var p1 = positionVectors[i1];
  17619. var p2 = positionVectors[i2];
  17620. var p3 = positionVectors[i3];
  17621. var p1p2 = p1.subtract(p2);
  17622. var p3p2 = p3.subtract(p2);
  17623. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  17624. facesOfVertices[i1].push(index);
  17625. facesOfVertices[i2].push(index);
  17626. facesOfVertices[i3].push(index);
  17627. }
  17628. for (index = 0; index < positionVectors.length; index++) {
  17629. var faces = facesOfVertices[index];
  17630. var normal = BABYLON.Vector3.Zero();
  17631. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  17632. normal.addInPlace(facesNormals[faces[faceIndex]]);
  17633. }
  17634. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  17635. normals[index * 3] = normal.x;
  17636. normals[index * 3 + 1] = normal.y;
  17637. normals[index * 3 + 2] = normal.z;
  17638. }
  17639. };
  17640. return VertexData;
  17641. })();
  17642. BABYLON.VertexData = VertexData;
  17643. })(BABYLON || (BABYLON = {}));
  17644. var __extends = this.__extends || function (d, b) {
  17645. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17646. function __() { this.constructor = d; }
  17647. __.prototype = b.prototype;
  17648. d.prototype = new __();
  17649. };
  17650. var BABYLON;
  17651. (function (BABYLON) {
  17652. var buildCamera = function (that, name) {
  17653. that._leftCamera.isIntermediate = true;
  17654. that.subCameras.push(that._leftCamera);
  17655. that.subCameras.push(that._rightCamera);
  17656. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  17657. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  17658. that._anaglyphPostProcess.onApply = function (effect) {
  17659. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  17660. };
  17661. that._update();
  17662. };
  17663. var AnaglyphArcRotateCamera = (function (_super) {
  17664. __extends(AnaglyphArcRotateCamera, _super);
  17665. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  17666. _super.call(this, name, alpha, beta, radius, target, scene);
  17667. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  17668. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  17669. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  17670. buildCamera(this, name);
  17671. }
  17672. AnaglyphArcRotateCamera.prototype._update = function () {
  17673. this._updateCamera(this._leftCamera);
  17674. this._updateCamera(this._rightCamera);
  17675. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  17676. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  17677. _super.prototype._update.call(this);
  17678. };
  17679. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  17680. camera.beta = this.beta;
  17681. camera.radius = this.radius;
  17682. camera.minZ = this.minZ;
  17683. camera.maxZ = this.maxZ;
  17684. camera.fov = this.fov;
  17685. camera.target = this.target;
  17686. };
  17687. return AnaglyphArcRotateCamera;
  17688. })(BABYLON.ArcRotateCamera);
  17689. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  17690. var AnaglyphFreeCamera = (function (_super) {
  17691. __extends(AnaglyphFreeCamera, _super);
  17692. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  17693. _super.call(this, name, position, scene);
  17694. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  17695. this._transformMatrix = new BABYLON.Matrix();
  17696. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  17697. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  17698. buildCamera(this, name);
  17699. }
  17700. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  17701. var target = this.getTarget();
  17702. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  17703. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  17704. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  17705. };
  17706. AnaglyphFreeCamera.prototype._update = function () {
  17707. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  17708. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  17709. this._updateCamera(this._leftCamera);
  17710. this._updateCamera(this._rightCamera);
  17711. _super.prototype._update.call(this);
  17712. };
  17713. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  17714. camera.minZ = this.minZ;
  17715. camera.maxZ = this.maxZ;
  17716. camera.fov = this.fov;
  17717. camera.viewport = this.viewport;
  17718. camera.setTarget(this.getTarget());
  17719. };
  17720. return AnaglyphFreeCamera;
  17721. })(BABYLON.FreeCamera);
  17722. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  17723. })(BABYLON || (BABYLON = {}));
  17724. var __extends = this.__extends || function (d, b) {
  17725. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17726. function __() { this.constructor = d; }
  17727. __.prototype = b.prototype;
  17728. d.prototype = new __();
  17729. };
  17730. var BABYLON;
  17731. (function (BABYLON) {
  17732. var AnaglyphPostProcess = (function (_super) {
  17733. __extends(AnaglyphPostProcess, _super);
  17734. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17735. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  17736. }
  17737. return AnaglyphPostProcess;
  17738. })(BABYLON.PostProcess);
  17739. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  17740. })(BABYLON || (BABYLON = {}));
  17741. var BABYLON;
  17742. (function (BABYLON) {
  17743. var Tags = (function () {
  17744. function Tags() {
  17745. }
  17746. Tags.EnableFor = function (obj) {
  17747. obj._tags = obj._tags || {};
  17748. obj.hasTags = function () {
  17749. return Tags.HasTags(obj);
  17750. };
  17751. obj.addTags = function (tagsString) {
  17752. return Tags.AddTagsTo(obj, tagsString);
  17753. };
  17754. obj.removeTags = function (tagsString) {
  17755. return Tags.RemoveTagsFrom(obj, tagsString);
  17756. };
  17757. obj.matchesTagsQuery = function (tagsQuery) {
  17758. return Tags.MatchesQuery(obj, tagsQuery);
  17759. };
  17760. };
  17761. Tags.DisableFor = function (obj) {
  17762. delete obj._tags;
  17763. delete obj.hasTags;
  17764. delete obj.addTags;
  17765. delete obj.removeTags;
  17766. delete obj.matchesTagsQuery;
  17767. };
  17768. Tags.HasTags = function (obj) {
  17769. if (!obj._tags) {
  17770. return false;
  17771. }
  17772. return !BABYLON.Tools.IsEmpty(obj._tags);
  17773. };
  17774. Tags.GetTags = function (obj) {
  17775. if (!obj._tags) {
  17776. return null;
  17777. }
  17778. return obj._tags;
  17779. };
  17780. Tags.AddTagsTo = function (obj, tagsString) {
  17781. if (!tagsString) {
  17782. return;
  17783. }
  17784. var tags = tagsString.split(" ");
  17785. for (var t in tags) {
  17786. Tags._AddTagTo(obj, tags[t]);
  17787. }
  17788. };
  17789. Tags._AddTagTo = function (obj, tag) {
  17790. tag = tag.trim();
  17791. if (tag === "" || tag === "true" || tag === "false") {
  17792. return;
  17793. }
  17794. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  17795. return;
  17796. }
  17797. Tags.EnableFor(obj);
  17798. obj._tags[tag] = true;
  17799. };
  17800. Tags.RemoveTagsFrom = function (obj, tagsString) {
  17801. if (!Tags.HasTags(obj)) {
  17802. return;
  17803. }
  17804. var tags = tagsString.split(" ");
  17805. for (var t in tags) {
  17806. Tags._RemoveTagFrom(obj, tags[t]);
  17807. }
  17808. };
  17809. Tags._RemoveTagFrom = function (obj, tag) {
  17810. delete obj._tags[tag];
  17811. };
  17812. Tags.MatchesQuery = function (obj, tagsQuery) {
  17813. if (tagsQuery === undefined) {
  17814. return true;
  17815. }
  17816. if (tagsQuery === "") {
  17817. return Tags.HasTags(obj);
  17818. }
  17819. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  17820. return Tags.HasTags(obj) && obj._tags[r];
  17821. });
  17822. };
  17823. return Tags;
  17824. })();
  17825. BABYLON.Tags = Tags;
  17826. })(BABYLON || (BABYLON = {}));
  17827. var BABYLON;
  17828. (function (BABYLON) {
  17829. (function (Internals) {
  17830. var AndOrNotEvaluator = (function () {
  17831. function AndOrNotEvaluator() {
  17832. }
  17833. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  17834. if (!query.match(/\([^\(\)]*\)/g)) {
  17835. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  17836. } else {
  17837. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  17838. r = r.slice(1, r.length - 1);
  17839. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  17840. });
  17841. }
  17842. if (query === "true") {
  17843. return true;
  17844. }
  17845. if (query === "false") {
  17846. return false;
  17847. }
  17848. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  17849. };
  17850. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  17851. evaluateCallback = evaluateCallback || (function (r) {
  17852. return r === "true" ? true : false;
  17853. });
  17854. var result;
  17855. var or = parenthesisContent.split("||");
  17856. for (var i in or) {
  17857. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  17858. var and = ori.split("&&");
  17859. if (and.length > 1) {
  17860. for (var j = 0; j < and.length; ++j) {
  17861. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  17862. if (andj !== "true" && andj !== "false") {
  17863. if (andj[0] === "!") {
  17864. result = !evaluateCallback(andj.substring(1));
  17865. } else {
  17866. result = evaluateCallback(andj);
  17867. }
  17868. } else {
  17869. result = andj === "true" ? true : false;
  17870. }
  17871. if (!result) {
  17872. ori = "false";
  17873. break;
  17874. }
  17875. }
  17876. }
  17877. if (result || ori === "true") {
  17878. result = true;
  17879. break;
  17880. }
  17881. if (ori !== "true" && ori !== "false") {
  17882. if (ori[0] === "!") {
  17883. result = !evaluateCallback(ori.substring(1));
  17884. } else {
  17885. result = evaluateCallback(ori);
  17886. }
  17887. } else {
  17888. result = ori === "true" ? true : false;
  17889. }
  17890. }
  17891. return result ? "true" : "false";
  17892. };
  17893. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  17894. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  17895. r = r.replace(/[\s]/g, function () {
  17896. return "";
  17897. });
  17898. return r.length % 2 ? "!" : "";
  17899. });
  17900. booleanString = booleanString.trim();
  17901. if (booleanString === "!true") {
  17902. booleanString = "false";
  17903. } else if (booleanString === "!false") {
  17904. booleanString = "true";
  17905. }
  17906. return booleanString;
  17907. };
  17908. return AndOrNotEvaluator;
  17909. })();
  17910. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  17911. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17912. var Internals = BABYLON.Internals;
  17913. })(BABYLON || (BABYLON = {}));
  17914. var BABYLON;
  17915. (function (BABYLON) {
  17916. var PostProcessRenderPass = (function () {
  17917. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  17918. this._enabled = true;
  17919. this._refCount = 0;
  17920. this._name = name;
  17921. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  17922. this.setRenderList(renderList);
  17923. this._renderTexture.onBeforeRender = beforeRender;
  17924. this._renderTexture.onAfterRender = afterRender;
  17925. this._scene = scene;
  17926. }
  17927. PostProcessRenderPass.prototype._incRefCount = function () {
  17928. if (this._refCount === 0) {
  17929. this._scene.customRenderTargets.push(this._renderTexture);
  17930. }
  17931. return ++this._refCount;
  17932. };
  17933. PostProcessRenderPass.prototype._decRefCount = function () {
  17934. this._refCount--;
  17935. if (this._refCount <= 0) {
  17936. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  17937. }
  17938. return this._refCount;
  17939. };
  17940. PostProcessRenderPass.prototype._update = function () {
  17941. this.setRenderList(this._renderList);
  17942. };
  17943. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  17944. this._renderTexture.renderList = renderList;
  17945. };
  17946. PostProcessRenderPass.prototype.getRenderTexture = function () {
  17947. return this._renderTexture;
  17948. };
  17949. return PostProcessRenderPass;
  17950. })();
  17951. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  17952. })(BABYLON || (BABYLON = {}));
  17953. var BABYLON;
  17954. (function (BABYLON) {
  17955. var PostProcessRenderEffect = (function () {
  17956. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  17957. this._engine = engine;
  17958. this._name = name;
  17959. this._singleInstance = singleInstance || true;
  17960. this._getPostProcess = getPostProcess;
  17961. this._cameras = [];
  17962. this._postProcesses = [];
  17963. this._indicesForCamera = [];
  17964. this._renderPasses = [];
  17965. this._renderEffectAsPasses = [];
  17966. }
  17967. PostProcessRenderEffect.prototype._update = function () {
  17968. for (var renderPassName in this._renderPasses) {
  17969. this._renderPasses[renderPassName]._update();
  17970. }
  17971. };
  17972. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  17973. this._renderPasses[renderPass._name] = renderPass;
  17974. this._linkParameters();
  17975. };
  17976. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  17977. delete this._renderPasses[renderPass._name];
  17978. this._linkParameters();
  17979. };
  17980. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  17981. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  17982. this._linkParameters();
  17983. };
  17984. PostProcessRenderEffect.prototype.getPass = function (passName) {
  17985. for (var renderPassName in this._renderPasses) {
  17986. if (renderPassName === passName) {
  17987. return this._renderPasses[passName];
  17988. }
  17989. }
  17990. };
  17991. PostProcessRenderEffect.prototype.emptyPasses = function () {
  17992. this._renderPasses.length = 0;
  17993. this._linkParameters();
  17994. };
  17995. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  17996. var cameraKey;
  17997. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  17998. for (var i = 0; i < _cam.length; i++) {
  17999. var camera = _cam[i];
  18000. var cameraName = camera.name;
  18001. if (this._singleInstance) {
  18002. cameraKey = 0;
  18003. } else {
  18004. cameraKey = cameraName;
  18005. }
  18006. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  18007. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  18008. if (!this._indicesForCamera[cameraName]) {
  18009. this._indicesForCamera[cameraName] = [];
  18010. }
  18011. this._indicesForCamera[cameraName].push(index);
  18012. if (this._cameras.indexOf(camera) === -1) {
  18013. this._cameras[cameraName] = camera;
  18014. }
  18015. for (var passName in this._renderPasses) {
  18016. this._renderPasses[passName]._incRefCount();
  18017. }
  18018. }
  18019. this._linkParameters();
  18020. };
  18021. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  18022. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18023. for (var i = 0; i < _cam.length; i++) {
  18024. var camera = _cam[i];
  18025. var cameraName = camera.name;
  18026. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  18027. var index = this._cameras.indexOf(cameraName);
  18028. this._indicesForCamera.splice(index, 1);
  18029. this._cameras.splice(index, 1);
  18030. for (var passName in this._renderPasses) {
  18031. this._renderPasses[passName]._decRefCount();
  18032. }
  18033. }
  18034. };
  18035. PostProcessRenderEffect.prototype._enable = function (cameras) {
  18036. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18037. for (var i = 0; i < _cam.length; i++) {
  18038. var camera = _cam[i];
  18039. var cameraName = camera.name;
  18040. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  18041. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  18042. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  18043. }
  18044. }
  18045. for (var passName in this._renderPasses) {
  18046. this._renderPasses[passName]._incRefCount();
  18047. }
  18048. }
  18049. };
  18050. PostProcessRenderEffect.prototype._disable = function (cameras) {
  18051. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18052. for (var i = 0; i < _cam.length; i++) {
  18053. var camera = _cam[i];
  18054. var cameraName = camera.Name;
  18055. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  18056. for (var passName in this._renderPasses) {
  18057. this._renderPasses[passName]._decRefCount();
  18058. }
  18059. }
  18060. };
  18061. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  18062. if (this._singleInstance) {
  18063. return this._postProcesses[0];
  18064. } else {
  18065. return this._postProcesses[camera.name];
  18066. }
  18067. };
  18068. PostProcessRenderEffect.prototype._linkParameters = function () {
  18069. var _this = this;
  18070. for (var index in this._postProcesses) {
  18071. if (this.applyParameters) {
  18072. this.applyParameters(this._postProcesses[index]);
  18073. }
  18074. this._postProcesses[index].onBeforeRender = function (effect) {
  18075. _this._linkTextures(effect);
  18076. };
  18077. }
  18078. };
  18079. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  18080. for (var renderPassName in this._renderPasses) {
  18081. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  18082. }
  18083. for (var renderEffectName in this._renderEffectAsPasses) {
  18084. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  18085. }
  18086. };
  18087. return PostProcessRenderEffect;
  18088. })();
  18089. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  18090. })(BABYLON || (BABYLON = {}));
  18091. var BABYLON;
  18092. (function (BABYLON) {
  18093. var PostProcessRenderPipeline = (function () {
  18094. function PostProcessRenderPipeline(engine, name) {
  18095. this._engine = engine;
  18096. this._name = name;
  18097. this._renderEffects = [];
  18098. this._renderEffectsForIsolatedPass = [];
  18099. this._cameras = [];
  18100. }
  18101. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  18102. this._renderEffects[renderEffect._name] = renderEffect;
  18103. };
  18104. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  18105. var renderEffects = this._renderEffects[renderEffectName];
  18106. if (!renderEffects) {
  18107. return;
  18108. }
  18109. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  18110. };
  18111. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  18112. var renderEffects = this._renderEffects[renderEffectName];
  18113. if (!renderEffects) {
  18114. return;
  18115. }
  18116. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  18117. };
  18118. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  18119. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18120. var indicesToDelete = [];
  18121. for (var i = 0; i < _cam.length; i++) {
  18122. var camera = _cam[i];
  18123. var cameraName = camera.name;
  18124. if (this._cameras.indexOf(camera) === -1) {
  18125. this._cameras[cameraName] = camera;
  18126. } else if (unique) {
  18127. indicesToDelete.push(i);
  18128. }
  18129. }
  18130. for (var i = 0; i < indicesToDelete.length; i++) {
  18131. cameras.splice(indicesToDelete[i], 1);
  18132. }
  18133. for (var renderEffectName in this._renderEffects) {
  18134. this._renderEffects[renderEffectName]._attachCameras(_cam);
  18135. }
  18136. };
  18137. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  18138. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18139. for (var renderEffectName in this._renderEffects) {
  18140. this._renderEffects[renderEffectName]._detachCameras(_cam);
  18141. }
  18142. for (var i = 0; i < _cam.length; i++) {
  18143. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  18144. }
  18145. };
  18146. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  18147. var _this = this;
  18148. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18149. var pass = null;
  18150. for (var renderEffectName in this._renderEffects) {
  18151. pass = this._renderEffects[renderEffectName].getPass(passName);
  18152. if (pass != null) {
  18153. break;
  18154. }
  18155. }
  18156. if (pass === null) {
  18157. return;
  18158. }
  18159. for (var renderEffectName in this._renderEffects) {
  18160. this._renderEffects[renderEffectName]._disable(_cam);
  18161. }
  18162. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  18163. for (var i = 0; i < _cam.length; i++) {
  18164. var camera = _cam[i];
  18165. var cameraName = camera.name;
  18166. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  18167. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  18168. });
  18169. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  18170. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  18171. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  18172. }
  18173. };
  18174. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  18175. var _this = this;
  18176. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18177. for (var i = 0; i < _cam.length; i++) {
  18178. var camera = _cam[i];
  18179. var cameraName = camera.name;
  18180. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  18181. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  18182. });
  18183. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  18184. }
  18185. for (var renderEffectName in this._renderEffects) {
  18186. this._renderEffects[renderEffectName]._enable(_cam);
  18187. }
  18188. };
  18189. PostProcessRenderPipeline.prototype._update = function () {
  18190. for (var renderEffectName in this._renderEffects) {
  18191. this._renderEffects[renderEffectName]._update();
  18192. }
  18193. for (var i = 0; i < this._cameras.length; i++) {
  18194. var cameraName = this._cameras[i].name;
  18195. if (this._renderEffectsForIsolatedPass[cameraName]) {
  18196. this._renderEffectsForIsolatedPass[cameraName]._update();
  18197. }
  18198. }
  18199. };
  18200. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  18201. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  18202. return PostProcessRenderPipeline;
  18203. })();
  18204. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  18205. })(BABYLON || (BABYLON = {}));
  18206. var BABYLON;
  18207. (function (BABYLON) {
  18208. var PostProcessRenderPipelineManager = (function () {
  18209. function PostProcessRenderPipelineManager() {
  18210. this._renderPipelines = new Array();
  18211. }
  18212. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  18213. this._renderPipelines[renderPipeline._name] = renderPipeline;
  18214. };
  18215. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  18216. var renderPipeline = this._renderPipelines[renderPipelineName];
  18217. if (!renderPipeline) {
  18218. return;
  18219. }
  18220. renderPipeline._attachCameras(cameras, unique);
  18221. };
  18222. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  18223. var renderPipeline = this._renderPipelines[renderPipelineName];
  18224. if (!renderPipeline) {
  18225. return;
  18226. }
  18227. renderPipeline._detachCameras(cameras);
  18228. };
  18229. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  18230. var renderPipeline = this._renderPipelines[renderPipelineName];
  18231. if (!renderPipeline) {
  18232. return;
  18233. }
  18234. renderPipeline._enableEffect(renderEffectName, cameras);
  18235. };
  18236. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  18237. var renderPipeline = this._renderPipelines[renderPipelineName];
  18238. if (!renderPipeline) {
  18239. return;
  18240. }
  18241. renderPipeline._disableEffect(renderEffectName, cameras);
  18242. };
  18243. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  18244. var renderPipeline = this._renderPipelines[renderPipelineName];
  18245. if (!renderPipeline) {
  18246. return;
  18247. }
  18248. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  18249. };
  18250. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  18251. var renderPipeline = this._renderPipelines[renderPipelineName];
  18252. if (!renderPipeline) {
  18253. return;
  18254. }
  18255. renderPipeline._disableDisplayOnlyPass(cameras);
  18256. };
  18257. PostProcessRenderPipelineManager.prototype.update = function () {
  18258. for (var renderPipelineName in this._renderPipelines) {
  18259. this._renderPipelines[renderPipelineName]._update();
  18260. }
  18261. };
  18262. return PostProcessRenderPipelineManager;
  18263. })();
  18264. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  18265. })(BABYLON || (BABYLON = {}));
  18266. var __extends = this.__extends || function (d, b) {
  18267. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18268. function __() { this.constructor = d; }
  18269. __.prototype = b.prototype;
  18270. d.prototype = new __();
  18271. };
  18272. var BABYLON;
  18273. (function (BABYLON) {
  18274. var DisplayPassPostProcess = (function (_super) {
  18275. __extends(DisplayPassPostProcess, _super);
  18276. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18277. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  18278. }
  18279. return DisplayPassPostProcess;
  18280. })(BABYLON.PostProcess);
  18281. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  18282. })(BABYLON || (BABYLON = {}));
  18283. var BABYLON;
  18284. (function (BABYLON) {
  18285. var BoundingBoxRenderer = (function () {
  18286. function BoundingBoxRenderer(scene) {
  18287. this.frontColor = new BABYLON.Color3(1, 1, 1);
  18288. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  18289. this.showBackLines = true;
  18290. this.renderList = new BABYLON.SmartArray(32);
  18291. this._scene = scene;
  18292. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  18293. attributes: ["position"],
  18294. uniforms: ["worldViewProjection", "color"]
  18295. });
  18296. var engine = this._scene.getEngine();
  18297. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  18298. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  18299. 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]);
  18300. }
  18301. BoundingBoxRenderer.prototype.reset = function () {
  18302. this.renderList.reset();
  18303. };
  18304. BoundingBoxRenderer.prototype.render = function () {
  18305. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  18306. return;
  18307. }
  18308. var engine = this._scene.getEngine();
  18309. engine.setDepthWrite(false);
  18310. this._colorShader._preBind();
  18311. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  18312. var boundingBox = this.renderList.data[boundingBoxIndex];
  18313. var min = boundingBox.minimum;
  18314. var max = boundingBox.maximum;
  18315. var diff = max.subtract(min);
  18316. var median = min.add(diff.scale(0.5));
  18317. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  18318. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  18319. if (this.showBackLines) {
  18320. engine.setDepthFunctionToGreaterOrEqual();
  18321. this._colorShader.setColor4("color", this.backColor.toColor4());
  18322. this._colorShader.bind(worldMatrix);
  18323. engine.draw(false, 0, 24);
  18324. }
  18325. engine.setDepthFunctionToLess();
  18326. this._colorShader.setColor4("color", this.frontColor.toColor4());
  18327. this._colorShader.bind(worldMatrix);
  18328. engine.draw(false, 0, 24);
  18329. }
  18330. this._colorShader.unbind();
  18331. engine.setDepthFunctionToLessOrEqual();
  18332. engine.setDepthWrite(true);
  18333. };
  18334. BoundingBoxRenderer.prototype.dispose = function () {
  18335. this._colorShader.dispose();
  18336. this._vb.dispose();
  18337. this._scene.getEngine()._releaseBuffer(this._ib);
  18338. };
  18339. return BoundingBoxRenderer;
  18340. })();
  18341. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  18342. })(BABYLON || (BABYLON = {}));
  18343. /**
  18344. * Based on jsTGALoader - Javascript loader for TGA file
  18345. * By Vincent Thibault
  18346. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  18347. */
  18348. var BABYLON;
  18349. (function (BABYLON) {
  18350. (function (Internals) {
  18351. var TGATools = (function () {
  18352. function TGATools() {
  18353. }
  18354. TGATools.GetTGAHeader = function (data) {
  18355. var offset = 0;
  18356. var header = {
  18357. id_length: data[offset++],
  18358. colormap_type: data[offset++],
  18359. image_type: data[offset++],
  18360. colormap_index: data[offset++] | data[offset++] << 8,
  18361. colormap_length: data[offset++] | data[offset++] << 8,
  18362. colormap_size: data[offset++],
  18363. origin: [
  18364. data[offset++] | data[offset++] << 8,
  18365. data[offset++] | data[offset++] << 8
  18366. ],
  18367. width: data[offset++] | data[offset++] << 8,
  18368. height: data[offset++] | data[offset++] << 8,
  18369. pixel_size: data[offset++],
  18370. flags: data[offset++]
  18371. };
  18372. return header;
  18373. };
  18374. TGATools.UploadContent = function (gl, data) {
  18375. if (data.length < 19) {
  18376. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  18377. return;
  18378. }
  18379. var offset = 18;
  18380. var header = TGATools.GetTGAHeader(data);
  18381. if (header.id_length + offset > data.length) {
  18382. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  18383. return;
  18384. }
  18385. offset += header.id_length;
  18386. var use_rle = false;
  18387. var use_pal = false;
  18388. var use_rgb = false;
  18389. var use_grey = false;
  18390. switch (header.image_type) {
  18391. case TGATools._TYPE_RLE_INDEXED:
  18392. use_rle = true;
  18393. case TGATools._TYPE_INDEXED:
  18394. use_pal = true;
  18395. break;
  18396. case TGATools._TYPE_RLE_RGB:
  18397. use_rle = true;
  18398. case TGATools._TYPE_RGB:
  18399. use_rgb = true;
  18400. break;
  18401. case TGATools._TYPE_RLE_GREY:
  18402. use_rle = true;
  18403. case TGATools._TYPE_GREY:
  18404. use_grey = true;
  18405. break;
  18406. }
  18407. var pixel_data;
  18408. var numAlphaBits = header.flags & 0xf;
  18409. var pixel_size = header.pixel_size >> 3;
  18410. var pixel_total = header.width * header.height * pixel_size;
  18411. var palettes;
  18412. if (use_pal) {
  18413. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  18414. }
  18415. if (use_rle) {
  18416. pixel_data = new Uint8Array(pixel_total);
  18417. var c, count, i;
  18418. var localOffset = 0;
  18419. var pixels = new Uint8Array(pixel_size);
  18420. while (offset < pixel_total && localOffset < pixel_total) {
  18421. c = data[offset++];
  18422. count = (c & 0x7f) + 1;
  18423. if (c & 0x80) {
  18424. for (i = 0; i < pixel_size; ++i) {
  18425. pixels[i] = data[offset++];
  18426. }
  18427. for (i = 0; i < count; ++i) {
  18428. pixel_data.set(pixels, localOffset + i * pixel_size);
  18429. }
  18430. localOffset += pixel_size * count;
  18431. } else {
  18432. count *= pixel_size;
  18433. for (i = 0; i < count; ++i) {
  18434. pixel_data[localOffset + i] = data[offset++];
  18435. }
  18436. localOffset += count;
  18437. }
  18438. }
  18439. } else {
  18440. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  18441. }
  18442. var x_start, y_start, x_step, y_step, y_end, x_end;
  18443. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  18444. default:
  18445. case TGATools._ORIGIN_UL:
  18446. x_start = 0;
  18447. x_step = 1;
  18448. x_end = header.width;
  18449. y_start = 0;
  18450. y_step = 1;
  18451. y_end = header.height;
  18452. break;
  18453. case TGATools._ORIGIN_BL:
  18454. x_start = 0;
  18455. x_step = 1;
  18456. x_end = header.width;
  18457. y_start = header.height - 1;
  18458. y_step = -1;
  18459. y_end = -1;
  18460. break;
  18461. case TGATools._ORIGIN_UR:
  18462. x_start = header.width - 1;
  18463. x_step = -1;
  18464. x_end = -1;
  18465. y_start = 0;
  18466. y_step = 1;
  18467. y_end = header.height;
  18468. break;
  18469. case TGATools._ORIGIN_BR:
  18470. x_start = header.width - 1;
  18471. x_step = -1;
  18472. x_end = -1;
  18473. y_start = header.height - 1;
  18474. y_step = -1;
  18475. y_end = -1;
  18476. break;
  18477. }
  18478. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  18479. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  18480. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  18481. };
  18482. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18483. var image = pixel_data, colormap = palettes;
  18484. var width = header.width, height = header.height;
  18485. var color, i = 0, x, y;
  18486. var imageData = new Uint8Array(width * height * 4);
  18487. for (y = y_start; y !== y_end; y += y_step) {
  18488. for (x = x_start; x !== x_end; x += x_step, i++) {
  18489. color = image[i];
  18490. imageData[(x + width * y) * 4 + 3] = 255;
  18491. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  18492. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  18493. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  18494. }
  18495. }
  18496. return imageData;
  18497. };
  18498. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18499. var image = pixel_data;
  18500. var width = header.width, height = header.height;
  18501. var color, i = 0, x, y;
  18502. var imageData = new Uint8Array(width * height * 4);
  18503. for (y = y_start; y !== y_end; y += y_step) {
  18504. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  18505. color = image[i + 0] + (image[i + 1] << 8);
  18506. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  18507. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  18508. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  18509. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  18510. }
  18511. }
  18512. return imageData;
  18513. };
  18514. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18515. var image = pixel_data;
  18516. var width = header.width, height = header.height;
  18517. var i = 0, x, y;
  18518. var imageData = new Uint8Array(width * height * 4);
  18519. for (y = y_start; y !== y_end; y += y_step) {
  18520. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  18521. imageData[(x + width * y) * 4 + 3] = 255;
  18522. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  18523. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  18524. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  18525. }
  18526. }
  18527. return imageData;
  18528. };
  18529. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18530. var image = pixel_data;
  18531. var width = header.width, height = header.height;
  18532. var i = 0, x, y;
  18533. var imageData = new Uint8Array(width * height * 4);
  18534. for (y = y_start; y !== y_end; y += y_step) {
  18535. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  18536. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  18537. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  18538. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  18539. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  18540. }
  18541. }
  18542. return imageData;
  18543. };
  18544. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18545. var image = pixel_data;
  18546. var width = header.width, height = header.height;
  18547. var color, i = 0, x, y;
  18548. var imageData = new Uint8Array(width * height * 4);
  18549. for (y = y_start; y !== y_end; y += y_step) {
  18550. for (x = x_start; x !== x_end; x += x_step, i++) {
  18551. color = image[i];
  18552. imageData[(x + width * y) * 4 + 0] = color;
  18553. imageData[(x + width * y) * 4 + 1] = color;
  18554. imageData[(x + width * y) * 4 + 2] = color;
  18555. imageData[(x + width * y) * 4 + 3] = 255;
  18556. }
  18557. }
  18558. return imageData;
  18559. };
  18560. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18561. var image = pixel_data;
  18562. var width = header.width, height = header.height;
  18563. var i = 0, x, y;
  18564. var imageData = new Uint8Array(width * height * 4);
  18565. for (y = y_start; y !== y_end; y += y_step) {
  18566. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  18567. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  18568. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  18569. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  18570. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  18571. }
  18572. }
  18573. return imageData;
  18574. };
  18575. TGATools._TYPE_NO_DATA = 0;
  18576. TGATools._TYPE_INDEXED = 1;
  18577. TGATools._TYPE_RGB = 2;
  18578. TGATools._TYPE_GREY = 3;
  18579. TGATools._TYPE_RLE_INDEXED = 9;
  18580. TGATools._TYPE_RLE_RGB = 10;
  18581. TGATools._TYPE_RLE_GREY = 11;
  18582. TGATools._ORIGIN_MASK = 0x30;
  18583. TGATools._ORIGIN_SHIFT = 0x04;
  18584. TGATools._ORIGIN_BL = 0x00;
  18585. TGATools._ORIGIN_BR = 0x01;
  18586. TGATools._ORIGIN_UL = 0x02;
  18587. TGATools._ORIGIN_UR = 0x03;
  18588. return TGATools;
  18589. })();
  18590. Internals.TGATools = TGATools;
  18591. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18592. var Internals = BABYLON.Internals;
  18593. })(BABYLON || (BABYLON = {}));
  18594. var BABYLON;
  18595. (function (BABYLON) {
  18596. (function (Internals) {
  18597. var DDS_MAGIC = 0x20534444;
  18598. 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;
  18599. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  18600. 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;
  18601. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  18602. function FourCCToInt32(value) {
  18603. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  18604. }
  18605. function Int32ToFourCC(value) {
  18606. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  18607. }
  18608. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  18609. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  18610. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  18611. var headerLengthInt = 31;
  18612. var off_magic = 0;
  18613. var off_size = 1;
  18614. var off_flags = 2;
  18615. var off_height = 3;
  18616. var off_width = 4;
  18617. var off_mipmapCount = 7;
  18618. var off_pfFlags = 20;
  18619. var off_pfFourCC = 21;
  18620. var off_RGBbpp = 22;
  18621. var off_RMask = 23;
  18622. var off_GMask = 24;
  18623. var off_BMask = 25;
  18624. var off_AMask = 26;
  18625. var off_caps1 = 27;
  18626. var off_caps2 = 28;
  18627. ;
  18628. var DDSTools = (function () {
  18629. function DDSTools() {
  18630. }
  18631. DDSTools.GetDDSInfo = function (arrayBuffer) {
  18632. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  18633. var mipmapCount = 1;
  18634. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  18635. mipmapCount = Math.max(1, header[off_mipmapCount]);
  18636. }
  18637. return {
  18638. width: header[off_width],
  18639. height: header[off_height],
  18640. mipmapCount: mipmapCount,
  18641. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  18642. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  18643. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  18644. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  18645. };
  18646. };
  18647. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  18648. var byteArray = new Uint8Array(dataLength);
  18649. var srcData = new Uint8Array(arrayBuffer);
  18650. var index = 0;
  18651. for (var y = height - 1; y >= 0; y--) {
  18652. for (var x = 0; x < width; x++) {
  18653. var srcPos = dataOffset + (x + y * width) * 4;
  18654. byteArray[index + 2] = srcData[srcPos];
  18655. byteArray[index + 1] = srcData[srcPos + 1];
  18656. byteArray[index] = srcData[srcPos + 2];
  18657. byteArray[index + 3] = srcData[srcPos + 3];
  18658. index += 4;
  18659. }
  18660. }
  18661. return byteArray;
  18662. };
  18663. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  18664. var byteArray = new Uint8Array(dataLength);
  18665. var srcData = new Uint8Array(arrayBuffer);
  18666. var index = 0;
  18667. for (var y = height - 1; y >= 0; y--) {
  18668. for (var x = 0; x < width; x++) {
  18669. var srcPos = dataOffset + (x + y * width) * 3;
  18670. byteArray[index + 2] = srcData[srcPos];
  18671. byteArray[index + 1] = srcData[srcPos + 1];
  18672. byteArray[index] = srcData[srcPos + 2];
  18673. index += 3;
  18674. }
  18675. }
  18676. return byteArray;
  18677. };
  18678. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  18679. var byteArray = new Uint8Array(dataLength);
  18680. var srcData = new Uint8Array(arrayBuffer);
  18681. var index = 0;
  18682. for (var y = height - 1; y >= 0; y--) {
  18683. for (var x = 0; x < width; x++) {
  18684. var srcPos = dataOffset + (x + y * width);
  18685. byteArray[index] = srcData[srcPos];
  18686. index++;
  18687. }
  18688. }
  18689. return byteArray;
  18690. };
  18691. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  18692. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  18693. if (header[off_magic] != DDS_MAGIC) {
  18694. BABYLON.Tools.Error("Invalid magic number in DDS header");
  18695. return;
  18696. }
  18697. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  18698. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  18699. return;
  18700. }
  18701. if (info.isFourCC) {
  18702. fourCC = header[off_pfFourCC];
  18703. switch (fourCC) {
  18704. case FOURCC_DXT1:
  18705. blockBytes = 8;
  18706. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  18707. break;
  18708. case FOURCC_DXT3:
  18709. blockBytes = 16;
  18710. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  18711. break;
  18712. case FOURCC_DXT5:
  18713. blockBytes = 16;
  18714. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  18715. break;
  18716. default:
  18717. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  18718. return;
  18719. }
  18720. }
  18721. mipmapCount = 1;
  18722. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  18723. mipmapCount = Math.max(1, header[off_mipmapCount]);
  18724. }
  18725. var bpp = header[off_RGBbpp];
  18726. for (var face = 0; face < faces; face++) {
  18727. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  18728. width = header[off_width];
  18729. height = header[off_height];
  18730. dataOffset = header[off_size] + 4;
  18731. for (i = 0; i < mipmapCount; ++i) {
  18732. if (info.isRGB) {
  18733. if (bpp == 24) {
  18734. dataLength = width * height * 3;
  18735. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  18736. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  18737. } else {
  18738. dataLength = width * height * 4;
  18739. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  18740. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  18741. }
  18742. } else if (info.isLuminance) {
  18743. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  18744. var unpaddedRowSize = width;
  18745. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  18746. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  18747. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  18748. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  18749. } else {
  18750. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  18751. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  18752. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  18753. }
  18754. dataOffset += dataLength;
  18755. width *= 0.5;
  18756. height *= 0.5;
  18757. width = Math.max(1.0, width);
  18758. height = Math.max(1.0, height);
  18759. }
  18760. }
  18761. };
  18762. return DDSTools;
  18763. })();
  18764. Internals.DDSTools = DDSTools;
  18765. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18766. var Internals = BABYLON.Internals;
  18767. })(BABYLON || (BABYLON = {}));
  18768. var BABYLON;
  18769. (function (BABYLON) {
  18770. var SmartArray = (function () {
  18771. function SmartArray(capacity) {
  18772. this.length = 0;
  18773. this._duplicateId = 0;
  18774. this.data = new Array(capacity);
  18775. this._id = SmartArray._GlobalId++;
  18776. }
  18777. SmartArray.prototype.push = function (value) {
  18778. this.data[this.length++] = value;
  18779. if (this.length > this.data.length) {
  18780. this.data.length *= 2;
  18781. }
  18782. if (!value.__smartArrayFlags) {
  18783. value.__smartArrayFlags = {};
  18784. }
  18785. value.__smartArrayFlags[this._id] = this._duplicateId;
  18786. };
  18787. SmartArray.prototype.pushNoDuplicate = function (value) {
  18788. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  18789. return;
  18790. }
  18791. this.push(value);
  18792. };
  18793. SmartArray.prototype.sort = function (compareFn) {
  18794. this.data.sort(compareFn);
  18795. };
  18796. SmartArray.prototype.reset = function () {
  18797. this.length = 0;
  18798. this._duplicateId++;
  18799. };
  18800. SmartArray.prototype.concat = function (array) {
  18801. if (array.length === 0) {
  18802. return;
  18803. }
  18804. if (this.length + array.length > this.data.length) {
  18805. this.data.length = (this.length + array.length) * 2;
  18806. }
  18807. for (var index = 0; index < array.length; index++) {
  18808. this.data[this.length++] = (array.data || array)[index];
  18809. }
  18810. };
  18811. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  18812. if (array.length === 0) {
  18813. return;
  18814. }
  18815. if (this.length + array.length > this.data.length) {
  18816. this.data.length = (this.length + array.length) * 2;
  18817. }
  18818. for (var index = 0; index < array.length; index++) {
  18819. var item = (array.data || array)[index];
  18820. this.pushNoDuplicate(item);
  18821. }
  18822. };
  18823. SmartArray.prototype.indexOf = function (value) {
  18824. var position = this.data.indexOf(value);
  18825. if (position >= this.length) {
  18826. return -1;
  18827. }
  18828. return position;
  18829. };
  18830. SmartArray._GlobalId = 0;
  18831. return SmartArray;
  18832. })();
  18833. BABYLON.SmartArray = SmartArray;
  18834. })(BABYLON || (BABYLON = {}));
  18835. var BABYLON;
  18836. (function (BABYLON) {
  18837. var CannonJSPlugin = (function () {
  18838. function CannonJSPlugin() {
  18839. this._registeredMeshes = [];
  18840. this._physicsMaterials = [];
  18841. this.updateBodyPosition = function (mesh) {
  18842. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18843. var registeredMesh = this._registeredMeshes[index];
  18844. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18845. var body = registeredMesh.body;
  18846. var center = mesh.getBoundingInfo().boundingBox.center;
  18847. body.position.set(center.x, center.z, center.y);
  18848. body.quaternion.x = mesh.rotationQuaternion.x;
  18849. body.quaternion.z = mesh.rotationQuaternion.y;
  18850. body.quaternion.y = mesh.rotationQuaternion.z;
  18851. body.quaternion.w = -mesh.rotationQuaternion.w;
  18852. return;
  18853. }
  18854. }
  18855. };
  18856. }
  18857. CannonJSPlugin.prototype.initialize = function (iterations) {
  18858. if (typeof iterations === "undefined") { iterations = 10; }
  18859. this._world = new CANNON.World();
  18860. this._world.broadphase = new CANNON.NaiveBroadphase();
  18861. this._world.solver.iterations = iterations;
  18862. };
  18863. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  18864. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  18865. };
  18866. CannonJSPlugin.prototype.runOneStep = function (delta) {
  18867. this._world.step(delta);
  18868. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18869. var registeredMesh = this._registeredMeshes[index];
  18870. if (registeredMesh.isChild) {
  18871. continue;
  18872. }
  18873. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  18874. var deltaPos = registeredMesh.delta;
  18875. if (deltaPos) {
  18876. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  18877. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  18878. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  18879. } else {
  18880. registeredMesh.mesh.position.x = bodyX;
  18881. registeredMesh.mesh.position.y = bodyZ;
  18882. registeredMesh.mesh.position.z = bodyY;
  18883. }
  18884. if (!registeredMesh.mesh.rotationQuaternion) {
  18885. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18886. }
  18887. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  18888. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  18889. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  18890. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  18891. }
  18892. };
  18893. CannonJSPlugin.prototype.setGravity = function (gravity) {
  18894. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  18895. };
  18896. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  18897. this.unregisterMesh(mesh);
  18898. mesh.computeWorldMatrix(true);
  18899. switch (impostor) {
  18900. case BABYLON.PhysicsEngine.SphereImpostor:
  18901. var bbox = mesh.getBoundingInfo().boundingBox;
  18902. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18903. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18904. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18905. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  18906. case BABYLON.PhysicsEngine.BoxImpostor:
  18907. bbox = mesh.getBoundingInfo().boundingBox;
  18908. var min = bbox.minimumWorld;
  18909. var max = bbox.maximumWorld;
  18910. var box = max.subtract(min).scale(0.5);
  18911. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  18912. case BABYLON.PhysicsEngine.PlaneImpostor:
  18913. return this._createPlane(mesh, options);
  18914. case BABYLON.PhysicsEngine.MeshImpostor:
  18915. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18916. var rawFaces = mesh.getIndices();
  18917. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  18918. }
  18919. return null;
  18920. };
  18921. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  18922. var shape = new CANNON.Sphere(radius);
  18923. if (!options) {
  18924. return shape;
  18925. }
  18926. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18927. };
  18928. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  18929. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  18930. if (!options) {
  18931. return shape;
  18932. }
  18933. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18934. };
  18935. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  18936. var shape = new CANNON.Plane();
  18937. if (!options) {
  18938. return shape;
  18939. }
  18940. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18941. };
  18942. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  18943. var verts = [], faces = [];
  18944. mesh.computeWorldMatrix(true);
  18945. for (var i = 0; i < rawVerts.length; i += 3) {
  18946. var transformed = BABYLON.Vector3.Zero();
  18947. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  18948. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  18949. }
  18950. for (var j = 0; j < rawFaces.length; j += 3) {
  18951. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  18952. }
  18953. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  18954. if (!options) {
  18955. return shape;
  18956. }
  18957. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  18958. };
  18959. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  18960. var index;
  18961. var mat;
  18962. for (index = 0; index < this._physicsMaterials.length; index++) {
  18963. mat = this._physicsMaterials[index];
  18964. if (mat.friction === friction && mat.restitution === restitution) {
  18965. return mat;
  18966. }
  18967. }
  18968. var currentMat = new CANNON.Material();
  18969. currentMat.friction = friction;
  18970. currentMat.restitution = restitution;
  18971. this._physicsMaterials.push(currentMat);
  18972. for (index = 0; index < this._physicsMaterials.length; index++) {
  18973. mat = this._physicsMaterials[index];
  18974. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  18975. contactMaterial.contactEquationStiffness = 1e10;
  18976. contactMaterial.contactEquationRegularizationTime = 10;
  18977. this._world.addContactMaterial(contactMaterial);
  18978. }
  18979. return currentMat;
  18980. };
  18981. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  18982. var initialRotation = null;
  18983. if (mesh.rotationQuaternion) {
  18984. initialRotation = mesh.rotationQuaternion.clone();
  18985. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18986. }
  18987. var bbox = mesh.getBoundingInfo().boundingBox;
  18988. var deltaPosition = mesh.position.subtract(bbox.center);
  18989. var material = this._addMaterial(friction, restitution);
  18990. var body = new CANNON.RigidBody(mass, shape, material);
  18991. if (initialRotation) {
  18992. body.quaternion.x = initialRotation.x;
  18993. body.quaternion.z = initialRotation.y;
  18994. body.quaternion.y = initialRotation.z;
  18995. body.quaternion.w = -initialRotation.w;
  18996. }
  18997. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  18998. this._world.add(body);
  18999. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  19000. return body;
  19001. };
  19002. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  19003. var compoundShape = new CANNON.Compound();
  19004. for (var index = 0; index < parts.length; index++) {
  19005. var mesh = parts[index].mesh;
  19006. var shape = this.registerMesh(mesh, parts[index].impostor);
  19007. if (index == 0) {
  19008. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  19009. } else {
  19010. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  19011. }
  19012. }
  19013. var initialMesh = parts[0].mesh;
  19014. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  19015. body.parts = parts;
  19016. return body;
  19017. };
  19018. CannonJSPlugin.prototype._unbindBody = function (body) {
  19019. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19020. var registeredMesh = this._registeredMeshes[index];
  19021. if (registeredMesh.body === body) {
  19022. registeredMesh.body = null;
  19023. registeredMesh.delta = 0;
  19024. }
  19025. }
  19026. };
  19027. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  19028. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19029. var registeredMesh = this._registeredMeshes[index];
  19030. if (registeredMesh.mesh === mesh) {
  19031. if (registeredMesh.body) {
  19032. this._world.remove(registeredMesh.body);
  19033. this._unbindBody(registeredMesh.body);
  19034. }
  19035. this._registeredMeshes.splice(index, 1);
  19036. return;
  19037. }
  19038. }
  19039. };
  19040. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  19041. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  19042. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  19043. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19044. var registeredMesh = this._registeredMeshes[index];
  19045. if (registeredMesh.mesh === mesh) {
  19046. registeredMesh.body.applyImpulse(impulse, worldPoint);
  19047. return;
  19048. }
  19049. }
  19050. };
  19051. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  19052. var body1 = null, body2 = null;
  19053. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19054. var registeredMesh = this._registeredMeshes[index];
  19055. if (registeredMesh.mesh === mesh1) {
  19056. body1 = registeredMesh.body;
  19057. } else if (registeredMesh.mesh === mesh2) {
  19058. body2 = registeredMesh.body;
  19059. }
  19060. }
  19061. if (!body1 || !body2) {
  19062. return false;
  19063. }
  19064. 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));
  19065. this._world.addConstraint(constraint);
  19066. return true;
  19067. };
  19068. CannonJSPlugin.prototype.dispose = function () {
  19069. while (this._registeredMeshes.length) {
  19070. this.unregisterMesh(this._registeredMeshes[0].mesh);
  19071. }
  19072. };
  19073. CannonJSPlugin.prototype.isSupported = function () {
  19074. return window.CANNON !== undefined;
  19075. };
  19076. return CannonJSPlugin;
  19077. })();
  19078. BABYLON.CannonJSPlugin = CannonJSPlugin;
  19079. })(BABYLON || (BABYLON = {}));
  19080. var __extends = this.__extends || function (d, b) {
  19081. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19082. function __() { this.constructor = d; }
  19083. __.prototype = b.prototype;
  19084. d.prototype = new __();
  19085. };
  19086. var BABYLON;
  19087. (function (BABYLON) {
  19088. var Condition = (function () {
  19089. function Condition(actionManager) {
  19090. this._actionManager = actionManager;
  19091. }
  19092. Condition.prototype.isValid = function () {
  19093. return true;
  19094. };
  19095. Condition.prototype._getProperty = function (propertyPath) {
  19096. return this._actionManager._getProperty(propertyPath);
  19097. };
  19098. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  19099. return this._actionManager._getEffectiveTarget(target, propertyPath);
  19100. };
  19101. return Condition;
  19102. })();
  19103. BABYLON.Condition = Condition;
  19104. var ValueCondition = (function (_super) {
  19105. __extends(ValueCondition, _super);
  19106. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  19107. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  19108. _super.call(this, actionManager);
  19109. this.propertyPath = propertyPath;
  19110. this.value = value;
  19111. this.operator = operator;
  19112. this._target = this._getEffectiveTarget(target, this.propertyPath);
  19113. this._property = this._getProperty(this.propertyPath);
  19114. }
  19115. Object.defineProperty(ValueCondition, "IsEqual", {
  19116. get: function () {
  19117. return ValueCondition._IsEqual;
  19118. },
  19119. enumerable: true,
  19120. configurable: true
  19121. });
  19122. Object.defineProperty(ValueCondition, "IsDifferent", {
  19123. get: function () {
  19124. return ValueCondition._IsDifferent;
  19125. },
  19126. enumerable: true,
  19127. configurable: true
  19128. });
  19129. Object.defineProperty(ValueCondition, "IsGreater", {
  19130. get: function () {
  19131. return ValueCondition._IsGreater;
  19132. },
  19133. enumerable: true,
  19134. configurable: true
  19135. });
  19136. Object.defineProperty(ValueCondition, "IsLesser", {
  19137. get: function () {
  19138. return ValueCondition._IsLesser;
  19139. },
  19140. enumerable: true,
  19141. configurable: true
  19142. });
  19143. ValueCondition.prototype.isValid = function () {
  19144. switch (this.operator) {
  19145. case ValueCondition.IsGreater:
  19146. return this._target[this._property] > this.value;
  19147. case ValueCondition.IsLesser:
  19148. return this._target[this._property] < this.value;
  19149. case ValueCondition.IsEqual:
  19150. case ValueCondition.IsDifferent:
  19151. var check;
  19152. if (this.value.equals) {
  19153. check = this.value.equals(this._target[this._property]);
  19154. } else {
  19155. check = this.value === this._target[this._property];
  19156. }
  19157. return this.operator === ValueCondition.IsEqual ? check : !check;
  19158. }
  19159. return false;
  19160. };
  19161. ValueCondition._IsEqual = 0;
  19162. ValueCondition._IsDifferent = 1;
  19163. ValueCondition._IsGreater = 2;
  19164. ValueCondition._IsLesser = 3;
  19165. return ValueCondition;
  19166. })(Condition);
  19167. BABYLON.ValueCondition = ValueCondition;
  19168. var PredicateCondition = (function (_super) {
  19169. __extends(PredicateCondition, _super);
  19170. function PredicateCondition(actionManager, predicate) {
  19171. _super.call(this, actionManager);
  19172. this.predicate = predicate;
  19173. }
  19174. PredicateCondition.prototype.isValid = function () {
  19175. return this.predicate();
  19176. };
  19177. return PredicateCondition;
  19178. })(Condition);
  19179. BABYLON.PredicateCondition = PredicateCondition;
  19180. var StateCondition = (function (_super) {
  19181. __extends(StateCondition, _super);
  19182. function StateCondition(actionManager, target, value) {
  19183. _super.call(this, actionManager);
  19184. this.value = value;
  19185. this._target = target;
  19186. }
  19187. StateCondition.prototype.isValid = function () {
  19188. return this._target.state === this.value;
  19189. };
  19190. return StateCondition;
  19191. })(Condition);
  19192. BABYLON.StateCondition = StateCondition;
  19193. })(BABYLON || (BABYLON = {}));
  19194. var BABYLON;
  19195. (function (BABYLON) {
  19196. var Action = (function () {
  19197. function Action(triggerOptions, condition) {
  19198. this.triggerOptions = triggerOptions;
  19199. if (triggerOptions.parameter) {
  19200. this.trigger = triggerOptions.trigger;
  19201. this._triggerParameter = triggerOptions.parameter;
  19202. } else {
  19203. this.trigger = triggerOptions;
  19204. }
  19205. this._nextActiveAction = this;
  19206. this._condition = condition;
  19207. }
  19208. Action.prototype._prepare = function () {
  19209. };
  19210. Action.prototype.getTriggerParameter = function () {
  19211. return this._triggerParameter;
  19212. };
  19213. Action.prototype._executeCurrent = function (evt) {
  19214. if (this._condition) {
  19215. var currentRenderId = this._actionManager.getScene().getRenderId();
  19216. if (this._condition._evaluationId === currentRenderId) {
  19217. if (!this._condition._currentResult) {
  19218. return;
  19219. }
  19220. } else {
  19221. this._condition._evaluationId = currentRenderId;
  19222. if (!this._condition.isValid()) {
  19223. this._condition._currentResult = false;
  19224. return;
  19225. }
  19226. this._condition._currentResult = true;
  19227. }
  19228. }
  19229. this._nextActiveAction.execute(evt);
  19230. if (this._nextActiveAction._child) {
  19231. if (!this._nextActiveAction._child._actionManager) {
  19232. this._nextActiveAction._child._actionManager = this._actionManager;
  19233. }
  19234. this._nextActiveAction = this._nextActiveAction._child;
  19235. } else {
  19236. this._nextActiveAction = this;
  19237. }
  19238. };
  19239. Action.prototype.execute = function (evt) {
  19240. };
  19241. Action.prototype.then = function (action) {
  19242. this._child = action;
  19243. action._actionManager = this._actionManager;
  19244. action._prepare();
  19245. return action;
  19246. };
  19247. Action.prototype._getProperty = function (propertyPath) {
  19248. return this._actionManager._getProperty(propertyPath);
  19249. };
  19250. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  19251. return this._actionManager._getEffectiveTarget(target, propertyPath);
  19252. };
  19253. return Action;
  19254. })();
  19255. BABYLON.Action = Action;
  19256. })(BABYLON || (BABYLON = {}));
  19257. var BABYLON;
  19258. (function (BABYLON) {
  19259. var ActionEvent = (function () {
  19260. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  19261. this.source = source;
  19262. this.pointerX = pointerX;
  19263. this.pointerY = pointerY;
  19264. this.meshUnderPointer = meshUnderPointer;
  19265. this.sourceEvent = sourceEvent;
  19266. }
  19267. ActionEvent.CreateNew = function (source) {
  19268. var scene = source.getScene();
  19269. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer);
  19270. };
  19271. ActionEvent.CreateNewFromScene = function (scene, evt) {
  19272. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  19273. };
  19274. return ActionEvent;
  19275. })();
  19276. BABYLON.ActionEvent = ActionEvent;
  19277. var ActionManager = (function () {
  19278. function ActionManager(scene) {
  19279. this.actions = new Array();
  19280. this._scene = scene;
  19281. scene._actionManagers.push(this);
  19282. }
  19283. Object.defineProperty(ActionManager, "NothingTrigger", {
  19284. get: function () {
  19285. return ActionManager._NothingTrigger;
  19286. },
  19287. enumerable: true,
  19288. configurable: true
  19289. });
  19290. Object.defineProperty(ActionManager, "OnPickTrigger", {
  19291. get: function () {
  19292. return ActionManager._OnPickTrigger;
  19293. },
  19294. enumerable: true,
  19295. configurable: true
  19296. });
  19297. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  19298. get: function () {
  19299. return ActionManager._OnLeftPickTrigger;
  19300. },
  19301. enumerable: true,
  19302. configurable: true
  19303. });
  19304. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  19305. get: function () {
  19306. return ActionManager._OnRightPickTrigger;
  19307. },
  19308. enumerable: true,
  19309. configurable: true
  19310. });
  19311. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  19312. get: function () {
  19313. return ActionManager._OnCenterPickTrigger;
  19314. },
  19315. enumerable: true,
  19316. configurable: true
  19317. });
  19318. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  19319. get: function () {
  19320. return ActionManager._OnPointerOverTrigger;
  19321. },
  19322. enumerable: true,
  19323. configurable: true
  19324. });
  19325. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  19326. get: function () {
  19327. return ActionManager._OnPointerOutTrigger;
  19328. },
  19329. enumerable: true,
  19330. configurable: true
  19331. });
  19332. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  19333. get: function () {
  19334. return ActionManager._OnEveryFrameTrigger;
  19335. },
  19336. enumerable: true,
  19337. configurable: true
  19338. });
  19339. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  19340. get: function () {
  19341. return ActionManager._OnIntersectionEnterTrigger;
  19342. },
  19343. enumerable: true,
  19344. configurable: true
  19345. });
  19346. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  19347. get: function () {
  19348. return ActionManager._OnIntersectionExitTrigger;
  19349. },
  19350. enumerable: true,
  19351. configurable: true
  19352. });
  19353. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  19354. get: function () {
  19355. return ActionManager._OnKeyDownTrigger;
  19356. },
  19357. enumerable: true,
  19358. configurable: true
  19359. });
  19360. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  19361. get: function () {
  19362. return ActionManager._OnKeyUpTrigger;
  19363. },
  19364. enumerable: true,
  19365. configurable: true
  19366. });
  19367. ActionManager.prototype.dispose = function () {
  19368. var index = this._scene._actionManagers.indexOf(this);
  19369. if (index > -1) {
  19370. this._scene._actionManagers.splice(index, 1);
  19371. }
  19372. };
  19373. ActionManager.prototype.getScene = function () {
  19374. return this._scene;
  19375. };
  19376. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  19377. for (var index = 0; index < this.actions.length; index++) {
  19378. var action = this.actions[index];
  19379. if (triggers.indexOf(action.trigger) > -1) {
  19380. return true;
  19381. }
  19382. }
  19383. return false;
  19384. };
  19385. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  19386. get: function () {
  19387. for (var index = 0; index < this.actions.length; index++) {
  19388. var action = this.actions[index];
  19389. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  19390. return true;
  19391. }
  19392. }
  19393. return false;
  19394. },
  19395. enumerable: true,
  19396. configurable: true
  19397. });
  19398. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  19399. get: function () {
  19400. for (var index = 0; index < this.actions.length; index++) {
  19401. var action = this.actions[index];
  19402. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  19403. return true;
  19404. }
  19405. }
  19406. return false;
  19407. },
  19408. enumerable: true,
  19409. configurable: true
  19410. });
  19411. ActionManager.prototype.registerAction = function (action) {
  19412. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  19413. if (this.getScene().actionManager !== this) {
  19414. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  19415. return null;
  19416. }
  19417. }
  19418. this.actions.push(action);
  19419. action._actionManager = this;
  19420. action._prepare();
  19421. return action;
  19422. };
  19423. ActionManager.prototype.processTrigger = function (trigger, evt) {
  19424. for (var index = 0; index < this.actions.length; index++) {
  19425. var action = this.actions[index];
  19426. if (action.trigger === trigger) {
  19427. if (trigger == ActionManager.OnKeyUpTrigger || trigger == ActionManager.OnKeyDownTrigger) {
  19428. var parameter = action.getTriggerParameter();
  19429. if (parameter) {
  19430. if (evt.sourceEvent.key !== parameter) {
  19431. continue;
  19432. }
  19433. }
  19434. }
  19435. action._executeCurrent(evt);
  19436. }
  19437. }
  19438. };
  19439. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  19440. var properties = propertyPath.split(".");
  19441. for (var index = 0; index < properties.length - 1; index++) {
  19442. target = target[properties[index]];
  19443. }
  19444. return target;
  19445. };
  19446. ActionManager.prototype._getProperty = function (propertyPath) {
  19447. var properties = propertyPath.split(".");
  19448. return properties[properties.length - 1];
  19449. };
  19450. ActionManager._NothingTrigger = 0;
  19451. ActionManager._OnPickTrigger = 1;
  19452. ActionManager._OnLeftPickTrigger = 2;
  19453. ActionManager._OnRightPickTrigger = 3;
  19454. ActionManager._OnCenterPickTrigger = 4;
  19455. ActionManager._OnPointerOverTrigger = 5;
  19456. ActionManager._OnPointerOutTrigger = 6;
  19457. ActionManager._OnEveryFrameTrigger = 7;
  19458. ActionManager._OnIntersectionEnterTrigger = 8;
  19459. ActionManager._OnIntersectionExitTrigger = 9;
  19460. ActionManager._OnKeyDownTrigger = 10;
  19461. ActionManager._OnKeyUpTrigger = 11;
  19462. return ActionManager;
  19463. })();
  19464. BABYLON.ActionManager = ActionManager;
  19465. })(BABYLON || (BABYLON = {}));
  19466. var __extends = this.__extends || function (d, b) {
  19467. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19468. function __() { this.constructor = d; }
  19469. __.prototype = b.prototype;
  19470. d.prototype = new __();
  19471. };
  19472. var BABYLON;
  19473. (function (BABYLON) {
  19474. var InterpolateValueAction = (function (_super) {
  19475. __extends(InterpolateValueAction, _super);
  19476. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  19477. if (typeof duration === "undefined") { duration = 1000; }
  19478. _super.call(this, triggerOptions, condition);
  19479. this.propertyPath = propertyPath;
  19480. this.value = value;
  19481. this.duration = duration;
  19482. this.stopOtherAnimations = stopOtherAnimations;
  19483. this._target = target;
  19484. }
  19485. InterpolateValueAction.prototype._prepare = function () {
  19486. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19487. this._property = this._getProperty(this.propertyPath);
  19488. };
  19489. InterpolateValueAction.prototype.execute = function () {
  19490. var scene = this._actionManager.getScene();
  19491. var keys = [
  19492. {
  19493. frame: 0,
  19494. value: this._target[this._property]
  19495. }, {
  19496. frame: 100,
  19497. value: this.value
  19498. }
  19499. ];
  19500. var dataType;
  19501. if (typeof this.value === "number") {
  19502. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  19503. } else if (this.value instanceof BABYLON.Color3) {
  19504. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  19505. } else if (this.value instanceof BABYLON.Vector3) {
  19506. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  19507. } else if (this.value instanceof BABYLON.Matrix) {
  19508. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  19509. } else if (this.value instanceof BABYLON.Quaternion) {
  19510. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  19511. } else {
  19512. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  19513. return;
  19514. }
  19515. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  19516. animation.setKeys(keys);
  19517. if (this.stopOtherAnimations) {
  19518. scene.stopAnimation(this._target);
  19519. }
  19520. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  19521. };
  19522. return InterpolateValueAction;
  19523. })(BABYLON.Action);
  19524. BABYLON.InterpolateValueAction = InterpolateValueAction;
  19525. })(BABYLON || (BABYLON = {}));
  19526. var __extends = this.__extends || function (d, b) {
  19527. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19528. function __() { this.constructor = d; }
  19529. __.prototype = b.prototype;
  19530. d.prototype = new __();
  19531. };
  19532. var BABYLON;
  19533. (function (BABYLON) {
  19534. var SwitchBooleanAction = (function (_super) {
  19535. __extends(SwitchBooleanAction, _super);
  19536. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  19537. _super.call(this, triggerOptions, condition);
  19538. this.propertyPath = propertyPath;
  19539. this._target = target;
  19540. }
  19541. SwitchBooleanAction.prototype._prepare = function () {
  19542. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19543. this._property = this._getProperty(this.propertyPath);
  19544. };
  19545. SwitchBooleanAction.prototype.execute = function () {
  19546. this._target[this._property] = !this._target[this._property];
  19547. };
  19548. return SwitchBooleanAction;
  19549. })(BABYLON.Action);
  19550. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  19551. var SetStateAction = (function (_super) {
  19552. __extends(SetStateAction, _super);
  19553. function SetStateAction(triggerOptions, target, value, condition) {
  19554. _super.call(this, triggerOptions, condition);
  19555. this.value = value;
  19556. this._target = target;
  19557. }
  19558. SetStateAction.prototype.execute = function () {
  19559. this._target.state = this.value;
  19560. };
  19561. return SetStateAction;
  19562. })(BABYLON.Action);
  19563. BABYLON.SetStateAction = SetStateAction;
  19564. var SetValueAction = (function (_super) {
  19565. __extends(SetValueAction, _super);
  19566. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  19567. _super.call(this, triggerOptions, condition);
  19568. this.propertyPath = propertyPath;
  19569. this.value = value;
  19570. this._target = target;
  19571. }
  19572. SetValueAction.prototype._prepare = function () {
  19573. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19574. this._property = this._getProperty(this.propertyPath);
  19575. };
  19576. SetValueAction.prototype.execute = function () {
  19577. this._target[this._property] = this.value;
  19578. };
  19579. return SetValueAction;
  19580. })(BABYLON.Action);
  19581. BABYLON.SetValueAction = SetValueAction;
  19582. var IncrementValueAction = (function (_super) {
  19583. __extends(IncrementValueAction, _super);
  19584. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  19585. _super.call(this, triggerOptions, condition);
  19586. this.propertyPath = propertyPath;
  19587. this.value = value;
  19588. this._target = target;
  19589. }
  19590. IncrementValueAction.prototype._prepare = function () {
  19591. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19592. this._property = this._getProperty(this.propertyPath);
  19593. if (typeof this._target[this._property] !== "number") {
  19594. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  19595. }
  19596. };
  19597. IncrementValueAction.prototype.execute = function () {
  19598. this._target[this._property] += this.value;
  19599. };
  19600. return IncrementValueAction;
  19601. })(BABYLON.Action);
  19602. BABYLON.IncrementValueAction = IncrementValueAction;
  19603. var PlayAnimationAction = (function (_super) {
  19604. __extends(PlayAnimationAction, _super);
  19605. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  19606. _super.call(this, triggerOptions, condition);
  19607. this.from = from;
  19608. this.to = to;
  19609. this.loop = loop;
  19610. this._target = target;
  19611. }
  19612. PlayAnimationAction.prototype._prepare = function () {
  19613. };
  19614. PlayAnimationAction.prototype.execute = function () {
  19615. var scene = this._actionManager.getScene();
  19616. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  19617. };
  19618. return PlayAnimationAction;
  19619. })(BABYLON.Action);
  19620. BABYLON.PlayAnimationAction = PlayAnimationAction;
  19621. var StopAnimationAction = (function (_super) {
  19622. __extends(StopAnimationAction, _super);
  19623. function StopAnimationAction(triggerOptions, target, condition) {
  19624. _super.call(this, triggerOptions, condition);
  19625. this._target = target;
  19626. }
  19627. StopAnimationAction.prototype._prepare = function () {
  19628. };
  19629. StopAnimationAction.prototype.execute = function () {
  19630. var scene = this._actionManager.getScene();
  19631. scene.stopAnimation(this._target);
  19632. };
  19633. return StopAnimationAction;
  19634. })(BABYLON.Action);
  19635. BABYLON.StopAnimationAction = StopAnimationAction;
  19636. var DoNothingAction = (function (_super) {
  19637. __extends(DoNothingAction, _super);
  19638. function DoNothingAction(triggerOptions, condition) {
  19639. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  19640. _super.call(this, triggerOptions, condition);
  19641. }
  19642. DoNothingAction.prototype.execute = function () {
  19643. };
  19644. return DoNothingAction;
  19645. })(BABYLON.Action);
  19646. BABYLON.DoNothingAction = DoNothingAction;
  19647. var CombineAction = (function (_super) {
  19648. __extends(CombineAction, _super);
  19649. function CombineAction(triggerOptions, children, condition) {
  19650. _super.call(this, triggerOptions, condition);
  19651. this.children = children;
  19652. }
  19653. CombineAction.prototype._prepare = function () {
  19654. for (var index = 0; index < this.children.length; index++) {
  19655. this.children[index]._actionManager = this._actionManager;
  19656. this.children[index]._prepare();
  19657. }
  19658. };
  19659. CombineAction.prototype.execute = function (evt) {
  19660. for (var index = 0; index < this.children.length; index++) {
  19661. this.children[index].execute(evt);
  19662. }
  19663. };
  19664. return CombineAction;
  19665. })(BABYLON.Action);
  19666. BABYLON.CombineAction = CombineAction;
  19667. var ExecuteCodeAction = (function (_super) {
  19668. __extends(ExecuteCodeAction, _super);
  19669. function ExecuteCodeAction(triggerOptions, func, condition) {
  19670. _super.call(this, triggerOptions, condition);
  19671. this.func = func;
  19672. }
  19673. ExecuteCodeAction.prototype.execute = function (evt) {
  19674. this.func(evt);
  19675. };
  19676. return ExecuteCodeAction;
  19677. })(BABYLON.Action);
  19678. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  19679. var SetParentAction = (function (_super) {
  19680. __extends(SetParentAction, _super);
  19681. function SetParentAction(triggerOptions, target, parent, condition) {
  19682. _super.call(this, triggerOptions, condition);
  19683. this._target = target;
  19684. this._parent = parent;
  19685. }
  19686. SetParentAction.prototype._prepare = function () {
  19687. };
  19688. SetParentAction.prototype.execute = function () {
  19689. if (this._target.parent === this._parent) {
  19690. return;
  19691. }
  19692. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  19693. invertParentWorldMatrix.invert();
  19694. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  19695. this._target.parent = this._parent;
  19696. };
  19697. return SetParentAction;
  19698. })(BABYLON.Action);
  19699. BABYLON.SetParentAction = SetParentAction;
  19700. })(BABYLON || (BABYLON = {}));
  19701. var __extends = this.__extends || function (d, b) {
  19702. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19703. function __() { this.constructor = d; }
  19704. __.prototype = b.prototype;
  19705. d.prototype = new __();
  19706. };
  19707. var BABYLON;
  19708. (function (BABYLON) {
  19709. var Geometry = (function () {
  19710. function Geometry(id, scene, vertexData, updatable, mesh) {
  19711. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19712. this._totalVertices = 0;
  19713. this._indices = [];
  19714. this.id = id;
  19715. this._engine = scene.getEngine();
  19716. this._meshes = [];
  19717. this._scene = scene;
  19718. if (vertexData) {
  19719. this.setAllVerticesData(vertexData, updatable);
  19720. } else {
  19721. this._totalVertices = 0;
  19722. this._indices = [];
  19723. }
  19724. if (mesh) {
  19725. this.applyToMesh(mesh);
  19726. }
  19727. }
  19728. Geometry.prototype.getScene = function () {
  19729. return this._scene;
  19730. };
  19731. Geometry.prototype.getEngine = function () {
  19732. return this._engine;
  19733. };
  19734. Geometry.prototype.isReady = function () {
  19735. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  19736. };
  19737. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  19738. vertexData.applyToGeometry(this, updatable);
  19739. };
  19740. Geometry.prototype.setVerticesData = function (kind, data, updatable) {
  19741. this._vertexBuffers = this._vertexBuffers || {};
  19742. if (this._vertexBuffers[kind]) {
  19743. this._vertexBuffers[kind].dispose();
  19744. }
  19745. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0);
  19746. if (kind === BABYLON.VertexBuffer.PositionKind) {
  19747. var stride = this._vertexBuffers[kind].getStrideSize();
  19748. this._totalVertices = data.length / stride;
  19749. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  19750. var meshes = this._meshes;
  19751. var numOfMeshes = meshes.length;
  19752. for (var index = 0; index < numOfMeshes; index++) {
  19753. var mesh = meshes[index];
  19754. mesh._resetPointsArrayCache();
  19755. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19756. mesh._createGlobalSubMesh();
  19757. mesh.computeWorldMatrix(true);
  19758. }
  19759. }
  19760. };
  19761. Geometry.prototype.updateVerticesDataDirectly = function (kind, data) {
  19762. var vertexBuffer = this.getVertexBuffer(kind);
  19763. if (!vertexBuffer) {
  19764. return;
  19765. }
  19766. vertexBuffer.updateDirectly(data);
  19767. };
  19768. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  19769. var vertexBuffer = this.getVertexBuffer(kind);
  19770. if (!vertexBuffer) {
  19771. return;
  19772. }
  19773. vertexBuffer.update(data);
  19774. if (kind === BABYLON.VertexBuffer.PositionKind) {
  19775. var extend;
  19776. if (updateExtends) {
  19777. var stride = vertexBuffer.getStrideSize();
  19778. this._totalVertices = data.length / stride;
  19779. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  19780. }
  19781. var meshes = this._meshes;
  19782. var numOfMeshes = meshes.length;
  19783. for (var index = 0; index < numOfMeshes; index++) {
  19784. var mesh = meshes[index];
  19785. mesh._resetPointsArrayCache();
  19786. if (updateExtends) {
  19787. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19788. }
  19789. }
  19790. }
  19791. };
  19792. Geometry.prototype.getTotalVertices = function () {
  19793. if (!this.isReady()) {
  19794. return 0;
  19795. }
  19796. return this._totalVertices;
  19797. };
  19798. Geometry.prototype.getVerticesData = function (kind) {
  19799. var vertexBuffer = this.getVertexBuffer(kind);
  19800. if (!vertexBuffer) {
  19801. return null;
  19802. }
  19803. return vertexBuffer.getData();
  19804. };
  19805. Geometry.prototype.getVertexBuffer = function (kind) {
  19806. if (!this.isReady()) {
  19807. return null;
  19808. }
  19809. return this._vertexBuffers[kind];
  19810. };
  19811. Geometry.prototype.getVertexBuffers = function () {
  19812. if (!this.isReady()) {
  19813. return null;
  19814. }
  19815. return this._vertexBuffers;
  19816. };
  19817. Geometry.prototype.isVerticesDataPresent = function (kind) {
  19818. if (!this._vertexBuffers) {
  19819. if (this._delayInfo) {
  19820. return this._delayInfo.indexOf(kind) !== -1;
  19821. }
  19822. return false;
  19823. }
  19824. return this._vertexBuffers[kind] !== undefined;
  19825. };
  19826. Geometry.prototype.getVerticesDataKinds = function () {
  19827. var result = [];
  19828. if (!this._vertexBuffers && this._delayInfo) {
  19829. for (var kind in this._delayInfo) {
  19830. result.push(kind);
  19831. }
  19832. } else {
  19833. for (kind in this._vertexBuffers) {
  19834. result.push(kind);
  19835. }
  19836. }
  19837. return result;
  19838. };
  19839. Geometry.prototype.setIndices = function (indices) {
  19840. if (this._indexBuffer) {
  19841. this._engine._releaseBuffer(this._indexBuffer);
  19842. }
  19843. this._indices = indices;
  19844. if (this._meshes.length !== 0 && this._indices) {
  19845. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  19846. }
  19847. var meshes = this._meshes;
  19848. var numOfMeshes = meshes.length;
  19849. for (var index = 0; index < numOfMeshes; index++) {
  19850. meshes[index]._createGlobalSubMesh();
  19851. }
  19852. };
  19853. Geometry.prototype.getTotalIndices = function () {
  19854. if (!this.isReady()) {
  19855. return 0;
  19856. }
  19857. return this._indices.length;
  19858. };
  19859. Geometry.prototype.getIndices = function () {
  19860. if (!this.isReady()) {
  19861. return null;
  19862. }
  19863. return this._indices;
  19864. };
  19865. Geometry.prototype.getIndexBuffer = function () {
  19866. if (!this.isReady()) {
  19867. return null;
  19868. }
  19869. return this._indexBuffer;
  19870. };
  19871. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  19872. var meshes = this._meshes;
  19873. var index = meshes.indexOf(mesh);
  19874. if (index === -1) {
  19875. return;
  19876. }
  19877. for (var kind in this._vertexBuffers) {
  19878. this._vertexBuffers[kind].dispose();
  19879. }
  19880. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  19881. this._indexBuffer = null;
  19882. }
  19883. meshes.splice(index, 1);
  19884. mesh._geometry = null;
  19885. if (meshes.length == 0 && shouldDispose) {
  19886. this.dispose();
  19887. }
  19888. };
  19889. Geometry.prototype.applyToMesh = function (mesh) {
  19890. if (mesh._geometry === this) {
  19891. return;
  19892. }
  19893. var previousGeometry = mesh._geometry;
  19894. if (previousGeometry) {
  19895. previousGeometry.releaseForMesh(mesh);
  19896. }
  19897. var meshes = this._meshes;
  19898. mesh._geometry = this;
  19899. this._scene.pushGeometry(this);
  19900. meshes.push(mesh);
  19901. if (this.isReady()) {
  19902. this._applyToMesh(mesh);
  19903. } else {
  19904. mesh._boundingInfo = this._boundingInfo;
  19905. }
  19906. };
  19907. Geometry.prototype._applyToMesh = function (mesh) {
  19908. var numOfMeshes = this._meshes.length;
  19909. for (var kind in this._vertexBuffers) {
  19910. if (numOfMeshes === 1) {
  19911. this._vertexBuffers[kind].create();
  19912. }
  19913. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  19914. if (kind === BABYLON.VertexBuffer.PositionKind) {
  19915. mesh._resetPointsArrayCache();
  19916. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  19917. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19918. mesh._createGlobalSubMesh();
  19919. }
  19920. }
  19921. if (numOfMeshes === 1 && this._indices) {
  19922. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  19923. }
  19924. if (this._indexBuffer) {
  19925. this._indexBuffer.references = numOfMeshes;
  19926. }
  19927. };
  19928. Geometry.prototype.load = function (scene, onLoaded) {
  19929. var _this = this;
  19930. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19931. return;
  19932. }
  19933. if (this.isReady()) {
  19934. if (onLoaded) {
  19935. onLoaded();
  19936. }
  19937. return;
  19938. }
  19939. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19940. scene._addPendingData(this);
  19941. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19942. _this._delayLoadingFunction(JSON.parse(data), _this);
  19943. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19944. _this._delayInfo = [];
  19945. scene._removePendingData(_this);
  19946. var meshes = _this._meshes;
  19947. var numOfMeshes = meshes.length;
  19948. for (var index = 0; index < numOfMeshes; index++) {
  19949. _this._applyToMesh(meshes[index]);
  19950. }
  19951. if (onLoaded) {
  19952. onLoaded();
  19953. }
  19954. }, function () {
  19955. }, scene.database);
  19956. };
  19957. Geometry.prototype.dispose = function () {
  19958. var meshes = this._meshes;
  19959. var numOfMeshes = meshes.length;
  19960. for (var index = 0; index < numOfMeshes; index++) {
  19961. this.releaseForMesh(meshes[index]);
  19962. }
  19963. this._meshes = [];
  19964. for (var kind in this._vertexBuffers) {
  19965. this._vertexBuffers[kind].dispose();
  19966. }
  19967. this._vertexBuffers = [];
  19968. this._totalVertices = 0;
  19969. if (this._indexBuffer) {
  19970. this._engine._releaseBuffer(this._indexBuffer);
  19971. }
  19972. this._indexBuffer = null;
  19973. this._indices = [];
  19974. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19975. this.delayLoadingFile = null;
  19976. this._delayLoadingFunction = null;
  19977. this._delayInfo = [];
  19978. this._boundingInfo = null;
  19979. var geometries = this._scene.getGeometries();
  19980. index = geometries.indexOf(this);
  19981. if (index > -1) {
  19982. geometries.splice(index, 1);
  19983. }
  19984. };
  19985. Geometry.prototype.copy = function (id) {
  19986. var vertexData = new BABYLON.VertexData();
  19987. vertexData.indices = [];
  19988. var indices = this.getIndices();
  19989. for (var index = 0; index < indices.length; index++) {
  19990. vertexData.indices.push(indices[index]);
  19991. }
  19992. var updatable = false;
  19993. var stopChecking = false;
  19994. for (var kind in this._vertexBuffers) {
  19995. vertexData.set(this.getVerticesData(kind), kind);
  19996. if (!stopChecking) {
  19997. updatable = this.getVertexBuffer(kind).isUpdatable();
  19998. stopChecking = !updatable;
  19999. }
  20000. }
  20001. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  20002. geometry.delayLoadState = this.delayLoadState;
  20003. geometry.delayLoadingFile = this.delayLoadingFile;
  20004. geometry._delayLoadingFunction = this._delayLoadingFunction;
  20005. for (kind in this._delayInfo) {
  20006. geometry._delayInfo = geometry._delayInfo || [];
  20007. geometry._delayInfo.push(kind);
  20008. }
  20009. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  20010. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20011. return geometry;
  20012. };
  20013. Geometry.ExtractFromMesh = function (mesh, id) {
  20014. var geometry = mesh._geometry;
  20015. if (!geometry) {
  20016. return null;
  20017. }
  20018. return geometry.copy(id);
  20019. };
  20020. Geometry.RandomId = function () {
  20021. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  20022. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  20023. return v.toString(16);
  20024. });
  20025. };
  20026. return Geometry;
  20027. })();
  20028. BABYLON.Geometry = Geometry;
  20029. (function (Geometry) {
  20030. (function (Primitives) {
  20031. var _Primitive = (function (_super) {
  20032. __extends(_Primitive, _super);
  20033. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  20034. this._beingRegenerated = true;
  20035. this._canBeRegenerated = canBeRegenerated;
  20036. _super.call(this, id, scene, vertexData, false, mesh);
  20037. this._beingRegenerated = false;
  20038. }
  20039. _Primitive.prototype.canBeRegenerated = function () {
  20040. return this._canBeRegenerated;
  20041. };
  20042. _Primitive.prototype.regenerate = function () {
  20043. if (!this._canBeRegenerated) {
  20044. return;
  20045. }
  20046. this._beingRegenerated = true;
  20047. this.setAllVerticesData(this._regenerateVertexData(), false);
  20048. this._beingRegenerated = false;
  20049. };
  20050. _Primitive.prototype.asNewGeometry = function (id) {
  20051. return _super.prototype.copy.call(this, id);
  20052. };
  20053. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  20054. if (!this._beingRegenerated) {
  20055. return;
  20056. }
  20057. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  20058. };
  20059. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  20060. if (!this._beingRegenerated) {
  20061. return;
  20062. }
  20063. _super.prototype.setVerticesData.call(this, kind, data, false);
  20064. };
  20065. _Primitive.prototype._regenerateVertexData = function () {
  20066. throw new Error("Abstract method");
  20067. };
  20068. _Primitive.prototype.copy = function (id) {
  20069. throw new Error("Must be overriden in sub-classes.");
  20070. };
  20071. return _Primitive;
  20072. })(Geometry);
  20073. Primitives._Primitive = _Primitive;
  20074. var Box = (function (_super) {
  20075. __extends(Box, _super);
  20076. function Box(id, scene, size, canBeRegenerated, mesh) {
  20077. this.size = size;
  20078. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20079. }
  20080. Box.prototype._regenerateVertexData = function () {
  20081. return BABYLON.VertexData.CreateBox(this.size);
  20082. };
  20083. Box.prototype.copy = function (id) {
  20084. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  20085. };
  20086. return Box;
  20087. })(_Primitive);
  20088. Primitives.Box = Box;
  20089. var Sphere = (function (_super) {
  20090. __extends(Sphere, _super);
  20091. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  20092. this.segments = segments;
  20093. this.diameter = diameter;
  20094. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20095. }
  20096. Sphere.prototype._regenerateVertexData = function () {
  20097. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  20098. };
  20099. Sphere.prototype.copy = function (id) {
  20100. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  20101. };
  20102. return Sphere;
  20103. })(_Primitive);
  20104. Primitives.Sphere = Sphere;
  20105. var Cylinder = (function (_super) {
  20106. __extends(Cylinder, _super);
  20107. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  20108. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  20109. this.height = height;
  20110. this.diameterTop = diameterTop;
  20111. this.diameterBottom = diameterBottom;
  20112. this.tessellation = tessellation;
  20113. this.subdivisions = subdivisions;
  20114. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20115. }
  20116. Cylinder.prototype._regenerateVertexData = function () {
  20117. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  20118. };
  20119. Cylinder.prototype.copy = function (id) {
  20120. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  20121. };
  20122. return Cylinder;
  20123. })(_Primitive);
  20124. Primitives.Cylinder = Cylinder;
  20125. var Torus = (function (_super) {
  20126. __extends(Torus, _super);
  20127. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  20128. this.diameter = diameter;
  20129. this.thickness = thickness;
  20130. this.tessellation = tessellation;
  20131. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20132. }
  20133. Torus.prototype._regenerateVertexData = function () {
  20134. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  20135. };
  20136. Torus.prototype.copy = function (id) {
  20137. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  20138. };
  20139. return Torus;
  20140. })(_Primitive);
  20141. Primitives.Torus = Torus;
  20142. var Ground = (function (_super) {
  20143. __extends(Ground, _super);
  20144. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  20145. this.width = width;
  20146. this.height = height;
  20147. this.subdivisions = subdivisions;
  20148. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20149. }
  20150. Ground.prototype._regenerateVertexData = function () {
  20151. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  20152. };
  20153. Ground.prototype.copy = function (id) {
  20154. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  20155. };
  20156. return Ground;
  20157. })(_Primitive);
  20158. Primitives.Ground = Ground;
  20159. var TiledGround = (function (_super) {
  20160. __extends(TiledGround, _super);
  20161. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  20162. this.xmin = xmin;
  20163. this.zmin = zmin;
  20164. this.xmax = xmax;
  20165. this.zmax = zmax;
  20166. this.subdivisions = subdivisions;
  20167. this.precision = precision;
  20168. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20169. }
  20170. TiledGround.prototype._regenerateVertexData = function () {
  20171. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  20172. };
  20173. TiledGround.prototype.copy = function (id) {
  20174. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  20175. };
  20176. return TiledGround;
  20177. })(_Primitive);
  20178. Primitives.TiledGround = TiledGround;
  20179. var Plane = (function (_super) {
  20180. __extends(Plane, _super);
  20181. function Plane(id, scene, size, canBeRegenerated, mesh) {
  20182. this.size = size;
  20183. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20184. }
  20185. Plane.prototype._regenerateVertexData = function () {
  20186. return BABYLON.VertexData.CreatePlane(this.size);
  20187. };
  20188. Plane.prototype.copy = function (id) {
  20189. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  20190. };
  20191. return Plane;
  20192. })(_Primitive);
  20193. Primitives.Plane = Plane;
  20194. var TorusKnot = (function (_super) {
  20195. __extends(TorusKnot, _super);
  20196. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  20197. this.radius = radius;
  20198. this.tube = tube;
  20199. this.radialSegments = radialSegments;
  20200. this.tubularSegments = tubularSegments;
  20201. this.p = p;
  20202. this.q = q;
  20203. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20204. }
  20205. TorusKnot.prototype._regenerateVertexData = function () {
  20206. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  20207. };
  20208. TorusKnot.prototype.copy = function (id) {
  20209. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  20210. };
  20211. return TorusKnot;
  20212. })(_Primitive);
  20213. Primitives.TorusKnot = TorusKnot;
  20214. })(Geometry.Primitives || (Geometry.Primitives = {}));
  20215. var Primitives = Geometry.Primitives;
  20216. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  20217. var Geometry = BABYLON.Geometry;
  20218. })(BABYLON || (BABYLON = {}));
  20219. var __extends = this.__extends || function (d, b) {
  20220. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20221. function __() { this.constructor = d; }
  20222. __.prototype = b.prototype;
  20223. d.prototype = new __();
  20224. };
  20225. var BABYLON;
  20226. (function (BABYLON) {
  20227. var Gamepads = (function () {
  20228. function Gamepads(ongamedpadconnected) {
  20229. var _this = this;
  20230. this.babylonGamepads = [];
  20231. this.oneGamepadConnected = false;
  20232. this.isMonitoring = false;
  20233. this.gamepadEventSupported = 'GamepadEvent' in window;
  20234. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  20235. 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=";
  20236. this._callbackGamepadConnected = ongamedpadconnected;
  20237. if (this.gamepadSupportAvailable) {
  20238. if (this.gamepadEventSupported) {
  20239. window.addEventListener('gamepadconnected', function (evt) {
  20240. _this._onGamepadConnected(evt);
  20241. }, false);
  20242. window.addEventListener('gamepaddisconnected', function (evt) {
  20243. _this._onGamepadDisconnected(evt);
  20244. }, false);
  20245. } else {
  20246. this._startMonitoringGamepads();
  20247. }
  20248. if (!this.oneGamepadConnected) {
  20249. this._insertGamepadDOMInstructions();
  20250. }
  20251. } else {
  20252. this._insertGamepadDOMNotSupported();
  20253. }
  20254. }
  20255. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  20256. Gamepads.gamepadDOMInfo = document.createElement("div");
  20257. var buttonAImage = document.createElement("img");
  20258. buttonAImage.src = this.buttonADataURL;
  20259. var spanMessage = document.createElement("span");
  20260. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  20261. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  20262. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  20263. Gamepads.gamepadDOMInfo.style.position = "absolute";
  20264. Gamepads.gamepadDOMInfo.style.width = "100%";
  20265. Gamepads.gamepadDOMInfo.style.height = "48px";
  20266. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  20267. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  20268. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  20269. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  20270. buttonAImage.style.position = "relative";
  20271. buttonAImage.style.bottom = "8px";
  20272. spanMessage.style.position = "relative";
  20273. spanMessage.style.fontSize = "32px";
  20274. spanMessage.style.bottom = "32px";
  20275. spanMessage.style.color = "green";
  20276. document.body.appendChild(Gamepads.gamepadDOMInfo);
  20277. };
  20278. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  20279. Gamepads.gamepadDOMInfo = document.createElement("div");
  20280. var spanMessage = document.createElement("span");
  20281. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  20282. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  20283. Gamepads.gamepadDOMInfo.style.position = "absolute";
  20284. Gamepads.gamepadDOMInfo.style.width = "100%";
  20285. Gamepads.gamepadDOMInfo.style.height = "40px";
  20286. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  20287. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  20288. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  20289. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  20290. spanMessage.style.position = "relative";
  20291. spanMessage.style.fontSize = "32px";
  20292. spanMessage.style.color = "red";
  20293. document.body.appendChild(Gamepads.gamepadDOMInfo);
  20294. };
  20295. Gamepads.prototype.dispose = function () {
  20296. document.body.removeChild(Gamepads.gamepadDOMInfo);
  20297. };
  20298. Gamepads.prototype._onGamepadConnected = function (evt) {
  20299. var newGamepad = this._addNewGamepad(evt.gamepad);
  20300. if (this._callbackGamepadConnected)
  20301. this._callbackGamepadConnected(newGamepad);
  20302. this._startMonitoringGamepads();
  20303. };
  20304. Gamepads.prototype._addNewGamepad = function (gamepad) {
  20305. if (!this.oneGamepadConnected) {
  20306. this.oneGamepadConnected = true;
  20307. if (Gamepads.gamepadDOMInfo) {
  20308. document.body.removeChild(Gamepads.gamepadDOMInfo);
  20309. Gamepads.gamepadDOMInfo = null;
  20310. }
  20311. }
  20312. var newGamepad;
  20313. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  20314. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  20315. } else {
  20316. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  20317. }
  20318. this.babylonGamepads.push(newGamepad);
  20319. return newGamepad;
  20320. };
  20321. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  20322. for (var i in this.babylonGamepads) {
  20323. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  20324. this.babylonGamepads.splice(i, 1);
  20325. break;
  20326. }
  20327. }
  20328. if (this.babylonGamepads.length == 0) {
  20329. this._stopMonitoringGamepads();
  20330. }
  20331. };
  20332. Gamepads.prototype._startMonitoringGamepads = function () {
  20333. if (!this.isMonitoring) {
  20334. this.isMonitoring = true;
  20335. this._checkGamepadsStatus();
  20336. }
  20337. };
  20338. Gamepads.prototype._stopMonitoringGamepads = function () {
  20339. this.isMonitoring = false;
  20340. };
  20341. Gamepads.prototype._checkGamepadsStatus = function () {
  20342. var _this = this;
  20343. this._updateGamepadObjects();
  20344. for (var i in this.babylonGamepads) {
  20345. this.babylonGamepads[i].update();
  20346. }
  20347. if (this.isMonitoring) {
  20348. if (window.requestAnimationFrame) {
  20349. window.requestAnimationFrame(function () {
  20350. _this._checkGamepadsStatus();
  20351. });
  20352. } else if (window.mozRequestAnimationFrame) {
  20353. window.mozRequestAnimationFrame(function () {
  20354. _this._checkGamepadsStatus();
  20355. });
  20356. } else if (window.webkitRequestAnimationFrame) {
  20357. window.webkitRequestAnimationFrame(function () {
  20358. _this._checkGamepadsStatus();
  20359. });
  20360. }
  20361. }
  20362. };
  20363. Gamepads.prototype._updateGamepadObjects = function () {
  20364. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  20365. for (var i = 0; i < gamepads.length; i++) {
  20366. if (gamepads[i]) {
  20367. if (!(gamepads[i].index in this.babylonGamepads)) {
  20368. var newGamepad = this._addNewGamepad(gamepads[i]);
  20369. if (this._callbackGamepadConnected) {
  20370. this._callbackGamepadConnected(newGamepad);
  20371. }
  20372. } else {
  20373. this.babylonGamepads[i].browserGamepad = gamepads[i];
  20374. }
  20375. }
  20376. }
  20377. };
  20378. return Gamepads;
  20379. })();
  20380. BABYLON.Gamepads = Gamepads;
  20381. var StickValues = (function () {
  20382. function StickValues(x, y) {
  20383. this.x = x;
  20384. this.y = y;
  20385. }
  20386. return StickValues;
  20387. })();
  20388. BABYLON.StickValues = StickValues;
  20389. var Gamepad = (function () {
  20390. function Gamepad(id, index, browserGamepad) {
  20391. this.id = id;
  20392. this.index = index;
  20393. this.browserGamepad = browserGamepad;
  20394. if (this.browserGamepad.axes.length >= 2) {
  20395. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  20396. }
  20397. if (this.browserGamepad.axes.length >= 4) {
  20398. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  20399. }
  20400. }
  20401. Gamepad.prototype.onleftstickchanged = function (callback) {
  20402. this._onleftstickchanged = callback;
  20403. };
  20404. Gamepad.prototype.onrightstickchanged = function (callback) {
  20405. this._onrightstickchanged = callback;
  20406. };
  20407. Object.defineProperty(Gamepad.prototype, "leftStick", {
  20408. get: function () {
  20409. return this._leftStick;
  20410. },
  20411. set: function (newValues) {
  20412. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  20413. this._onleftstickchanged(newValues);
  20414. }
  20415. this._leftStick = newValues;
  20416. },
  20417. enumerable: true,
  20418. configurable: true
  20419. });
  20420. Object.defineProperty(Gamepad.prototype, "rightStick", {
  20421. get: function () {
  20422. return this._rightStick;
  20423. },
  20424. set: function (newValues) {
  20425. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  20426. this._onrightstickchanged(newValues);
  20427. }
  20428. this._rightStick = newValues;
  20429. },
  20430. enumerable: true,
  20431. configurable: true
  20432. });
  20433. Gamepad.prototype.update = function () {
  20434. if (this._leftStick) {
  20435. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  20436. }
  20437. if (this._rightStick) {
  20438. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  20439. }
  20440. };
  20441. return Gamepad;
  20442. })();
  20443. BABYLON.Gamepad = Gamepad;
  20444. var GenericPad = (function (_super) {
  20445. __extends(GenericPad, _super);
  20446. function GenericPad(id, index, gamepad) {
  20447. _super.call(this, id, index, gamepad);
  20448. this.id = id;
  20449. this.index = index;
  20450. this.gamepad = gamepad;
  20451. this._buttons = new Array(gamepad.buttons.length);
  20452. }
  20453. GenericPad.prototype.onbuttondown = function (callback) {
  20454. this._onbuttondown = callback;
  20455. };
  20456. GenericPad.prototype.onbuttonup = function (callback) {
  20457. this._onbuttonup = callback;
  20458. };
  20459. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  20460. if (newValue !== currentValue) {
  20461. if (this._onbuttondown && newValue === 1) {
  20462. this._onbuttondown(buttonIndex);
  20463. }
  20464. if (this._onbuttonup && newValue === 0) {
  20465. this._onbuttonup(buttonIndex);
  20466. }
  20467. }
  20468. return newValue;
  20469. };
  20470. GenericPad.prototype.update = function () {
  20471. _super.prototype.update.call(this);
  20472. for (var index = 0; index < this._buttons.length; index++) {
  20473. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  20474. }
  20475. };
  20476. return GenericPad;
  20477. })(Gamepad);
  20478. BABYLON.GenericPad = GenericPad;
  20479. (function (Xbox360Button) {
  20480. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  20481. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  20482. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  20483. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  20484. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  20485. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  20486. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  20487. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  20488. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  20489. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  20490. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  20491. var Xbox360Button = BABYLON.Xbox360Button;
  20492. (function (Xbox360Dpad) {
  20493. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  20494. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  20495. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  20496. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  20497. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  20498. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  20499. var Xbox360Pad = (function (_super) {
  20500. __extends(Xbox360Pad, _super);
  20501. function Xbox360Pad() {
  20502. _super.apply(this, arguments);
  20503. this._leftTrigger = 0;
  20504. this._rightTrigger = 0;
  20505. this._buttonA = 0;
  20506. this._buttonB = 0;
  20507. this._buttonX = 0;
  20508. this._buttonY = 0;
  20509. this._buttonBack = 0;
  20510. this._buttonStart = 0;
  20511. this._buttonLB = 0;
  20512. this._buttonRB = 0;
  20513. this._buttonLeftStick = 0;
  20514. this._buttonRightStick = 0;
  20515. this._dPadUp = 0;
  20516. this._dPadDown = 0;
  20517. this._dPadLeft = 0;
  20518. this._dPadRight = 0;
  20519. }
  20520. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  20521. this._onlefttriggerchanged = callback;
  20522. };
  20523. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  20524. this._onrighttriggerchanged = callback;
  20525. };
  20526. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  20527. get: function () {
  20528. return this._leftTrigger;
  20529. },
  20530. set: function (newValue) {
  20531. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  20532. this._onlefttriggerchanged(newValue);
  20533. }
  20534. this._leftTrigger = newValue;
  20535. },
  20536. enumerable: true,
  20537. configurable: true
  20538. });
  20539. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  20540. get: function () {
  20541. return this._rightTrigger;
  20542. },
  20543. set: function (newValue) {
  20544. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  20545. this._onrighttriggerchanged(newValue);
  20546. }
  20547. this._rightTrigger = newValue;
  20548. },
  20549. enumerable: true,
  20550. configurable: true
  20551. });
  20552. Xbox360Pad.prototype.onbuttondown = function (callback) {
  20553. this._onbuttondown = callback;
  20554. };
  20555. Xbox360Pad.prototype.onbuttonup = function (callback) {
  20556. this._onbuttonup = callback;
  20557. };
  20558. Xbox360Pad.prototype.ondpaddown = function (callback) {
  20559. this._ondpaddown = callback;
  20560. };
  20561. Xbox360Pad.prototype.ondpadup = function (callback) {
  20562. this._ondpadup = callback;
  20563. };
  20564. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  20565. if (newValue !== currentValue) {
  20566. if (this._onbuttondown && newValue === 1) {
  20567. this._onbuttondown(buttonType);
  20568. }
  20569. if (this._onbuttonup && newValue === 0) {
  20570. this._onbuttonup(buttonType);
  20571. }
  20572. }
  20573. return newValue;
  20574. };
  20575. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  20576. if (newValue !== currentValue) {
  20577. if (this._ondpaddown && newValue === 1) {
  20578. this._ondpaddown(buttonType);
  20579. }
  20580. if (this._ondpadup && newValue === 0) {
  20581. this._ondpadup(buttonType);
  20582. }
  20583. }
  20584. return newValue;
  20585. };
  20586. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  20587. get: function () {
  20588. return this._buttonA;
  20589. },
  20590. set: function (value) {
  20591. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  20592. },
  20593. enumerable: true,
  20594. configurable: true
  20595. });
  20596. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  20597. get: function () {
  20598. return this._buttonB;
  20599. },
  20600. set: function (value) {
  20601. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  20602. },
  20603. enumerable: true,
  20604. configurable: true
  20605. });
  20606. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  20607. get: function () {
  20608. return this._buttonX;
  20609. },
  20610. set: function (value) {
  20611. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  20612. },
  20613. enumerable: true,
  20614. configurable: true
  20615. });
  20616. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  20617. get: function () {
  20618. return this._buttonY;
  20619. },
  20620. set: function (value) {
  20621. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  20622. },
  20623. enumerable: true,
  20624. configurable: true
  20625. });
  20626. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  20627. get: function () {
  20628. return this._buttonStart;
  20629. },
  20630. set: function (value) {
  20631. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  20632. },
  20633. enumerable: true,
  20634. configurable: true
  20635. });
  20636. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  20637. get: function () {
  20638. return this._buttonBack;
  20639. },
  20640. set: function (value) {
  20641. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  20642. },
  20643. enumerable: true,
  20644. configurable: true
  20645. });
  20646. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  20647. get: function () {
  20648. return this._buttonLB;
  20649. },
  20650. set: function (value) {
  20651. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  20652. },
  20653. enumerable: true,
  20654. configurable: true
  20655. });
  20656. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  20657. get: function () {
  20658. return this._buttonRB;
  20659. },
  20660. set: function (value) {
  20661. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  20662. },
  20663. enumerable: true,
  20664. configurable: true
  20665. });
  20666. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  20667. get: function () {
  20668. return this._buttonLeftStick;
  20669. },
  20670. set: function (value) {
  20671. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  20672. },
  20673. enumerable: true,
  20674. configurable: true
  20675. });
  20676. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  20677. get: function () {
  20678. return this._buttonRightStick;
  20679. },
  20680. set: function (value) {
  20681. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  20682. },
  20683. enumerable: true,
  20684. configurable: true
  20685. });
  20686. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  20687. get: function () {
  20688. return this._dPadUp;
  20689. },
  20690. set: function (value) {
  20691. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  20692. },
  20693. enumerable: true,
  20694. configurable: true
  20695. });
  20696. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  20697. get: function () {
  20698. return this._dPadDown;
  20699. },
  20700. set: function (value) {
  20701. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  20702. },
  20703. enumerable: true,
  20704. configurable: true
  20705. });
  20706. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  20707. get: function () {
  20708. return this._dPadLeft;
  20709. },
  20710. set: function (value) {
  20711. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  20712. },
  20713. enumerable: true,
  20714. configurable: true
  20715. });
  20716. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  20717. get: function () {
  20718. return this._dPadRight;
  20719. },
  20720. set: function (value) {
  20721. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  20722. },
  20723. enumerable: true,
  20724. configurable: true
  20725. });
  20726. Xbox360Pad.prototype.update = function () {
  20727. _super.prototype.update.call(this);
  20728. this.buttonA = this.browserGamepad.buttons[0].value;
  20729. this.buttonB = this.browserGamepad.buttons[1].value;
  20730. this.buttonX = this.browserGamepad.buttons[2].value;
  20731. this.buttonY = this.browserGamepad.buttons[3].value;
  20732. this.buttonLB = this.browserGamepad.buttons[4].value;
  20733. this.buttonRB = this.browserGamepad.buttons[5].value;
  20734. this.leftTrigger = this.browserGamepad.buttons[6].value;
  20735. this.rightTrigger = this.browserGamepad.buttons[7].value;
  20736. this.buttonBack = this.browserGamepad.buttons[8].value;
  20737. this.buttonStart = this.browserGamepad.buttons[9].value;
  20738. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  20739. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  20740. this.dPadUp = this.browserGamepad.buttons[12].value;
  20741. this.dPadDown = this.browserGamepad.buttons[13].value;
  20742. this.dPadLeft = this.browserGamepad.buttons[14].value;
  20743. this.dPadRight = this.browserGamepad.buttons[15].value;
  20744. };
  20745. return Xbox360Pad;
  20746. })(Gamepad);
  20747. BABYLON.Xbox360Pad = Xbox360Pad;
  20748. })(BABYLON || (BABYLON = {}));
  20749. var __extends = this.__extends || function (d, b) {
  20750. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20751. function __() { this.constructor = d; }
  20752. __.prototype = b.prototype;
  20753. d.prototype = new __();
  20754. };
  20755. var BABYLON;
  20756. (function (BABYLON) {
  20757. var GamepadCamera = (function (_super) {
  20758. __extends(GamepadCamera, _super);
  20759. function GamepadCamera(name, position, scene) {
  20760. var _this = this;
  20761. _super.call(this, name, position, scene);
  20762. this.angularSensibility = 200;
  20763. this.moveSensibility = 75;
  20764. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  20765. _this._onNewGameConnected(gamepad);
  20766. });
  20767. }
  20768. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  20769. if (gamepad.index === 0) {
  20770. this._gamepad = gamepad;
  20771. }
  20772. };
  20773. GamepadCamera.prototype._checkInputs = function () {
  20774. if (!this._gamepad) {
  20775. return;
  20776. }
  20777. var LSValues = this._gamepad.leftStick;
  20778. var normalizedLX = LSValues.x / this.moveSensibility;
  20779. var normalizedLY = LSValues.y / this.moveSensibility;
  20780. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  20781. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  20782. var RSValues = this._gamepad.rightStick;
  20783. var normalizedRX = RSValues.x / this.angularSensibility;
  20784. var normalizedRY = RSValues.y / this.angularSensibility;
  20785. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  20786. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  20787. ;
  20788. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20789. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  20790. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20791. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  20792. };
  20793. GamepadCamera.prototype.dispose = function () {
  20794. this._gamepads.dispose();
  20795. _super.prototype.dispose.call(this);
  20796. };
  20797. return GamepadCamera;
  20798. })(BABYLON.FreeCamera);
  20799. BABYLON.GamepadCamera = GamepadCamera;
  20800. })(BABYLON || (BABYLON = {}));
  20801. var __extends = this.__extends || function (d, b) {
  20802. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20803. function __() { this.constructor = d; }
  20804. __.prototype = b.prototype;
  20805. d.prototype = new __();
  20806. };
  20807. var BABYLON;
  20808. (function (BABYLON) {
  20809. var LinesMesh = (function (_super) {
  20810. __extends(LinesMesh, _super);
  20811. function LinesMesh(name, scene, updatable) {
  20812. if (typeof updatable === "undefined") { updatable = false; }
  20813. _super.call(this, name, scene);
  20814. this.color = new BABYLON.Color3(1, 1, 1);
  20815. this.alpha = 1;
  20816. this._indices = new Array();
  20817. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  20818. attributes: ["position"],
  20819. uniforms: ["worldViewProjection", "color"],
  20820. needAlphaBlending: true
  20821. });
  20822. }
  20823. Object.defineProperty(LinesMesh.prototype, "material", {
  20824. get: function () {
  20825. return this._colorShader;
  20826. },
  20827. enumerable: true,
  20828. configurable: true
  20829. });
  20830. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  20831. get: function () {
  20832. return false;
  20833. },
  20834. enumerable: true,
  20835. configurable: true
  20836. });
  20837. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  20838. get: function () {
  20839. return false;
  20840. },
  20841. enumerable: true,
  20842. configurable: true
  20843. });
  20844. LinesMesh.prototype._bind = function (subMesh, effect, wireframe) {
  20845. var engine = this.getScene().getEngine();
  20846. var indexToBind = this._geometry.getIndexBuffer();
  20847. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  20848. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  20849. };
  20850. LinesMesh.prototype._draw = function (subMesh, useTriangles, instancesCount) {
  20851. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20852. return;
  20853. }
  20854. var engine = this.getScene().getEngine();
  20855. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  20856. };
  20857. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  20858. return null;
  20859. };
  20860. LinesMesh.prototype.dispose = function (doNotRecurse) {
  20861. this._colorShader.dispose();
  20862. _super.prototype.dispose.call(this, doNotRecurse);
  20863. };
  20864. return LinesMesh;
  20865. })(BABYLON.Mesh);
  20866. BABYLON.LinesMesh = LinesMesh;
  20867. })(BABYLON || (BABYLON = {}));
  20868. var BABYLON;
  20869. (function (BABYLON) {
  20870. var OutlineRenderer = (function () {
  20871. function OutlineRenderer(scene) {
  20872. this._scene = scene;
  20873. }
  20874. OutlineRenderer.prototype.render = function (subMesh, batch) {
  20875. var scene = this._scene;
  20876. var engine = this._scene.getEngine();
  20877. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  20878. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  20879. return;
  20880. }
  20881. var mesh = subMesh.getRenderingMesh();
  20882. var material = subMesh.getMaterial();
  20883. engine.enableEffect(this._effect);
  20884. this._effect.setFloat("offset", mesh.outlineWidth);
  20885. this._effect.setColor3("color", mesh.outlineColor);
  20886. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  20887. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  20888. if (useBones) {
  20889. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  20890. }
  20891. mesh._bind(subMesh, this._effect, false);
  20892. if (material && material.needAlphaTesting()) {
  20893. var alphaTexture = material.getAlphaTestTexture();
  20894. this._effect.setTexture("diffuseSampler", alphaTexture);
  20895. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  20896. }
  20897. if (hardwareInstancedRendering) {
  20898. mesh._renderWithInstances(subMesh, false, batch, this._effect, engine);
  20899. } else {
  20900. if (batch.renderSelf[subMesh._id]) {
  20901. this._effect.setMatrix("world", mesh.getWorldMatrix());
  20902. mesh._draw(subMesh, true);
  20903. }
  20904. if (batch.visibleInstances[subMesh._id]) {
  20905. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20906. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20907. this._effect.setMatrix("world", instance.getWorldMatrix());
  20908. mesh._draw(subMesh, true);
  20909. }
  20910. }
  20911. }
  20912. };
  20913. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  20914. var defines = [];
  20915. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  20916. var mesh = subMesh.getMesh();
  20917. var material = subMesh.getMaterial();
  20918. if (material && material.needAlphaTesting()) {
  20919. defines.push("#define ALPHATEST");
  20920. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20921. attribs.push(BABYLON.VertexBuffer.UVKind);
  20922. defines.push("#define UV1");
  20923. }
  20924. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20925. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  20926. defines.push("#define UV2");
  20927. }
  20928. }
  20929. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20930. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20931. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20932. defines.push("#define BONES");
  20933. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  20934. }
  20935. if (useInstances) {
  20936. defines.push("#define INSTANCES");
  20937. attribs.push("world0");
  20938. attribs.push("world1");
  20939. attribs.push("world2");
  20940. attribs.push("world3");
  20941. }
  20942. var join = defines.join("\n");
  20943. if (this._cachedDefines != join) {
  20944. this._cachedDefines = join;
  20945. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  20946. }
  20947. return this._effect.isReady();
  20948. };
  20949. return OutlineRenderer;
  20950. })();
  20951. BABYLON.OutlineRenderer = OutlineRenderer;
  20952. })(BABYLON || (BABYLON = {}));
  20953. var BABYLON;
  20954. (function (BABYLON) {
  20955. var MeshAssetTask = (function () {
  20956. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  20957. this.name = name;
  20958. this.meshesNames = meshesNames;
  20959. this.rootUrl = rootUrl;
  20960. this.sceneFilename = sceneFilename;
  20961. this.isCompleted = false;
  20962. }
  20963. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20964. var _this = this;
  20965. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  20966. _this.loadedMeshes = meshes;
  20967. _this.loadedParticleSystems = particleSystems;
  20968. _this.loadedSkeletons = skeletons;
  20969. _this.isCompleted = true;
  20970. if (_this.onSuccess) {
  20971. _this.onSuccess(_this);
  20972. }
  20973. onSuccess();
  20974. }, null, function () {
  20975. if (_this.onError) {
  20976. _this.onError(_this);
  20977. }
  20978. onError();
  20979. });
  20980. };
  20981. return MeshAssetTask;
  20982. })();
  20983. BABYLON.MeshAssetTask = MeshAssetTask;
  20984. var TextFileAssetTask = (function () {
  20985. function TextFileAssetTask(name, url) {
  20986. this.name = name;
  20987. this.url = url;
  20988. this.isCompleted = false;
  20989. }
  20990. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  20991. var _this = this;
  20992. BABYLON.Tools.LoadFile(this.url, function (data) {
  20993. _this.text = data;
  20994. _this.isCompleted = true;
  20995. if (_this.onSuccess) {
  20996. _this.onSuccess(_this);
  20997. }
  20998. onSuccess();
  20999. }, null, scene.database, false, function () {
  21000. if (_this.onError) {
  21001. _this.onError(_this);
  21002. }
  21003. onError();
  21004. });
  21005. };
  21006. return TextFileAssetTask;
  21007. })();
  21008. BABYLON.TextFileAssetTask = TextFileAssetTask;
  21009. var BinaryFileAssetTask = (function () {
  21010. function BinaryFileAssetTask(name, url) {
  21011. this.name = name;
  21012. this.url = url;
  21013. this.isCompleted = false;
  21014. }
  21015. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21016. var _this = this;
  21017. BABYLON.Tools.LoadFile(this.url, function (data) {
  21018. _this.data = data;
  21019. _this.isCompleted = true;
  21020. if (_this.onSuccess) {
  21021. _this.onSuccess(_this);
  21022. }
  21023. onSuccess();
  21024. }, null, scene.database, true, function () {
  21025. if (_this.onError) {
  21026. _this.onError(_this);
  21027. }
  21028. onError();
  21029. });
  21030. };
  21031. return BinaryFileAssetTask;
  21032. })();
  21033. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  21034. var ImageAssetTask = (function () {
  21035. function ImageAssetTask(name, url) {
  21036. this.name = name;
  21037. this.url = url;
  21038. this.isCompleted = false;
  21039. }
  21040. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21041. var _this = this;
  21042. var img = new Image();
  21043. img.onload = function () {
  21044. _this.image = img;
  21045. _this.isCompleted = true;
  21046. if (_this.onSuccess) {
  21047. _this.onSuccess(_this);
  21048. }
  21049. onSuccess();
  21050. };
  21051. img.onerror = function () {
  21052. if (_this.onError) {
  21053. _this.onError(_this);
  21054. }
  21055. onError();
  21056. };
  21057. img.src = this.url;
  21058. };
  21059. return ImageAssetTask;
  21060. })();
  21061. BABYLON.ImageAssetTask = ImageAssetTask;
  21062. var TextureAssetTask = (function () {
  21063. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  21064. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21065. this.name = name;
  21066. this.url = url;
  21067. this.noMipmap = noMipmap;
  21068. this.invertY = invertY;
  21069. this.samplingMode = samplingMode;
  21070. this.isCompleted = false;
  21071. }
  21072. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21073. var _this = this;
  21074. var onload = function () {
  21075. _this.isCompleted = true;
  21076. if (_this.onSuccess) {
  21077. _this.onSuccess(_this);
  21078. }
  21079. onSuccess();
  21080. };
  21081. var onerror = function () {
  21082. if (_this.onError) {
  21083. _this.onError(_this);
  21084. }
  21085. onError();
  21086. };
  21087. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  21088. };
  21089. return TextureAssetTask;
  21090. })();
  21091. BABYLON.TextureAssetTask = TextureAssetTask;
  21092. var AssetsManager = (function () {
  21093. function AssetsManager(scene) {
  21094. this._tasks = new Array();
  21095. this._waitingTasksCount = 0;
  21096. this.useDefaultLoadingScreen = true;
  21097. this._scene = scene;
  21098. }
  21099. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  21100. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  21101. this._tasks.push(task);
  21102. return task;
  21103. };
  21104. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  21105. var task = new TextFileAssetTask(taskName, url);
  21106. this._tasks.push(task);
  21107. return task;
  21108. };
  21109. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  21110. var task = new BinaryFileAssetTask(taskName, url);
  21111. this._tasks.push(task);
  21112. return task;
  21113. };
  21114. AssetsManager.prototype.addImageTask = function (taskName, url) {
  21115. var task = new ImageAssetTask(taskName, url);
  21116. this._tasks.push(task);
  21117. return task;
  21118. };
  21119. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  21120. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21121. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  21122. this._tasks.push(task);
  21123. return task;
  21124. };
  21125. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  21126. this._waitingTasksCount--;
  21127. if (this._waitingTasksCount === 0) {
  21128. if (this.onFinish) {
  21129. this.onFinish(this._tasks);
  21130. }
  21131. this._scene.getEngine().hideLoadingUI();
  21132. }
  21133. };
  21134. AssetsManager.prototype._runTask = function (task) {
  21135. var _this = this;
  21136. task.run(this._scene, function () {
  21137. if (_this.onTaskSuccess) {
  21138. _this.onTaskSuccess(task);
  21139. }
  21140. _this._decreaseWaitingTasksCount();
  21141. }, function () {
  21142. if (_this.onTaskError) {
  21143. _this.onTaskError(task);
  21144. }
  21145. _this._decreaseWaitingTasksCount();
  21146. });
  21147. };
  21148. AssetsManager.prototype.reset = function () {
  21149. this._tasks = new Array();
  21150. return this;
  21151. };
  21152. AssetsManager.prototype.load = function () {
  21153. this._waitingTasksCount = this._tasks.length;
  21154. if (this._waitingTasksCount === 0) {
  21155. if (this.onFinish) {
  21156. this.onFinish(this._tasks);
  21157. }
  21158. return this;
  21159. }
  21160. if (this.useDefaultLoadingScreen) {
  21161. this._scene.getEngine().displayLoadingUI();
  21162. }
  21163. for (var index = 0; index < this._tasks.length; index++) {
  21164. var task = this._tasks[index];
  21165. this._runTask(task);
  21166. }
  21167. return this;
  21168. };
  21169. return AssetsManager;
  21170. })();
  21171. BABYLON.AssetsManager = AssetsManager;
  21172. })(BABYLON || (BABYLON = {}));
  21173. var __extends = this.__extends || function (d, b) {
  21174. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21175. function __() { this.constructor = d; }
  21176. __.prototype = b.prototype;
  21177. d.prototype = new __();
  21178. };
  21179. var BABYLON;
  21180. (function (BABYLON) {
  21181. var VRDeviceOrientationCamera = (function (_super) {
  21182. __extends(VRDeviceOrientationCamera, _super);
  21183. function VRDeviceOrientationCamera(name, position, scene) {
  21184. _super.call(this, name, position, scene);
  21185. this._alpha = 0;
  21186. this._beta = 0;
  21187. this._gamma = 0;
  21188. }
  21189. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  21190. this._alpha = +evt.alpha | 0;
  21191. this._beta = +evt.beta | 0;
  21192. this._gamma = +evt.gamma | 0;
  21193. if (this._gamma < 0) {
  21194. this._gamma = 90 + this._gamma;
  21195. } else {
  21196. this._gamma = 270 - this._gamma;
  21197. }
  21198. this.rotation.x = this._gamma / 180.0 * Math.PI;
  21199. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  21200. this.rotation.z = this._beta / 180.0 * Math.PI;
  21201. };
  21202. return VRDeviceOrientationCamera;
  21203. })(BABYLON.OculusCamera);
  21204. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  21205. })(BABYLON || (BABYLON = {}));
  21206. var __extends = this.__extends || function (d, b) {
  21207. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21208. function __() { this.constructor = d; }
  21209. __.prototype = b.prototype;
  21210. d.prototype = new __();
  21211. };
  21212. var BABYLON;
  21213. (function (BABYLON) {
  21214. var WebVRCamera = (function (_super) {
  21215. __extends(WebVRCamera, _super);
  21216. function WebVRCamera(name, position, scene) {
  21217. _super.call(this, name, position, scene);
  21218. this._hmdDevice = null;
  21219. this._sensorDevice = null;
  21220. this._cacheState = null;
  21221. this._cacheQuaternion = new BABYLON.Quaternion();
  21222. this._cacheRotation = BABYLON.Vector3.Zero();
  21223. this._vrEnabled = false;
  21224. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  21225. }
  21226. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  21227. var size = devices.length;
  21228. var i = 0;
  21229. this._sensorDevice = null;
  21230. this._hmdDevice = null;
  21231. while (i < size && this._hmdDevice === null) {
  21232. if (devices[i] instanceof HMDVRDevice) {
  21233. this._hmdDevice = devices[i];
  21234. }
  21235. i++;
  21236. }
  21237. i = 0;
  21238. while (i < size && this._sensorDevice === null) {
  21239. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  21240. this._sensorDevice = devices[i];
  21241. }
  21242. i++;
  21243. }
  21244. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  21245. };
  21246. WebVRCamera.prototype._update = function () {
  21247. if (this._vrEnabled) {
  21248. this._cacheState = this._sensorDevice.getState();
  21249. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  21250. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  21251. this.rotation.x = -this._cacheRotation.z;
  21252. this.rotation.y = -this._cacheRotation.y;
  21253. this.rotation.z = this._cacheRotation.x;
  21254. }
  21255. _super.prototype._update.call(this);
  21256. };
  21257. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  21258. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21259. if (navigator.getVRDevices) {
  21260. navigator.getVRDevices().then(this._getWebVRDevices);
  21261. } else if (navigator.mozGetVRDevices) {
  21262. navigator.mozGetVRDevices(this._getWebVRDevices);
  21263. }
  21264. };
  21265. WebVRCamera.prototype.detachControl = function (element) {
  21266. _super.prototype.detachControl.call(this, element);
  21267. this._vrEnabled = false;
  21268. };
  21269. return WebVRCamera;
  21270. })(BABYLON.OculusCamera);
  21271. BABYLON.WebVRCamera = WebVRCamera;
  21272. })(BABYLON || (BABYLON = {}));
  21273. var __extends = this.__extends || function (d, b) {
  21274. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21275. function __() { this.constructor = d; }
  21276. __.prototype = b.prototype;
  21277. d.prototype = new __();
  21278. };
  21279. var BABYLON;
  21280. (function (BABYLON) {
  21281. var SceneOptimization = (function () {
  21282. function SceneOptimization(priority) {
  21283. if (typeof priority === "undefined") { priority = 0; }
  21284. this.priority = priority;
  21285. this.apply = function (scene) {
  21286. return true;
  21287. };
  21288. }
  21289. return SceneOptimization;
  21290. })();
  21291. BABYLON.SceneOptimization = SceneOptimization;
  21292. var TextureSceneOptimization = (function (_super) {
  21293. __extends(TextureSceneOptimization, _super);
  21294. function TextureSceneOptimization(priority, maximumSize) {
  21295. if (typeof priority === "undefined") { priority = 0; }
  21296. if (typeof maximumSize === "undefined") { maximumSize = 1024; }
  21297. var _this = this;
  21298. _super.call(this, priority);
  21299. this.priority = priority;
  21300. this.maximumSize = maximumSize;
  21301. this.apply = function (scene) {
  21302. var allDone = true;
  21303. for (var index = 0; index < scene.textures.length; index++) {
  21304. var texture = scene.textures[index];
  21305. if (!texture.canRescale) {
  21306. continue;
  21307. }
  21308. var currentSize = texture.getSize();
  21309. var maxDimension = Math.max(currentSize.width, currentSize.height);
  21310. if (maxDimension > _this.maximumSize) {
  21311. texture.scale(0.5);
  21312. allDone = false;
  21313. }
  21314. }
  21315. return allDone;
  21316. };
  21317. }
  21318. return TextureSceneOptimization;
  21319. })(SceneOptimization);
  21320. BABYLON.TextureSceneOptimization = TextureSceneOptimization;
  21321. var HardwareScalingSceneOptimization = (function (_super) {
  21322. __extends(HardwareScalingSceneOptimization, _super);
  21323. function HardwareScalingSceneOptimization(priority, maximumScale) {
  21324. if (typeof priority === "undefined") { priority = 0; }
  21325. if (typeof maximumScale === "undefined") { maximumScale = 2; }
  21326. var _this = this;
  21327. _super.call(this, priority);
  21328. this.priority = priority;
  21329. this.maximumScale = maximumScale;
  21330. this._currentScale = 1;
  21331. this.apply = function (scene) {
  21332. _this._currentScale++;
  21333. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  21334. return _this._currentScale >= _this.maximumScale;
  21335. };
  21336. }
  21337. return HardwareScalingSceneOptimization;
  21338. })(SceneOptimization);
  21339. BABYLON.HardwareScalingSceneOptimization = HardwareScalingSceneOptimization;
  21340. var ShadowsSceneOptimization = (function (_super) {
  21341. __extends(ShadowsSceneOptimization, _super);
  21342. function ShadowsSceneOptimization() {
  21343. _super.apply(this, arguments);
  21344. this.apply = function (scene) {
  21345. scene.shadowsEnabled = false;
  21346. return true;
  21347. };
  21348. }
  21349. return ShadowsSceneOptimization;
  21350. })(SceneOptimization);
  21351. BABYLON.ShadowsSceneOptimization = ShadowsSceneOptimization;
  21352. var PostProcessesSceneOptimization = (function (_super) {
  21353. __extends(PostProcessesSceneOptimization, _super);
  21354. function PostProcessesSceneOptimization() {
  21355. _super.apply(this, arguments);
  21356. this.apply = function (scene) {
  21357. scene.postProcessesEnabled = false;
  21358. return true;
  21359. };
  21360. }
  21361. return PostProcessesSceneOptimization;
  21362. })(SceneOptimization);
  21363. BABYLON.PostProcessesSceneOptimization = PostProcessesSceneOptimization;
  21364. var LensFlaresSceneOptimization = (function (_super) {
  21365. __extends(LensFlaresSceneOptimization, _super);
  21366. function LensFlaresSceneOptimization() {
  21367. _super.apply(this, arguments);
  21368. this.apply = function (scene) {
  21369. scene.lensFlaresEnabled = false;
  21370. return true;
  21371. };
  21372. }
  21373. return LensFlaresSceneOptimization;
  21374. })(SceneOptimization);
  21375. BABYLON.LensFlaresSceneOptimization = LensFlaresSceneOptimization;
  21376. var ParticlesSceneOptimization = (function (_super) {
  21377. __extends(ParticlesSceneOptimization, _super);
  21378. function ParticlesSceneOptimization() {
  21379. _super.apply(this, arguments);
  21380. this.apply = function (scene) {
  21381. scene.particlesEnabled = false;
  21382. return true;
  21383. };
  21384. }
  21385. return ParticlesSceneOptimization;
  21386. })(SceneOptimization);
  21387. BABYLON.ParticlesSceneOptimization = ParticlesSceneOptimization;
  21388. var RenderTargetsSceneOptimization = (function (_super) {
  21389. __extends(RenderTargetsSceneOptimization, _super);
  21390. function RenderTargetsSceneOptimization() {
  21391. _super.apply(this, arguments);
  21392. this.apply = function (scene) {
  21393. scene.renderTargetsEnabled = false;
  21394. return true;
  21395. };
  21396. }
  21397. return RenderTargetsSceneOptimization;
  21398. })(SceneOptimization);
  21399. BABYLON.RenderTargetsSceneOptimization = RenderTargetsSceneOptimization;
  21400. var SceneOptimizerOptions = (function () {
  21401. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  21402. if (typeof targetFrameRate === "undefined") { targetFrameRate = 60; }
  21403. if (typeof trackerDuration === "undefined") { trackerDuration = 2000; }
  21404. this.targetFrameRate = targetFrameRate;
  21405. this.trackerDuration = trackerDuration;
  21406. this.optimizations = new Array();
  21407. }
  21408. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  21409. var result = new SceneOptimizerOptions(targetFrameRate);
  21410. var priority = 0;
  21411. result.optimizations.push(new ShadowsSceneOptimization(priority));
  21412. result.optimizations.push(new LensFlaresSceneOptimization(priority));
  21413. priority++;
  21414. result.optimizations.push(new PostProcessesSceneOptimization(priority));
  21415. result.optimizations.push(new ParticlesSceneOptimization(priority));
  21416. priority++;
  21417. result.optimizations.push(new TextureSceneOptimization(priority, 1024));
  21418. return result;
  21419. };
  21420. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  21421. var result = new SceneOptimizerOptions(targetFrameRate);
  21422. var priority = 0;
  21423. result.optimizations.push(new ShadowsSceneOptimization(priority));
  21424. result.optimizations.push(new LensFlaresSceneOptimization(priority));
  21425. priority++;
  21426. result.optimizations.push(new PostProcessesSceneOptimization(priority));
  21427. result.optimizations.push(new ParticlesSceneOptimization(priority));
  21428. priority++;
  21429. result.optimizations.push(new TextureSceneOptimization(priority, 512));
  21430. priority++;
  21431. result.optimizations.push(new RenderTargetsSceneOptimization(priority));
  21432. priority++;
  21433. result.optimizations.push(new HardwareScalingSceneOptimization(priority, 2));
  21434. return result;
  21435. };
  21436. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  21437. var result = new SceneOptimizerOptions(targetFrameRate);
  21438. var priority = 0;
  21439. result.optimizations.push(new ShadowsSceneOptimization(priority));
  21440. result.optimizations.push(new LensFlaresSceneOptimization(priority));
  21441. priority++;
  21442. result.optimizations.push(new PostProcessesSceneOptimization(priority));
  21443. result.optimizations.push(new ParticlesSceneOptimization(priority));
  21444. priority++;
  21445. result.optimizations.push(new TextureSceneOptimization(priority, 256));
  21446. priority++;
  21447. result.optimizations.push(new RenderTargetsSceneOptimization(priority));
  21448. priority++;
  21449. result.optimizations.push(new HardwareScalingSceneOptimization(priority, 4));
  21450. return result;
  21451. };
  21452. return SceneOptimizerOptions;
  21453. })();
  21454. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  21455. var SceneOptimizer = (function () {
  21456. function SceneOptimizer() {
  21457. }
  21458. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  21459. if (BABYLON.Tools.GetFps() >= options.targetFrameRate) {
  21460. if (onSuccess) {
  21461. onSuccess();
  21462. }
  21463. return;
  21464. }
  21465. var allDone = true;
  21466. var noOptimizationApplied = true;
  21467. for (var index = 0; index < options.optimizations.length; index++) {
  21468. var optimization = options.optimizations[index];
  21469. if (optimization.priority === currentPriorityLevel) {
  21470. noOptimizationApplied = false;
  21471. allDone = allDone && optimization.apply(scene);
  21472. }
  21473. }
  21474. if (noOptimizationApplied) {
  21475. if (onFailure) {
  21476. onFailure();
  21477. }
  21478. return;
  21479. }
  21480. if (allDone) {
  21481. currentPriorityLevel++;
  21482. }
  21483. scene.executeWhenReady(function () {
  21484. setTimeout(function () {
  21485. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  21486. }, options.trackerDuration);
  21487. });
  21488. };
  21489. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  21490. if (!options) {
  21491. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  21492. }
  21493. scene.executeWhenReady(function () {
  21494. setTimeout(function () {
  21495. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  21496. }, options.trackerDuration);
  21497. });
  21498. };
  21499. return SceneOptimizer;
  21500. })();
  21501. BABYLON.SceneOptimizer = SceneOptimizer;
  21502. })(BABYLON || (BABYLON = {}));